blob: 06c56a05d42a6e2105a737dd5564bd18af432052 [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;
yuemingw1d13eae2018-01-30 17:27:54 +000034import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000042import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010044import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070045import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060047import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080048import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080049import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.os.Environment;
51import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080053import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000054import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090067import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000068import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070069import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070070import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010071import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080073import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010074import android.os.storage.StorageManager;
yuemingw1d13eae2018-01-30 17:27:54 +000075import android.provider.Settings;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070076import android.security.GateKeeper;
77import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Makoto Onuki73dded22017-12-20 13:14:48 +090085import android.util.SparseLongArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070086import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087import android.util.Xml;
88
Makoto Onuki068c54a2015-10-13 14:34:03 -070089import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070090import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040091import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080092import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080093import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060094import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080095import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070096import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070097import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000098import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070099import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600100import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700101import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000102import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700103import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100104
Jeff Sharkey47f71082016-02-01 17:03:54 -0700105import libcore.io.IoUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800106
107import org.xmlpull.v1.XmlPullParser;
108import org.xmlpull.v1.XmlPullParserException;
109import org.xmlpull.v1.XmlSerializer;
110
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.BufferedOutputStream;
112import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700113import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700115import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000117import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000118import java.io.InputStream;
119import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700120import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100121import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100123import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700124import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000126import java.util.Objects;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127
Makoto Onuki068c54a2015-10-13 14:34:03 -0700128/**
129 * Service for {@link UserManager}.
130 *
131 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700132 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700133 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800134 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700135 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
136 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
137 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700138 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700139public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700140
Amith Yamasani2a003292012-08-14 18:25:45 -0700141 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800142 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800143 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700144 // Can be used for manual testing of id recycling
145 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700146
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800148 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700150 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700152 private static final String ATTR_CREATION_TIME = "created";
153 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600154 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700155 private static final String ATTR_SERIAL_NO = "serialNumber";
156 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700157 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700158 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700159 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100160 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000161 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700162 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800163 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
164 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530165 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800168 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800169 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100170 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
171 "device_policy_global_restrictions";
172 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100173 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100174 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800175 private static final String TAG_ENTRY = "entry";
176 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800177 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700179 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800180 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700181
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700182 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
183 private static final String ATTR_TYPE_STRING = "s";
184 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700185 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700186 private static final String ATTR_TYPE_BUNDLE = "B";
187 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700188
Amith Yamasani0b285492011-04-14 17:35:23 -0700189 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700191 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100192 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700193
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800194 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700195 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800196
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700197 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
198 UserInfo.FLAG_MANAGED_PROFILE
199 | UserInfo.FLAG_EPHEMERAL
200 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700201 | UserInfo.FLAG_GUEST
202 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700203
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700204 @VisibleForTesting
205 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700206 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700207 @VisibleForTesting
208 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
209
210 // Max size of the queue of recently removed users
211 @VisibleForTesting
212 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700213
Pavel Grafov6a40f092016-10-25 15:46:51 +0100214 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700215
Amith Yamasani920ace02012-09-20 22:15:37 -0700216 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
217
Nicolas Prevotb8186812015-08-06 15:00:03 +0100218 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700219 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000220 @VisibleForTesting
221 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700222
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800223 static final int WRITE_USER_MSG = 1;
224 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530225
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800226 // Tron counters
227 private static final String TRON_GUEST_CREATED = "users_guest_created";
228 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700229 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800230
Dianne Hackborn4428e172012-08-24 17:43:05 -0700231 private final Context mContext;
232 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700233 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800234 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700235 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600236 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700237 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700238 // Used for serializing access to app restriction files
239 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700240
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800241 private final Handler mHandler;
242
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700243 private final File mUsersDir;
244 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700245
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800246 private static final IBinder mUserRestriconToken = new Binder();
247
Makoto Onuki068c54a2015-10-13 14:34:03 -0700248 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900249 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800250 */
Kenny Guy02c89902016-11-15 19:36:38 +0000251 @VisibleForTesting
252 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800253 // Basic user information and properties
254 UserInfo info;
255 // Account name used when there is a strong association between a user and an account
256 String account;
257 // Account information for seeding into a newly created user. This could also be
258 // used for login validation for an existing user, for updating their credentials.
259 // In the latter case, data may not need to be persisted as it is only valid for the
260 // current login session.
261 String seedAccountName;
262 String seedAccountType;
263 PersistableBundle seedAccountOptions;
264 // Whether to perist the seed account information to be available after a boot
265 boolean persistSeedData;
266
Makoto Onuki73dded22017-12-20 13:14:48 +0900267 /** Elapsed realtime since boot when the user started. */
268 long startRealtime;
269
270 /** Elapsed realtime since boot when the user was unlocked. */
271 long unlockRealtime;
272
Amith Yamasani12747872015-12-07 14:19:49 -0800273 void clearSeedAccountData() {
274 seedAccountName = null;
275 seedAccountType = null;
276 seedAccountOptions = null;
277 persistSeedData = false;
278 }
279 }
280
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800281 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800282 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800283
284 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700285 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100286 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700287 *
288 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
289 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
290 * maybe shared between {@link #mBaseUserRestrictions} and
291 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
292 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700293 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700294 */
295 @GuardedBy("mRestrictionsLock")
296 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
297
298 /**
299 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
300 * with device / profile owner restrictions. We'll initialize it lazily; use
301 * {@link #getEffectiveUserRestrictions} to access it.
302 *
303 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
304 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
305 * maybe shared between {@link #mBaseUserRestrictions} and
306 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
307 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700308 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700309 */
310 @GuardedBy("mRestrictionsLock")
311 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
312
Makoto Onuki4f160732015-10-27 17:15:38 -0700313 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800314 * User restrictions that have already been applied in
315 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
316 * that have changed since the last
317 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700318 */
319 @GuardedBy("mRestrictionsLock")
320 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
321
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800322 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800323 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100324 * that should be applied to all users, including guests. Only non-empty restriction bundles are
325 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800326 */
327 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100328 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800329
330 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100331 * Id of the user that set global restrictions.
332 */
333 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100334 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100335
336 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800337 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100338 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800339 */
340 @GuardedBy("mRestrictionsLock")
341 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
342
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800343 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530344 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800345
346 /**
347 * Set of user IDs being actively removed. Removed IDs linger in this set
348 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700349 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800350 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700351 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800352 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700353
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700354 /**
355 * Queue of recently removed userIds. Used for recycling of userIds
356 */
357 @GuardedBy("mUsersLock")
358 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
359
Fyodor Kupolov82402752015-10-28 14:54:51 -0700360 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700361 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800362 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700363 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700364 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700365
Jason Monk62062992014-05-06 09:55:28 -0400366 private IAppOpsService mAppOpsService;
367
Makoto Onuki068c54a2015-10-13 14:34:03 -0700368 private final LocalService mLocalService;
369
Makoto Onukie7927da2015-11-25 10:05:17 -0800370 @GuardedBy("mUsersLock")
371 private boolean mIsDeviceManaged;
372
373 @GuardedBy("mUsersLock")
374 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
375
Makoto Onukid45a4a22015-11-02 17:17:38 -0800376 @GuardedBy("mUserRestrictionsListeners")
377 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
378 new ArrayList<>();
379
Clara Bayarria1771112015-12-18 16:29:18 +0000380 private final LockPatternUtils mLockPatternUtils;
381
Ricky Waib1dd80b2016-06-07 18:00:55 +0100382 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
383 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
384
385 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
386 @Override
387 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000388 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
389 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100390 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000391 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
392 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800393 // Call setQuietModeEnabled on bg thread to avoid ANR
394 BackgroundThread.getHandler()
395 .post(() -> setQuietModeEnabled(userHandle, false, target));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100396 }
397 };
398
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100399 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000400 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
401 *
Tony Makbece85d2018-01-12 12:10:17 +0000402 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000403 */
404 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
405 private final IntentSender mTarget;
406
407 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
408 Preconditions.checkNotNull(target);
409 mTarget = target;
410 }
411
412 @Override
413 public void onStarted(int id, Bundle extras) {}
414
415 @Override
416 public void onProgress(int id, int progress, Bundle extras) {}
417
418 @Override
419 public void onFinished(int id, Bundle extras) {
420 try {
421 mContext.startIntentSender(mTarget, null, 0, 0, 0);
422 } catch (IntentSender.SendIntentException e) {
423 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
424 }
425 }
426 }
427
428 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100429 * Whether all users should be created ephemeral.
430 */
431 @GuardedBy("mUsersLock")
432 private boolean mForceEphemeralUsers;
433
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000434 @GuardedBy("mUserStates")
435 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700436
Amith Yamasani258848d2012-08-10 17:06:33 -0700437 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700438
Dianne Hackborn4428e172012-08-24 17:43:05 -0700439 public static UserManagerService getInstance() {
440 synchronized (UserManagerService.class) {
441 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700442 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700443 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700444
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700445 public static class LifeCycle extends SystemService {
446
447 private UserManagerService mUms;
448
449 /**
450 * @param context
451 */
452 public LifeCycle(Context context) {
453 super(context);
454 }
455
456 @Override
457 public void onStart() {
458 mUms = UserManagerService.getInstance();
459 publishBinderService(Context.USER_SERVICE, mUms);
460 }
461
462 @Override
463 public void onBootPhase(int phase) {
464 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
465 mUms.cleanupPartialUsers();
466 }
467 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900468
469 @Override
470 public void onStartUser(int userHandle) {
471 synchronized (mUms.mUsersLock) {
472 final UserData user = mUms.getUserDataLU(userHandle);
473 if (user != null) {
474 user.startRealtime = SystemClock.elapsedRealtime();
475 }
476 }
477 }
478
479 @Override
480 public void onUnlockUser(int userHandle) {
481 synchronized (mUms.mUsersLock) {
482 final UserData user = mUms.getUserDataLU(userHandle);
483 if (user != null) {
484 user.unlockRealtime = SystemClock.elapsedRealtime();
485 }
486 }
487 }
488
489 @Override
490 public void onStopUser(int userHandle) {
491 synchronized (mUms.mUsersLock) {
492 final UserData user = mUms.getUserDataLU(userHandle);
493 if (user != null) {
494 user.startRealtime = 0;
495 user.unlockRealtime = 0;
496 }
497 }
498 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700499 }
500
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700501 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800502 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700503 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800504 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700505 }
506
Dianne Hackborn4428e172012-08-24 17:43:05 -0700507 /**
508 * Called by package manager to create the service. This is closely
509 * associated with the package manager, and the given lock is the
510 * package manager's own lock.
511 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800512 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
513 Object packagesLock) {
514 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700515 }
516
Dianne Hackborn4428e172012-08-24 17:43:05 -0700517 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800518 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700519 mContext = context;
520 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700521 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800522 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800523 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800524 synchronized (mPackagesLock) {
525 mUsersDir = new File(dataDir, USER_INFO_DIR);
526 mUsersDir.mkdirs();
527 // Make zeroth user directory, for services to migrate their files to that location
528 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
529 userZeroDir.mkdirs();
530 FileUtils.setPermissions(mUsersDir.toString(),
531 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
532 -1, -1);
533 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
534 initDefaultGuestRestrictions();
535 readUserListLP();
536 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700537 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700538 mLocalService = new LocalService();
539 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000540 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000541 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700542 }
543
544 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400545 mAppOpsService = IAppOpsService.Stub.asInterface(
546 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800547
548 synchronized (mRestrictionsLock) {
549 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400550 }
Samuel Tand9453b82016-03-14 15:57:02 -0700551
552 UserInfo currentGuestUser = findCurrentGuestUser();
553 if (currentGuestUser != null && !hasUserRestriction(
554 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
555 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
556 // to it, in case this guest was created in a previous version where this
557 // user restriction was not a default guest restriction.
558 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
559 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700560
Ricky Waib1dd80b2016-06-07 18:00:55 +0100561 mContext.registerReceiver(mDisableQuietModeCallback,
562 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
563 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700564 }
565
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700566 void cleanupPartialUsers() {
567 // Prune out any partially created, partially removed and ephemeral users.
568 ArrayList<UserInfo> partials = new ArrayList<>();
569 synchronized (mUsersLock) {
570 final int userSize = mUsers.size();
571 for (int i = 0; i < userSize; i++) {
572 UserInfo ui = mUsers.valueAt(i).info;
573 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
574 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700575 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700576 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700577 }
578 }
579 }
580 final int partialsSize = partials.size();
581 for (int i = 0; i < partialsSize; i++) {
582 UserInfo ui = partials.get(i);
583 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
584 + " (name=" + ui.name + ")");
585 removeUserState(ui.id);
586 }
587 }
588
Amith Yamasani258848d2012-08-10 17:06:33 -0700589 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800590 public String getUserAccount(int userId) {
591 checkManageUserAndAcrossUsersFullPermission("get user account");
592 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800593 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800594 }
595 }
596
597 @Override
598 public void setUserAccount(int userId, String accountName) {
599 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800600 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800601 synchronized (mPackagesLock) {
602 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800603 final UserData userData = mUsers.get(userId);
604 if (userData == null) {
605 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
606 return;
607 }
608 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000609 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800610 userData.account = accountName;
611 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800612 }
613 }
614
615 if (userToUpdate != null) {
616 writeUserLP(userToUpdate);
617 }
618 }
619 }
620
621 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700622 public UserInfo getPrimaryUser() {
623 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700624 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700625 final int userSize = mUsers.size();
626 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800627 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800628 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700629 return ui;
630 }
631 }
632 }
633 return null;
634 }
635
636 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700637 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700638 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700639 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700640 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700641 final int userSize = mUsers.size();
642 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800643 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700644 if (ui.partial) {
645 continue;
646 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800647 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700648 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700649 }
Amith Yamasani13593602012-03-22 16:16:17 -0700650 }
651 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700652 }
Amith Yamasani13593602012-03-22 16:16:17 -0700653 }
654
Amith Yamasani258848d2012-08-10 17:06:33 -0700655 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100656 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700657 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800658 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700659 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700660 } else {
661 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800662 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700663 final long ident = Binder.clearCallingIdentity();
664 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700665 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700666 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100667 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700668 } finally {
669 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000670 }
671 }
672
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700673 @Override
674 public int[] getProfileIds(int userId, boolean enabledOnly) {
675 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700676 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700677 }
678 final long ident = Binder.clearCallingIdentity();
679 try {
680 synchronized (mUsersLock) {
681 return getProfileIdsLU(userId, enabledOnly).toArray();
682 }
683 } finally {
684 Binder.restoreCallingIdentity(ident);
685 }
686 }
687
Amith Yamasanibe465322014-04-24 13:45:17 -0700688 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700689 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700690 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
691 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
692 for (int i = 0; i < profileIds.size(); i++) {
693 int profileId = profileIds.get(i);
694 UserInfo userInfo = mUsers.get(profileId).info;
695 // If full info is not required - clear PII data to prevent 3P apps from reading it
696 if (!fullInfo) {
697 userInfo = new UserInfo(userInfo);
698 userInfo.name = null;
699 userInfo.iconPath = null;
700 } else {
701 userInfo = userWithName(userInfo);
702 }
703 users.add(userInfo);
704 }
705 return users;
706 }
707
708 /**
709 * Assume permissions already checked and caller's identity cleared
710 */
711 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700712 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700713 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700714 if (user == null) {
715 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700716 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700717 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700718 final int userSize = mUsers.size();
719 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800720 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700721 if (!isProfileOf(user, profile)) {
722 continue;
723 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100724 if (enabledOnly && !profile.isEnabled()) {
725 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700726 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700727 if (mRemovingUserIds.get(profile.id)) {
728 continue;
729 }
Tony Mak80189cd2016-04-05 17:21:42 +0100730 if (profile.partial) {
731 continue;
732 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700733 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700734 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700735 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700736 }
737
Jessica Hummelbe81c802014-04-22 15:49:22 +0100738 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700739 public int getCredentialOwnerProfile(int userHandle) {
740 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000741 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700742 synchronized (mUsersLock) {
743 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700744 if (profileParent != null) {
745 return profileParent.id;
746 }
747 }
748 }
749
750 return userHandle;
751 }
752
753 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700754 public boolean isSameProfileGroup(int userId, int otherUserId) {
755 if (userId == otherUserId) return true;
756 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700757 return isSameProfileGroupNoChecks(userId, otherUserId);
758 }
759
760 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700761 synchronized (mUsersLock) {
762 UserInfo userInfo = getUserInfoLU(userId);
763 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
764 return false;
765 }
766 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
767 if (otherUserInfo == null
768 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
769 return false;
770 }
771 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700772 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700773 }
774
775 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100776 public UserInfo getProfileParent(int userHandle) {
777 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700778 synchronized (mUsersLock) {
779 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700780 }
781 }
782
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800783 @Override
784 public int getProfileParentId(int userHandle) {
785 checkManageUsersPermission("get the profile parent");
Sunny Goyal145c8f82018-02-15 14:27:09 -0800786 return mLocalService.getProfileParentId(userHandle);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800787 }
788
Fyodor Kupolov82402752015-10-28 14:54:51 -0700789 private UserInfo getProfileParentLU(int userHandle) {
790 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700791 if (profile == null) {
792 return null;
793 }
794 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800795 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700796 return null;
797 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700798 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100799 }
800 }
801
Fyodor Kupolov82402752015-10-28 14:54:51 -0700802 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100803 return user.id == profile.id ||
804 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
805 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000806 }
807
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000808 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000809 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100810 Intent intent = new Intent();
811 if (inQuietMode) {
812 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
813 } else {
814 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
815 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000816 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
817 intent.putExtra(Intent.EXTRA_USER, profileHandle);
818 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000819 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000820 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000821 }
822
823 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000824 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000825 int userHandle, @Nullable IntentSender target) {
826 Preconditions.checkNotNull(callingPackage);
827
Tony Makb7e6fd42017-12-05 19:40:28 +0000828 if (enableQuietMode && target != null) {
829 throw new IllegalArgumentException(
830 "target should only be specified when we are disabling quiet mode.");
831 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000832
Tony Makd390ae92017-12-28 13:23:10 +0000833 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000834 final long identity = Binder.clearCallingIdentity();
835 try {
836 if (enableQuietMode) {
837 setQuietModeEnabled(userHandle, true /* enableQuietMode */, target);
838 return true;
839 } else {
840 boolean needToShowConfirmCredential =
841 mLockPatternUtils.isSecure(userHandle)
842 && !StorageManager.isUserKeyUnlocked(userHandle);
843 if (needToShowConfirmCredential) {
844 showConfirmCredentialToDisableQuietMode(userHandle, target);
845 return false;
846 } else {
847 setQuietModeEnabled(userHandle, false /* enableQuietMode */, target);
848 return true;
849 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000850 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000851 } finally {
852 Binder.restoreCallingIdentity(identity);
853 }
854 }
855
Tony Make3d1f652017-12-12 11:00:37 +0000856 /**
Tony Makd390ae92017-12-28 13:23:10 +0000857 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000858 * <ul>
859 * <li>Has system UID or root UID</li>
860 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
861 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
862 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000863 * <p>
864 * If caller wants to start an intent after disabling the quiet mode, it must has
865 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000866 */
Tony Makd390ae92017-12-28 13:23:10 +0000867 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
868 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000869 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000870 return;
Tony Make3d1f652017-12-12 11:00:37 +0000871 }
Tony Makd390ae92017-12-28 13:23:10 +0000872 if (startIntent) {
873 throw new SecurityException("MANAGE_USERS permission is required to start intent "
874 + "after disabling quiet mode.");
875 }
jovanakf24ad492018-05-18 12:15:59 -0700876 final boolean hasModifyQuietModePermission = hasPermissionGranted(
877 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000878 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000879 return;
Tony Make3d1f652017-12-12 11:00:37 +0000880 }
881
Tony Makd390ae92017-12-28 13:23:10 +0000882 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000883 final ShortcutServiceInternal shortcutInternal =
884 LocalServices.getService(ShortcutServiceInternal.class);
885 if (shortcutInternal != null) {
886 boolean isForegroundLauncher =
887 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
888 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000889 return;
Tony Make3d1f652017-12-12 11:00:37 +0000890 }
891 }
Tony Makd390ae92017-12-28 13:23:10 +0000892 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
893 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000894 }
895
Tony Makb7e6fd42017-12-05 19:40:28 +0000896 private void setQuietModeEnabled(
897 int userHandle, boolean enableQuietMode, IntentSender target) {
898 final UserInfo profile, parent;
899 final UserData profileUserData;
900 synchronized (mUsersLock) {
901 profile = getUserInfoLU(userHandle);
902 parent = getProfileParentLU(userHandle);
903
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000904 if (profile == null || !profile.isManagedProfile()) {
905 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
906 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000907 if (profile.isQuietModeEnabled() == enableQuietMode) {
908 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
909 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000910 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000911 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
912 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000913 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000914 synchronized (mPackagesLock) {
915 writeUserLP(profileUserData);
916 }
917 try {
918 if (enableQuietMode) {
919 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
920 LocalServices.getService(ActivityManagerInternal.class)
921 .killForegroundAppsForUser(userHandle);
922 } else {
923 IProgressListener callback = target != null
924 ? new DisableQuietModeUserUnlockedCallback(target)
925 : null;
926 ActivityManager.getService().startUserInBackgroundWithListener(
927 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000928 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000929 } catch (RemoteException e) {
930 // Should not happen, same process.
931 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000932 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000933 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
934 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000935 }
936
937 @Override
938 public boolean isQuietModeEnabled(int userHandle) {
939 synchronized (mPackagesLock) {
940 UserInfo info;
941 synchronized (mUsersLock) {
942 info = getUserInfoLU(userHandle);
943 }
944 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000945 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000946 }
947 return info.isQuietModeEnabled();
948 }
949 }
950
Tony Makb7e6fd42017-12-05 19:40:28 +0000951 /**
952 * Show confirm credential screen to unlock user in order to turn off quiet mode.
953 */
954 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000955 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000956 // otherwise, we show a profile challenge to trigger decryption of the user
957 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
958 Context.KEYGUARD_SERVICE);
959 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
960 // lock, confirm screenlock page will know and show personal challenge, and unlock
961 // work profile when personal challenge is correct
962 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
963 userHandle);
964 if (unlockIntent == null) {
965 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +0100966 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000967 final Intent callBackIntent = new Intent(
968 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
969 if (target != null) {
970 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100971 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000972 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
973 callBackIntent.setPackage(mContext.getPackageName());
974 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
975 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
976 mContext,
977 0,
978 callBackIntent,
979 PendingIntent.FLAG_CANCEL_CURRENT |
980 PendingIntent.FLAG_ONE_SHOT |
981 PendingIntent.FLAG_IMMUTABLE);
982 // After unlocking the challenge, it will disable quiet mode and run the original
983 // intentSender
984 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
985 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
986 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100987 }
988
989 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100990 public void setUserEnabled(int userId) {
991 checkManageUsersPermission("enable user");
992 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700993 UserInfo info;
994 synchronized (mUsersLock) {
995 info = getUserInfoLU(userId);
996 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100997 if (info != null && !info.isEnabled()) {
998 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800999 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001000 }
1001 }
1002 }
1003
jovanakf24ad492018-05-18 12:15:59 -07001004 @Override
1005 public void setUserAdmin(int userId) {
1006 checkManageUserAndAcrossUsersFullPermission("set user admin");
1007
1008 synchronized (mPackagesLock) {
1009 UserInfo info;
1010 synchronized (mUsersLock) {
1011 info = getUserInfoLU(userId);
1012 }
1013 if (info == null || info.isAdmin()) {
1014 // Exit if no user found with that id, or the user is already an Admin.
1015 return;
1016 }
1017
1018 info.flags ^= UserInfo.FLAG_ADMIN;
1019 writeUserLP(getUserDataLU(info.id));
1020 }
1021
1022 // Remove non-admin restrictions.
1023 // Keep synchronized with createUserEvenWhenDisallowed.
1024 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1025 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1026 }
1027
Andrew Scull85a63bc2016-10-24 13:47:47 +01001028 /**
1029 * Evicts a user's CE key by stopping and restarting the user.
1030 *
1031 * The key is evicted automatically by the user controller when the user has stopped.
1032 */
1033 @Override
1034 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1035 checkManageUsersPermission("evict CE key");
1036 final IActivityManager am = ActivityManagerNative.getDefault();
1037 final long identity = Binder.clearCallingIdentity();
1038 try {
1039 am.restartUserInBackground(userId);
1040 } catch (RemoteException re) {
1041 throw re.rethrowAsRuntimeException();
1042 } finally {
1043 Binder.restoreCallingIdentity(identity);
1044 }
1045 }
1046
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001047 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001048 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001049 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001050 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001051 return userWithName(getUserInfoLU(userId));
1052 }
1053 }
1054
1055 /**
1056 * Returns a UserInfo object with the name filled in, for Owner, or the original
1057 * if the name is already set.
1058 */
1059 private UserInfo userWithName(UserInfo orig) {
1060 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1061 UserInfo withName = new UserInfo(orig);
1062 withName.name = getOwnerName();
1063 return withName;
1064 } else {
1065 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001066 }
1067 }
1068
1069 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001070 public int getManagedProfileBadge(@UserIdInt int userId) {
1071 int callingUserId = UserHandle.getCallingUserId();
1072 if (callingUserId != userId && !hasManageUsersPermission()) {
1073 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
1074 throw new SecurityException(
1075 "You need MANAGE_USERS permission to: check if specified user a " +
1076 "managed profile outside your profile group");
1077 }
1078 }
1079 synchronized (mUsersLock) {
1080 UserInfo userInfo = getUserInfoLU(userId);
1081 return userInfo != null ? userInfo.profileBadge : 0;
1082 }
1083 }
1084
1085 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001086 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +00001087 int callingUserId = UserHandle.getCallingUserId();
1088 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -07001089 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001090 throw new SecurityException(
1091 "You need MANAGE_USERS permission to: check if specified user a " +
1092 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +00001093 }
Tony Mak4dc008c2016-03-16 10:46:49 +00001094 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001095 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001096 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001097 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001098 }
1099 }
1100
Amith Yamasani71e6c692013-03-24 17:39:28 -07001101 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001102 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001103 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001104 return mLocalService.isUserUnlockingOrUnlocked(userId);
1105 }
1106
1107 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001108 public boolean isUserUnlocked(int userId) {
1109 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001110 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001111 }
1112
1113 @Override
1114 public boolean isUserRunning(int userId) {
1115 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1116 return mLocalService.isUserRunning(userId);
1117 }
1118
Makoto Onuki73dded22017-12-20 13:14:48 +09001119 @Override
1120 public long getUserStartRealtime() {
1121 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1122 synchronized (mUsersLock) {
1123 final UserData user = getUserDataLU(userId);
1124 if (user != null) {
1125 return user.startRealtime;
1126 }
1127 return 0;
1128 }
1129 }
1130
1131 @Override
1132 public long getUserUnlockRealtime() {
1133 synchronized (mUsersLock) {
1134 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1135 if (user != null) {
1136 return user.unlockRealtime;
1137 }
1138 return 0;
1139 }
1140 }
1141
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001142 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1143 int callingUserId = UserHandle.getCallingUserId();
1144 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1145 hasManageUsersPermission()) {
1146 return;
1147 }
jovanakf24ad492018-05-18 12:15:59 -07001148 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1149 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001150 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1151 + "to: check " + name);
1152 }
1153 }
1154
1155 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001156 public boolean isDemoUser(int userId) {
1157 int callingUserId = UserHandle.getCallingUserId();
1158 if (callingUserId != userId && !hasManageUsersPermission()) {
1159 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1160 + " is a demo user");
1161 }
1162 synchronized (mUsersLock) {
1163 UserInfo userInfo = getUserInfoLU(userId);
1164 return userInfo != null && userInfo.isDemo();
1165 }
1166 }
1167
1168 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001169 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001170 synchronized (mUsersLock) {
1171 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001172 }
1173 }
1174
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001175 @Override
1176 public boolean canHaveRestrictedProfile(int userId) {
1177 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001178 synchronized (mUsersLock) {
1179 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001180 if (userInfo == null || !userInfo.canHaveProfile()) {
1181 return false;
1182 }
1183 if (!userInfo.isAdmin()) {
1184 return false;
1185 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001186 // restricted profile can be created if there is no DO set and the admin user has no PO;
1187 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001188 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001189 }
1190
Fyodor Kupolovca177562017-11-09 17:43:01 -08001191 @Override
1192 public boolean hasRestrictedProfiles() {
1193 checkManageUsersPermission("hasRestrictedProfiles");
1194 final int callingUserId = UserHandle.getCallingUserId();
1195 synchronized (mUsersLock) {
1196 final int userSize = mUsers.size();
1197 for (int i = 0; i < userSize; i++) {
1198 UserInfo profile = mUsers.valueAt(i).info;
1199 if (callingUserId != profile.id
1200 && profile.restrictedProfileParentId == callingUserId) {
1201 return true;
1202 }
1203 }
1204 return false;
1205 }
1206 }
1207
Amith Yamasani195263742012-08-21 15:40:12 -07001208 /*
1209 * Should be locked on mUsers before calling this.
1210 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001211 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001212 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001213 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001214 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001215 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1216 return null;
1217 }
Amith Yamasani12747872015-12-07 14:19:49 -08001218 return userData != null ? userData.info : null;
1219 }
1220
1221 private UserData getUserDataLU(int userId) {
1222 final UserData userData = mUsers.get(userId);
1223 // If it is partial and not in the process of being removed, return as unknown user.
1224 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1225 return null;
1226 }
1227 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001228 }
1229
Fyodor Kupolov82402752015-10-28 14:54:51 -07001230 /**
1231 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1232 * <p>No permissions checking or any addition checks are made</p>
1233 */
1234 private UserInfo getUserInfoNoChecks(int userId) {
1235 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001236 final UserData userData = mUsers.get(userId);
1237 return userData != null ? userData.info : null;
1238 }
1239 }
1240
1241 /**
1242 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1243 * <p>No permissions checking or any addition checks are made</p>
1244 */
1245 private UserData getUserDataNoChecks(int userId) {
1246 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001247 return mUsers.get(userId);
1248 }
1249 }
1250
Amith Yamasani236b2b52015-08-18 14:32:14 -07001251 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001252 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001253 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001254 }
1255
Amith Yamasani258848d2012-08-10 17:06:33 -07001256 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001257 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001258 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001259 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001260 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001261 UserData userData = getUserDataNoChecks(userId);
1262 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001263 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1264 return;
1265 }
Amith Yamasani12747872015-12-07 14:19:49 -08001266 if (name != null && !name.equals(userData.info.name)) {
1267 userData.info.name = name;
1268 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001269 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001270 }
1271 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001272 if (changed) {
1273 sendUserInfoChangedBroadcast(userId);
1274 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001275 }
1276
Amith Yamasani258848d2012-08-10 17:06:33 -07001277 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001278 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001279 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001280 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1281 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1282 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001283 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001284 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001285 }
1286
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001287
1288
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001289 private void sendUserInfoChangedBroadcast(int userId) {
1290 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1291 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1292 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001293 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001294 }
1295
Amith Yamasani258848d2012-08-10 17:06:33 -07001296 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001297 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001298 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001299 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001300 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1301 if (targetUserInfo == null || targetUserInfo.partial) {
1302 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001303 return null;
1304 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001305
1306 final int callingUserId = UserHandle.getCallingUserId();
1307 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1308 final int targetGroupId = targetUserInfo.profileGroupId;
1309 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1310 && callingGroupId == targetGroupId);
1311 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001312 checkManageUsersPermission("get the icon of a user who is not related");
1313 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001314
1315 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001316 return null;
1317 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001318 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001319 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001320
1321 try {
1322 return ParcelFileDescriptor.open(
1323 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1324 } catch (FileNotFoundException e) {
1325 Log.e(LOG_TAG, "Couldn't find icon file", e);
1326 }
1327 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001328 }
1329
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001330 public void makeInitialized(int userId) {
1331 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001332 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001333 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001334 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001335 userData = mUsers.get(userId);
1336 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001337 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001338 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001339 }
Amith Yamasani12747872015-12-07 14:19:49 -08001340 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1341 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001342 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001343 }
1344 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001345 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001346 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001347 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001348 }
1349
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001350 /**
1351 * If default guest restrictions haven't been initialized yet, add the basic
1352 * restrictions.
1353 */
1354 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001355 synchronized (mGuestRestrictions) {
1356 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001357 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001358 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001359 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1360 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1361 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001362 }
1363 }
1364
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001365 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301366 public Bundle getDefaultGuestRestrictions() {
1367 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001368 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301369 return new Bundle(mGuestRestrictions);
1370 }
1371 }
1372
1373 @Override
1374 public void setDefaultGuestRestrictions(Bundle restrictions) {
1375 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001376 synchronized (mGuestRestrictions) {
1377 mGuestRestrictions.clear();
1378 mGuestRestrictions.putAll(restrictions);
1379 }
1380 synchronized (mPackagesLock) {
1381 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301382 }
1383 }
1384
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001385 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001386 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001387 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001388 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1389 boolean isDeviceOwner, int cameraRestrictionScope) {
1390 final Bundle global = new Bundle();
1391 final Bundle local = new Bundle();
1392
1393 // Sort restrictions into local and global ensuring they don't overlap.
1394 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1395 cameraRestrictionScope, global, local);
1396
1397 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001398 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001399 // Update global and local restrictions if they were changed.
1400 globalChanged = updateRestrictionsIfNeededLR(
1401 userId, global, mDevicePolicyGlobalUserRestrictions);
1402 localChanged = updateRestrictionsIfNeededLR(
1403 userId, local, mDevicePolicyLocalUserRestrictions);
1404
1405 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001406 // Remember the global restriction owner userId to be able to make a distinction
1407 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001408 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001409 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001410 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001411 // When profile owner sets restrictions it passes null global bundle and we
1412 // reset global restriction owner userId.
1413 // This means this user used to have DO, but now the DO is gone and the user
1414 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001415 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001416 }
1417 }
1418 }
1419 if (DBG) {
1420 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1421 + " global=" + global + (globalChanged ? " (changed)" : "")
1422 + " local=" + local + (localChanged ? " (changed)" : "")
1423 );
1424 }
1425 // Don't call them within the mRestrictionsLock.
1426 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001427 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001428 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001429 }
1430 }
1431
1432 synchronized (mRestrictionsLock) {
1433 if (globalChanged) {
1434 applyUserRestrictionsForAllUsersLR();
1435 } else if (localChanged) {
1436 applyUserRestrictionsLR(userId);
1437 }
1438 }
1439 }
1440
Pavel Grafov6a40f092016-10-25 15:46:51 +01001441 /**
1442 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1443 * empty, record is removed from the array.
1444 * @return whether restrictions bundle is different from the old one.
1445 */
1446 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1447 SparseArray<Bundle> restrictionsArray) {
1448 final boolean changed =
1449 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1450 if (changed) {
1451 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1452 restrictionsArray.put(userId, restrictions);
1453 } else {
1454 restrictionsArray.delete(userId);
1455 }
1456 }
1457 return changed;
1458 }
1459
Makoto Onuki068c54a2015-10-13 14:34:03 -07001460 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001461 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462 final Bundle baseRestrictions =
1463 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001464 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001465 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001466
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001467 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1468 // Common case first.
1469 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001470 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001471 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1472 UserRestrictionsUtils.merge(effective, global);
1473 UserRestrictionsUtils.merge(effective, local);
1474
Makoto Onuki068c54a2015-10-13 14:34:03 -07001475 return effective;
1476 }
1477
1478 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001479 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001480 if (DBG) {
1481 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1482 }
1483 mCachedEffectiveUserRestrictions.remove(userId);
1484 }
1485
1486 private Bundle getEffectiveUserRestrictions(int userId) {
1487 synchronized (mRestrictionsLock) {
1488 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1489 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001490 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001491 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1492 }
1493 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001494 }
1495 }
1496
Makoto Onuki068c54a2015-10-13 14:34:03 -07001497 /** @return a specific user restriction that's in effect currently. */
1498 @Override
1499 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001500 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1501 return false;
1502 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001503 Bundle restrictions = getEffectiveUserRestrictions(userId);
1504 return restrictions != null && restrictions.getBoolean(restrictionKey);
1505 }
1506
Makoto Onukiacc50462018-02-14 14:13:49 -08001507 /** @return if any user has the given restriction. */
1508 @Override
1509 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1510 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1511 return false;
1512 }
1513 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1514 for (int i = 0; i < users.size(); i++) {
1515 final int userId = users.get(i).id;
1516 Bundle restrictions = getEffectiveUserRestrictions(userId);
1517 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1518 return true;
1519 }
1520 }
1521 return false;
1522 }
1523
Makoto Onuki068c54a2015-10-13 14:34:03 -07001524 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001525 * @hide
1526 *
1527 * Returns who set a user restriction on a user.
1528 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1529 * @param restrictionKey the string key representing the restriction
1530 * @param userId the id of the user for whom to retrieve the restrictions.
1531 * @return The source of user restriction. Any combination of
1532 * {@link UserManager#RESTRICTION_NOT_SET},
1533 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1534 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1535 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1536 */
1537 @Override
1538 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001539 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1540 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001541 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001542 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1543 result |= enforcingUsers.get(i).getUserRestrictionSource();
1544 }
1545 return result;
1546 }
1547
1548 @Override
1549 public List<EnforcingUser> getUserRestrictionSources(
1550 String restrictionKey, @UserIdInt int userId) {
1551 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001552
1553 // Shortcut for the most common case
1554 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001555 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001556 }
1557
Pavel Grafov6a40f092016-10-25 15:46:51 +01001558 final List<EnforcingUser> result = new ArrayList<>();
1559
1560 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001561 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001562 result.add(new EnforcingUser(
1563 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001564 }
1565
Pavel Grafov6a40f092016-10-25 15:46:51 +01001566 synchronized (mRestrictionsLock) {
1567 // Check if it is set by profile owner.
1568 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1569 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1570 result.add(getEnforcingUserLocked(userId));
1571 }
1572
1573 // Iterate over all users who enforce global restrictions.
1574 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1575 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1576 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1577 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1578 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001579 }
1580 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001581 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001582 return result;
1583 }
1584
Andreas Gampea36dc622018-02-05 17:19:22 -08001585 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001586 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1587 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1588 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1589 return new EnforcingUser(userId, source);
1590 }
1591
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001592 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001593 * @return UserRestrictions that are in effect currently. This always returns a new
1594 * {@link Bundle}.
1595 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001596 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001597 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001598 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001599 }
1600
1601 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001602 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1603 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001604 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1605 return false;
1606 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001607 synchronized (mRestrictionsLock) {
1608 Bundle bundle = mBaseUserRestrictions.get(userId);
1609 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1610 }
1611 }
1612
1613 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001614 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001615 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001616 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1617 return;
1618 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001619 synchronized (mRestrictionsLock) {
1620 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1621 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1623 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001624 newRestrictions.putBoolean(key, value);
1625
Fyodor Kupolov82402752015-10-28 14:54:51 -07001626 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001627 }
1628 }
1629
Makoto Onuki068c54a2015-10-13 14:34:03 -07001630 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001631 * Optionally updating user restrictions, calculate the effective user restrictions and also
1632 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001633 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001634 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001635 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001636 * @param userId target user ID.
1637 */
1638 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001639 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001640 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1642 mAppliedUserRestrictions.get(userId));
1643
1644 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001645 if (newBaseRestrictions != null) {
1646 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1648
Pavel Grafov6a40f092016-10-25 15:46:51 +01001649 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001650 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001651 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001652
Pavel Grafov6a40f092016-10-25 15:46:51 +01001653 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001654 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001655 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001656 }
1657
Fyodor Kupolov82402752015-10-28 14:54:51 -07001658 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001659
Makoto Onuki759a7632015-10-28 16:43:10 -07001660 mCachedEffectiveUserRestrictions.put(userId, effective);
1661
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001662 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001663 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001664 debug("Applying user restrictions: userId=" + userId
1665 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001666 }
1667
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001668 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001669 mHandler.post(new Runnable() {
1670 @Override
1671 public void run() {
1672 try {
1673 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1674 } catch (RemoteException e) {
1675 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1676 }
1677 }
1678 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001679 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001680
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001682
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001684 }
1685
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001687 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001688 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1689 // actually, but we still need some kind of synchronization otherwise we might end up
1690 // calling listeners out-of-order, thus "LR".
1691
1692 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1693 return;
1694 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001695
1696 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1697 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1698
1699 mHandler.post(new Runnable() {
1700 @Override
1701 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001702 UserRestrictionsUtils.applyUserRestrictions(
1703 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001704
Makoto Onukid45a4a22015-11-02 17:17:38 -08001705 final UserRestrictionsListener[] listeners;
1706 synchronized (mUserRestrictionsListeners) {
1707 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1708 mUserRestrictionsListeners.toArray(listeners);
1709 }
1710 for (int i = 0; i < listeners.length; i++) {
1711 listeners[i].onUserRestrictionsChanged(userId,
1712 newRestrictionsFinal, prevRestrictionsFinal);
1713 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001714
1715 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1716 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1717 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001718 }
1719 });
1720 }
1721
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722 // Package private for the inner class.
1723 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001724 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001725 }
1726
1727 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001728 // Package private for the inner class.
1729 void applyUserRestrictionsForAllUsersLR() {
1730 if (DBG) {
1731 debug("applyUserRestrictionsForAllUsersLR");
1732 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001733 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001734 mCachedEffectiveUserRestrictions.clear();
1735
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001736 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001737 // it on a handler.
1738 final Runnable r = new Runnable() {
1739 @Override
1740 public void run() {
1741 // Then get the list of running users.
1742 final int[] runningUsers;
1743 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001744 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001745 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001746 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001747 return;
1748 }
1749 // Then re-calculate the effective restrictions and apply, only for running users.
1750 // It's okay if a new user has started after the getRunningUserIds() call,
1751 // because we'll do the same thing (re-calculate the restrictions and apply)
1752 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001753 synchronized (mRestrictionsLock) {
1754 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001755 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001756 }
1757 }
1758 }
1759 };
1760 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001761 }
1762
Amith Yamasani258848d2012-08-10 17:06:33 -07001763 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001764 * Check if we've hit the limit of how many users can be created.
1765 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001766 private boolean isUserLimitReached() {
1767 int count;
1768 synchronized (mUsersLock) {
1769 count = getAliveUsersExcludingGuestsCountLU();
1770 }
1771 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001772 }
1773
1774 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001775 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001776 checkManageUsersPermission("check if more managed profiles can be added.");
1777 if (ActivityManager.isLowRamDeviceStatic()) {
1778 return false;
1779 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001780 if (!mContext.getPackageManager().hasSystemFeature(
1781 PackageManager.FEATURE_MANAGED_USERS)) {
1782 return false;
1783 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001784 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001785 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001786 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001787 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001788 return false;
1789 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001790 synchronized(mUsersLock) {
1791 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001792 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001793 return false;
1794 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001795 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1796 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001797 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001798 return usersCountAfterRemoving == 1
1799 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001800 }
1801 }
1802
Fyodor Kupolov82402752015-10-28 14:54:51 -07001803 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001804 int aliveUserCount = 0;
1805 final int totalUserCount = mUsers.size();
1806 // Skip over users being removed
1807 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001808 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001809 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001810 aliveUserCount++;
1811 }
1812 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001813 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001814 }
1815
1816 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001817 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001818 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1819 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1820 * permissions can make certain calls to the UserManager.
1821 *
1822 * @param message used as message if SecurityException is thrown
1823 * @throws SecurityException if the caller does not have enough privilege.
1824 */
1825 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1826 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001827
1828 if (uid == Process.SYSTEM_UID || uid == 0) {
1829 // System UID or root's UID are granted privilege.
1830 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001831 }
jovanakf24ad492018-05-18 12:15:59 -07001832
1833 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1834 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1835 // Apps with both permissions are granted privilege.
1836 return;
1837 }
1838
1839 throw new SecurityException(
1840 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1841 }
1842
1843 private static boolean hasPermissionGranted(String permission, int uid) {
1844 return ActivityManager.checkComponentPermission(
1845 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1846 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001847 }
1848
1849 /**
1850 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001851 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001852 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001853 *
1854 * @param message used as message if SecurityException is thrown
1855 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001856 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001857 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001858 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001859 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001860 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1861 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001862 }
1863
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001864 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001865 * Enforces that only the system UID or root's UID or apps that have the
1866 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1867 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1868 * can make certain calls to the UserManager.
1869 *
1870 * @param message used as message if SecurityException is thrown
1871 * @throws SecurityException if the caller is not system or root
1872 * @see #hasManageOrCreateUsersPermission()
1873 */
1874 private static final void checkManageOrCreateUsersPermission(String message) {
1875 if (!hasManageOrCreateUsersPermission()) {
1876 throw new SecurityException(
1877 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1878 }
1879 }
1880
1881 /**
1882 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1883 * to create user/profiles other than what is allowed for
1884 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1885 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1886 */
1887 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1888 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1889 if (!hasManageOrCreateUsersPermission()) {
1890 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1891 + "permission to create an user with flags: " + creationFlags);
1892 }
1893 } else if (!hasManageUsersPermission()) {
1894 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1895 + " with flags: " + creationFlags);
1896 }
1897 }
1898
1899 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001900 * @return whether the calling UID is system UID or root's UID or the calling app has the
1901 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1902 */
1903 private static final boolean hasManageUsersPermission() {
1904 final int callingUid = Binder.getCallingUid();
1905 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1906 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001907 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001908 }
1909
1910 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001911 * @return whether the calling UID is system UID or root's UID or the calling app has the
1912 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1913 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1914 */
1915 private static final boolean hasManageOrCreateUsersPermission() {
1916 final int callingUid = Binder.getCallingUid();
1917 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1918 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001919 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
1920 || hasPermissionGranted(android.Manifest.permission.CREATE_USERS, callingUid);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001921 }
1922
1923 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001924 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1925 * UserManager.
1926 *
1927 * @param message used as message if SecurityException is thrown
1928 * @throws SecurityException if the caller is not system or root
1929 */
1930 private static void checkSystemOrRoot(String message) {
1931 final int uid = Binder.getCallingUid();
1932 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1933 throw new SecurityException("Only system may: " + message);
1934 }
1935 }
1936
Fyodor Kupolov82402752015-10-28 14:54:51 -07001937 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001938 try {
1939 File dir = new File(mUsersDir, Integer.toString(info.id));
1940 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001941 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001942 if (!dir.exists()) {
1943 dir.mkdir();
1944 FileUtils.setPermissions(
1945 dir.getPath(),
1946 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1947 -1, -1);
1948 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001949 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001950 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001951 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001952 info.iconPath = file.getAbsolutePath();
1953 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001954 try {
1955 os.close();
1956 } catch (IOException ioe) {
1957 // What the ... !
1958 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001959 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001960 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001961 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001962 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001963 }
1964
Amith Yamasani0b285492011-04-14 17:35:23 -07001965 /**
1966 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1967 * cache it elsewhere.
1968 * @return the array of user ids.
1969 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001970 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001971 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001972 return mUserIds;
1973 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001974 }
1975
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001976 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001977 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001978 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001979 return;
1980 }
1981 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001982 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001983 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001984 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001985 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001986 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001987 int type;
1988 while ((type = parser.next()) != XmlPullParser.START_TAG
1989 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001990 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001991 }
1992
1993 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001994 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001995 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001996 return;
1997 }
1998
Amith Yamasani2a003292012-08-14 18:25:45 -07001999 mNextSerialNumber = -1;
2000 if (parser.getName().equals(TAG_USERS)) {
2001 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2002 if (lastSerialNumber != null) {
2003 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2004 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002005 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2006 if (versionNumber != null) {
2007 mUserVersion = Integer.parseInt(versionNumber);
2008 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002009 }
2010
Pavel Grafov6a40f092016-10-25 15:46:51 +01002011 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2012 // currently), take care of it in case of upgrade.
2013 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002014
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002015 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302016 if (type == XmlPullParser.START_TAG) {
2017 final String name = parser.getName();
2018 if (name.equals(TAG_USER)) {
2019 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002020
Amith Yamasani12747872015-12-07 14:19:49 -08002021 UserData userData = readUserLP(Integer.parseInt(id));
2022
2023 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002024 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002025 mUsers.put(userData.info.id, userData);
2026 if (mNextSerialNumber < 0
2027 || mNextSerialNumber <= userData.info.id) {
2028 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002029 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302030 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002031 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302032 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002033 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2034 && type != XmlPullParser.END_TAG) {
2035 if (type == XmlPullParser.START_TAG) {
2036 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002037 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002038 UserRestrictionsUtils
2039 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002040 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002041 }
2042 break;
2043 }
2044 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002045 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2046 // Legacy name, should only be encountered when upgrading from pre-O.
2047 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002048 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2049 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002050 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002051 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002052 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2053 // Should only happen when upgrading from pre-O (version < 7).
2054 oldDevicePolicyGlobalUserRestrictions =
2055 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002056 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002057 }
2058 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002059
Fyodor Kupolov82402752015-10-28 14:54:51 -07002060 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002061 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002062 } catch (IOException | XmlPullParserException e) {
2063 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002064 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002065 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002066 }
2067 }
2068
Amith Yamasani6f34b412012-10-22 18:19:27 -07002069 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002070 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002071 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002072 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01002073 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002074 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002075 int userVersion = mUserVersion;
2076 if (userVersion < 1) {
2077 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002078 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2079 if ("Primary".equals(userData.info.name)) {
2080 userData.info.name =
2081 mContext.getResources().getString(com.android.internal.R.string.owner_name);
2082 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002083 }
2084 userVersion = 1;
2085 }
2086
Amith Yamasanibc9625052012-11-15 14:39:18 -08002087 if (userVersion < 2) {
2088 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002089 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2090 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2091 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2092 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002093 }
2094 userVersion = 2;
2095 }
2096
Amith Yamasani350962c2013-08-06 11:18:53 -07002097
Amith Yamasani5e486f52013-08-07 11:06:44 -07002098 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002099 userVersion = 4;
2100 }
2101
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002102 if (userVersion < 5) {
2103 initDefaultGuestRestrictions();
2104 userVersion = 5;
2105 }
2106
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002107 if (userVersion < 6) {
2108 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002109 synchronized (mUsersLock) {
2110 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002111 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002112 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002113 if (!splitSystemUser && userData.info.isRestricted()
2114 && (userData.info.restrictedProfileParentId
2115 == UserInfo.NO_PROFILE_GROUP_ID)) {
2116 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2117 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002118 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002119 }
2120 }
2121 userVersion = 6;
2122 }
2123
Pavel Grafov6a40f092016-10-25 15:46:51 +01002124 if (userVersion < 7) {
2125 // Previously only one user could enforce global restrictions, now it is per-user.
2126 synchronized (mRestrictionsLock) {
2127 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2128 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2129 mDevicePolicyGlobalUserRestrictions.put(
2130 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2131 }
2132 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2133 // it from local to global bundle for all users who set it.
2134 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2135 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2136 );
2137 }
2138 userVersion = 7;
2139 }
2140
Amith Yamasani6f34b412012-10-22 18:19:27 -07002141 if (userVersion < USER_VERSION) {
2142 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2143 + USER_VERSION);
2144 } else {
2145 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002146
2147 if (originalVersion < mUserVersion) {
2148 writeUserListLP();
2149 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002150 }
2151 }
2152
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002153 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002154 int flags = UserInfo.FLAG_INITIALIZED;
2155 // In split system user mode, the admin and primary flags are assigned to the first human
2156 // user.
2157 if (!UserManager.isSplitSystemUser()) {
2158 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2159 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002160 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002161 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002162 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002163 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002164 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002165
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002166 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002167 try {
2168 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2169 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2170 for (String userRestriction : defaultFirstUserRestrictions) {
2171 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2172 restrictions.putBoolean(userRestriction, true);
2173 }
2174 }
2175 } catch (Resources.NotFoundException e) {
2176 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2177 }
2178
Pavel Grafov6a40f092016-10-25 15:46:51 +01002179 if (!restrictions.isEmpty()) {
2180 synchronized (mRestrictionsLock) {
2181 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2182 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002183 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002184
Fyodor Kupolov82402752015-10-28 14:54:51 -07002185 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002186 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002187
Amith Yamasani12747872015-12-07 14:19:49 -08002188 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002189 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002190 }
2191
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002192 private String getOwnerName() {
2193 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2194 }
2195
Amith Yamasani12747872015-12-07 14:19:49 -08002196 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002197 if (DBG) {
2198 debug("scheduleWriteUser");
2199 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002200 // No need to wrap it within a lock -- worst case, we'll just post the same message
2201 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002202 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2203 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002204 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2205 }
2206 }
2207
Amith Yamasani12747872015-12-07 14:19:49 -08002208 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002209 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002210 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002211 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002212 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002213 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002214 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002215 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002216 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002217 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002218 userFile.finishWrite(fos);
2219 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002220 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002221 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002222 }
2223 }
2224
2225 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002226 * Writes the user file in this format:
2227 *
2228 * <user flags="20039023" id="0">
2229 * <name>Primary</name>
2230 * </user>
2231 */
2232 @VisibleForTesting
2233 void writeUserLP(UserData userData, OutputStream os)
2234 throws IOException, XmlPullParserException {
2235 // XmlSerializer serializer = XmlUtils.serializerInstance();
2236 final XmlSerializer serializer = new FastXmlSerializer();
2237 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2238 serializer.startDocument(null, true);
2239 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2240
2241 final UserInfo userInfo = userData.info;
2242 serializer.startTag(null, TAG_USER);
2243 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2244 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2245 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2246 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2247 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2248 Long.toString(userInfo.lastLoggedInTime));
2249 if (userInfo.lastLoggedInFingerprint != null) {
2250 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2251 userInfo.lastLoggedInFingerprint);
2252 }
2253 if (userInfo.iconPath != null) {
2254 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2255 }
2256 if (userInfo.partial) {
2257 serializer.attribute(null, ATTR_PARTIAL, "true");
2258 }
2259 if (userInfo.guestToRemove) {
2260 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2261 }
2262 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2263 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2264 Integer.toString(userInfo.profileGroupId));
2265 }
2266 serializer.attribute(null, ATTR_PROFILE_BADGE,
2267 Integer.toString(userInfo.profileBadge));
2268 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2269 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2270 Integer.toString(userInfo.restrictedProfileParentId));
2271 }
2272 // Write seed data
2273 if (userData.persistSeedData) {
2274 if (userData.seedAccountName != null) {
2275 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2276 }
2277 if (userData.seedAccountType != null) {
2278 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2279 }
2280 }
2281 if (userInfo.name != null) {
2282 serializer.startTag(null, TAG_NAME);
2283 serializer.text(userInfo.name);
2284 serializer.endTag(null, TAG_NAME);
2285 }
2286 synchronized (mRestrictionsLock) {
2287 UserRestrictionsUtils.writeRestrictions(serializer,
2288 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2289 UserRestrictionsUtils.writeRestrictions(serializer,
2290 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2291 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002292 UserRestrictionsUtils.writeRestrictions(serializer,
2293 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2294 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002295 }
2296
2297 if (userData.account != null) {
2298 serializer.startTag(null, TAG_ACCOUNT);
2299 serializer.text(userData.account);
2300 serializer.endTag(null, TAG_ACCOUNT);
2301 }
2302
2303 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2304 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2305 userData.seedAccountOptions.saveToXml(serializer);
2306 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2307 }
2308
2309 serializer.endTag(null, TAG_USER);
2310
2311 serializer.endDocument();
2312 }
2313
2314 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002315 * Writes the user list file in this format:
2316 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002317 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002318 * <user id="0"></user>
2319 * <user id="2"></user>
2320 * </users>
2321 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002322 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002323 if (DBG) {
2324 debug("writeUserList");
2325 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002326 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002327 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002328 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002329 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002330 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2331
2332 // XmlSerializer serializer = XmlUtils.serializerInstance();
2333 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002334 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002335 serializer.startDocument(null, true);
2336 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2337
2338 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002339 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002340 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002341
Adam Lesinskieddeb492014-09-08 17:50:03 -07002342 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002343 synchronized (mGuestRestrictions) {
2344 UserRestrictionsUtils
2345 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2346 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302347 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002348 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2349 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2350 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002351 int[] userIdsToWrite;
2352 synchronized (mUsersLock) {
2353 userIdsToWrite = new int[mUsers.size()];
2354 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002355 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002356 userIdsToWrite[i] = user.id;
2357 }
2358 }
2359 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002360 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002361 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002362 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002363 }
2364
2365 serializer.endTag(null, TAG_USERS);
2366
2367 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002368 userListFile.finishWrite(fos);
2369 } catch (Exception e) {
2370 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002371 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002372 }
2373 }
2374
Amith Yamasani12747872015-12-07 14:19:49 -08002375 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002376 FileInputStream fis = null;
2377 try {
2378 AtomicFile userFile =
2379 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2380 fis = userFile.openRead();
2381 return readUserLP(id, fis);
2382 } catch (IOException ioe) {
2383 Slog.e(LOG_TAG, "Error reading user list");
2384 } catch (XmlPullParserException pe) {
2385 Slog.e(LOG_TAG, "Error reading user list");
2386 } finally {
2387 IoUtils.closeQuietly(fis);
2388 }
2389 return null;
2390 }
2391
2392 @VisibleForTesting
2393 UserData readUserLP(int id, InputStream is) throws IOException,
2394 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002395 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002396 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002397 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002398 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002399 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002400 long creationTime = 0L;
2401 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002402 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002403 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002404 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002405 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002406 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002407 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002408 boolean persistSeedData = false;
2409 String seedAccountName = null;
2410 String seedAccountType = null;
2411 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002412 Bundle baseRestrictions = null;
2413 Bundle localRestrictions = null;
2414 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002415
Kenny Guy02c89902016-11-15 19:36:38 +00002416 XmlPullParser parser = Xml.newPullParser();
2417 parser.setInput(is, StandardCharsets.UTF_8.name());
2418 int type;
2419 while ((type = parser.next()) != XmlPullParser.START_TAG
2420 && type != XmlPullParser.END_DOCUMENT) {
2421 // Skip
2422 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002423
Kenny Guy02c89902016-11-15 19:36:38 +00002424 if (type != XmlPullParser.START_TAG) {
2425 Slog.e(LOG_TAG, "Unable to read user " + id);
2426 return null;
2427 }
2428
2429 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2430 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2431 if (storedId != id) {
2432 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002433 return null;
2434 }
Kenny Guy02c89902016-11-15 19:36:38 +00002435 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2436 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2437 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2438 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2439 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2440 lastLoggedInFingerprint = parser.getAttributeValue(null,
2441 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2442 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2443 UserInfo.NO_PROFILE_GROUP_ID);
2444 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2445 restrictedProfileParentId = readIntAttribute(parser,
2446 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2447 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2448 if ("true".equals(valueString)) {
2449 partial = true;
2450 }
2451 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2452 if ("true".equals(valueString)) {
2453 guestToRemove = true;
2454 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002455
Kenny Guy02c89902016-11-15 19:36:38 +00002456 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2457 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2458 if (seedAccountName != null || seedAccountType != null) {
2459 persistSeedData = true;
2460 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002461
Kenny Guy02c89902016-11-15 19:36:38 +00002462 int outerDepth = parser.getDepth();
2463 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2464 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2465 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2466 continue;
2467 }
2468 String tag = parser.getName();
2469 if (TAG_NAME.equals(tag)) {
2470 type = parser.next();
2471 if (type == XmlPullParser.TEXT) {
2472 name = parser.getText();
2473 }
2474 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002475 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002476 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002477 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2478 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2479 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002480 } else if (TAG_ACCOUNT.equals(tag)) {
2481 type = parser.next();
2482 if (type == XmlPullParser.TEXT) {
2483 account = parser.getText();
2484 }
2485 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2486 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002487 persistSeedData = true;
2488 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002489 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002490 }
Kenny Guy02c89902016-11-15 19:36:38 +00002491
2492 // Create the UserInfo object that gets passed around
2493 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2494 userInfo.serialNumber = serialNumber;
2495 userInfo.creationTime = creationTime;
2496 userInfo.lastLoggedInTime = lastLoggedInTime;
2497 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2498 userInfo.partial = partial;
2499 userInfo.guestToRemove = guestToRemove;
2500 userInfo.profileGroupId = profileGroupId;
2501 userInfo.profileBadge = profileBadge;
2502 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2503
2504 // Create the UserData object that's internal to this class
2505 UserData userData = new UserData();
2506 userData.info = userInfo;
2507 userData.account = account;
2508 userData.seedAccountName = seedAccountName;
2509 userData.seedAccountType = seedAccountType;
2510 userData.persistSeedData = persistSeedData;
2511 userData.seedAccountOptions = seedAccountOptions;
2512
2513 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002514 if (baseRestrictions != null) {
2515 mBaseUserRestrictions.put(id, baseRestrictions);
2516 }
2517 if (localRestrictions != null) {
2518 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2519 }
2520 if (globalRestrictions != null) {
2521 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2522 }
Kenny Guy02c89902016-11-15 19:36:38 +00002523 }
2524 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002525 }
2526
Amith Yamasani920ace02012-09-20 22:15:37 -07002527 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2528 String valueString = parser.getAttributeValue(null, attr);
2529 if (valueString == null) return defaultValue;
2530 try {
2531 return Integer.parseInt(valueString);
2532 } catch (NumberFormatException nfe) {
2533 return defaultValue;
2534 }
2535 }
2536
2537 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2538 String valueString = parser.getAttributeValue(null, attr);
2539 if (valueString == null) return defaultValue;
2540 try {
2541 return Long.parseLong(valueString);
2542 } catch (NumberFormatException nfe) {
2543 return defaultValue;
2544 }
2545 }
2546
Amith Yamasanib82add22013-07-09 11:24:44 -07002547 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002548 * Removes the app restrictions file for a specific package and user id, if it exists.
2549 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002550 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2551 File dir = Environment.getUserSystemDirectory(userId);
2552 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2553 if (resFile.exists()) {
2554 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002555 }
2556 }
2557
Kenny Guya52dc3e2014-02-11 15:33:14 +00002558 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002559 public UserInfo createProfileForUser(String name, int flags, int userId,
2560 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002561 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002562 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002563 }
2564
Amith Yamasani258848d2012-08-10 17:06:33 -07002565 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002566 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2567 String[] disallowedPackages) {
2568 checkManageOrCreateUsersPermission(flags);
2569 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2570 }
2571
2572 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002573 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2574 checkManageOrCreateUsersPermission("Only the system can remove users");
2575 return removeUserUnchecked(userHandle);
2576 }
2577
2578 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002579 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002580 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002581 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002582 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002583
Jessica Hummelbe81c802014-04-22 15:49:22 +01002584 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002585 return createUserInternal(name, flags, parentId, null);
2586 }
2587
2588 private UserInfo createUserInternal(String name, int flags, int parentId,
2589 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002590 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2591 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2592 : UserManager.DISALLOW_ADD_USER;
2593 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2594 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002595 return null;
2596 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002597 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2598 }
2599
2600 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2601 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002602 DeviceStorageMonitorInternal dsm = LocalServices
2603 .getService(DeviceStorageMonitorInternal.class);
2604 if (dsm.isMemoryLow()) {
2605 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2606 return null;
2607 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002608 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002609 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002610 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002611 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002612 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002613 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002614 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002615 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002616 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002617 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002618 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002619 if (parentId != UserHandle.USER_NULL) {
2620 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002621 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002622 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002623 if (parent == null) return null;
2624 }
2625 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2626 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2627 return null;
2628 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002629 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2630 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002631 // been reached, cannot add a user.
2632 return null;
2633 }
2634 // If we're adding a guest and there already exists one, bail.
2635 if (isGuest && findCurrentGuestUser() != null) {
2636 return null;
2637 }
2638 // In legacy mode, restricted profile's parent can only be the owner user
2639 if (isRestricted && !UserManager.isSplitSystemUser()
2640 && (parentId != UserHandle.USER_SYSTEM)) {
2641 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2642 return null;
2643 }
2644 if (isRestricted && UserManager.isSplitSystemUser()) {
2645 if (parent == null) {
2646 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2647 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002648 return null;
2649 }
Amith Yamasani12747872015-12-07 14:19:49 -08002650 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002651 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2652 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002653 return null;
2654 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002655 }
2656 // In split system user mode, we assign the first human user the primary flag.
2657 // And if there is no device owner, we also assign the admin flag to primary user.
2658 if (UserManager.isSplitSystemUser()
2659 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2660 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002661 synchronized (mUsersLock) {
2662 if (!mIsDeviceManaged) {
2663 flags |= UserInfo.FLAG_ADMIN;
2664 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002665 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002666 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002667
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002668 userId = getNextAvailableId();
2669 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002670 boolean ephemeralGuests = Resources.getSystem()
2671 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002672
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002673 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002674 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2675 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2676 || (parent != null && parent.info.isEphemeral())) {
2677 flags |= UserInfo.FLAG_EPHEMERAL;
2678 }
2679
2680 userInfo = new UserInfo(userId, name, null, flags);
2681 userInfo.serialNumber = mNextSerialNumber++;
2682 long now = System.currentTimeMillis();
2683 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2684 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002685 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002686 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2687 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2688 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002689 userData = new UserData();
2690 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002691 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002692 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002693 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002694 writeUserListLP();
2695 if (parent != null) {
2696 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002697 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2698 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002699 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002700 }
Amith Yamasani12747872015-12-07 14:19:49 -08002701 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002702 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002703 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2704 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002705 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002706 }
Amith Yamasani12747872015-12-07 14:19:49 -08002707 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002708 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002709 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002710 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002711 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002712 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002713 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002714 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002715 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002716 userInfo.partial = false;
2717 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002718 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002719 }
2720 updateUserIds();
2721 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002722 if (isGuest) {
2723 synchronized (mGuestRestrictions) {
2724 restrictions.putAll(mGuestRestrictions);
2725 }
2726 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002727 synchronized (mRestrictionsLock) {
2728 mBaseUserRestrictions.append(userId, restrictions);
2729 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002730 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002731 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2732 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2733 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2734 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002735 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2736 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002737 } finally {
2738 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002739 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002740 return userInfo;
2741 }
2742
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002743 @VisibleForTesting
2744 UserData putUserInfo(UserInfo userInfo) {
2745 final UserData userData = new UserData();
2746 userData.info = userInfo;
2747 synchronized (mUsers) {
2748 mUsers.put(userInfo.id, userData);
2749 }
2750 return userData;
2751 }
2752
2753 @VisibleForTesting
2754 void removeUserInfo(int userId) {
2755 synchronized (mUsers) {
2756 mUsers.remove(userId);
2757 }
2758 }
2759
Amith Yamasani0b285492011-04-14 17:35:23 -07002760 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002761 * @hide
2762 */
Amith Yamasani12747872015-12-07 14:19:49 -08002763 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002764 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002765 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002766 final UserInfo user = createProfileForUser(
2767 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002768 if (user == null) {
2769 return null;
2770 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002771 long identity = Binder.clearCallingIdentity();
2772 try {
2773 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2774 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2775 // the putIntForUser() will fail.
2776 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2777 android.provider.Settings.Secure.LOCATION_MODE,
2778 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2779 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2780 } finally {
2781 Binder.restoreCallingIdentity(identity);
2782 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002783 return user;
2784 }
2785
2786 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002787 * Find the current guest user. If the Guest user is partial,
2788 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002789 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002790 private UserInfo findCurrentGuestUser() {
2791 synchronized (mUsersLock) {
2792 final int size = mUsers.size();
2793 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002794 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002795 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2796 return user;
2797 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002798 }
2799 }
2800 return null;
2801 }
2802
2803 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002804 * Mark this guest user for deletion to allow us to create another guest
2805 * and switch to that user before actually removing this guest.
2806 * @param userHandle the userid of the current guest
2807 * @return whether the user could be marked for deletion
2808 */
Amith Yamasani12747872015-12-07 14:19:49 -08002809 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002810 public boolean markGuestForDeletion(int userHandle) {
2811 checkManageUsersPermission("Only the system can remove users");
2812 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2813 UserManager.DISALLOW_REMOVE_USER, false)) {
2814 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2815 return false;
2816 }
2817
2818 long ident = Binder.clearCallingIdentity();
2819 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002820 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002821 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002822 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002823 userData = mUsers.get(userHandle);
2824 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002825 return false;
2826 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002827 }
Amith Yamasani12747872015-12-07 14:19:49 -08002828 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002829 return false;
2830 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002831 // We set this to a guest user that is to be removed. This is a temporary state
2832 // where we are allowed to add new Guest users, even if this one is still not
2833 // removed. This user will still show up in getUserInfo() calls.
2834 // If we don't get around to removing this Guest user, it will be purged on next
2835 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002836 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002837 // Mark it as disabled, so that it isn't returned any more when
2838 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002839 userData.info.flags |= UserInfo.FLAG_DISABLED;
2840 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002841 }
2842 } finally {
2843 Binder.restoreCallingIdentity(ident);
2844 }
2845 return true;
2846 }
2847
2848 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002849 * Removes a user and all data directories created for that user. This method should be called
2850 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002851 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002852 */
Amith Yamasani12747872015-12-07 14:19:49 -08002853 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002854 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002855 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002856 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002857
2858 final boolean isManagedProfile;
2859 synchronized (mUsersLock) {
2860 UserInfo userInfo = getUserInfoLU(userHandle);
2861 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2862 }
2863 String restriction = isManagedProfile
2864 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2865 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2866 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002867 return false;
2868 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002869 return removeUserUnchecked(userHandle);
2870 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002871
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002872 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002873 long ident = Binder.clearCallingIdentity();
2874 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002875 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002876 int currentUser = ActivityManager.getCurrentUser();
2877 if (currentUser == userHandle) {
2878 Log.w(LOG_TAG, "Current user cannot be removed");
2879 return false;
2880 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002881 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002882 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002883 userData = mUsers.get(userHandle);
2884 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002885 return false;
2886 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002887
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002888 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002889 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002890
Kenny Guyee58b4f2014-05-23 15:19:53 +01002891 // Set this to a partially created user, so that the user will be purged
2892 // on next startup, in case the runtime stops now before stopping and
2893 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002894 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002895 // Mark it as disabled, so that it isn't returned any more when
2896 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002897 userData.info.flags |= UserInfo.FLAG_DISABLED;
2898 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002899 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002900 try {
2901 mAppOpsService.removeUser(userHandle);
2902 } catch (RemoteException e) {
2903 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2904 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002905
Amith Yamasani12747872015-12-07 14:19:49 -08002906 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2907 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002908 // Send broadcast to notify system that the user removed was a
2909 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002910 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002911 }
2912
2913 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2914 int res;
2915 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002916 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002917 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002918 @Override
2919 public void userStopped(int userId) {
2920 finishRemoveUser(userId);
2921 }
2922 @Override
2923 public void userStopAborted(int userId) {
2924 }
2925 });
2926 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002927 return false;
2928 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002929 return res == ActivityManager.USER_OP_SUCCESS;
2930 } finally {
2931 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002932 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002933 }
2934
Andreas Gampea36dc622018-02-05 17:19:22 -08002935 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002936 @VisibleForTesting
2937 void addRemovingUserIdLocked(int userId) {
2938 // We remember deleted user IDs to prevent them from being
2939 // reused during the current boot; they can still be reused
2940 // after a reboot or recycling of userIds.
2941 mRemovingUserIds.put(userId, true);
2942 mRecentlyRemovedIds.add(userId);
2943 // Keep LRU queue of recently removed IDs for recycling
2944 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2945 mRecentlyRemovedIds.removeFirst();
2946 }
2947 }
2948
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002949 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002950 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002951 // Let other services shutdown any activity and clean up their state before completely
2952 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002953 long ident = Binder.clearCallingIdentity();
2954 try {
2955 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2956 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002957 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2958 android.Manifest.permission.MANAGE_USERS,
2959
2960 new BroadcastReceiver() {
2961 @Override
2962 public void onReceive(Context context, Intent intent) {
2963 if (DBG) {
2964 Slog.i(LOG_TAG,
2965 "USER_REMOVED broadcast sent, cleaning up user data "
2966 + userHandle);
2967 }
2968 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002969 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002970 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002971 // Clean up any ActivityManager state
2972 LocalServices.getService(ActivityManagerInternal.class)
2973 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002974 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002975 }
2976 }.start();
2977 }
2978 },
2979
2980 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002981 } finally {
2982 Binder.restoreCallingIdentity(ident);
2983 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002984 }
2985
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002986 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002987 try {
2988 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2989 } catch (IllegalStateException e) {
2990 // This may be simply because the user was partially created.
2991 Slog.i(LOG_TAG,
2992 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2993 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002994
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002995 // Cleanup gatekeeper secure user id
2996 try {
2997 final IGateKeeperService gk = GateKeeper.getService();
2998 if (gk != null) {
2999 gk.clearSecureUserId(userHandle);
3000 }
3001 } catch (Exception ex) {
3002 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3003 }
3004
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003005 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003006 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003007
3008 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003009 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003010 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3011
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003012 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003013 synchronized (mUsersLock) {
3014 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003015 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003016 }
3017 synchronized (mUserStates) {
3018 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003019 }
3020 synchronized (mRestrictionsLock) {
3021 mBaseUserRestrictions.remove(userHandle);
3022 mAppliedUserRestrictions.remove(userHandle);
3023 mCachedEffectiveUserRestrictions.remove(userHandle);
3024 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003025 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3026 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3027 applyUserRestrictionsForAllUsersLR();
3028 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003029 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003030 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003031 synchronized (mPackagesLock) {
3032 writeUserListLP();
3033 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003034 // Remove user file
3035 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3036 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003037 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003038 if (RELEASE_DELETED_USER_ID) {
3039 synchronized (mUsers) {
3040 mRemovingUserIds.delete(userHandle);
3041 }
3042 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003043 }
3044
Kenny Guyf8d3a232014-05-15 16:09:52 +01003045 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003046 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003047 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3048 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003049 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003050 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003051 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003052 }
3053
Amith Yamasani2a003292012-08-14 18:25:45 -07003054 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003055 public Bundle getApplicationRestrictions(String packageName) {
3056 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3057 }
3058
3059 @Override
3060 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003061 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003062 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003063 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003064 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003065 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003066 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003067 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003068 }
3069 }
3070
3071 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003072 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003073 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003074 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003075 if (restrictions != null) {
3076 restrictions.setDefusable(true);
3077 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003078 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003079 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003080 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003081 } else {
3082 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003083 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003084 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003085 }
Robin Lee66e5d962014-04-09 16:44:21 +01003086
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003087 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3088 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3089 changeIntent.setPackage(packageName);
3090 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3091 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003092 }
3093
3094 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003095 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003096 try {
3097 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003098 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003099 } catch (NameNotFoundException nnfe) {
3100 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003101 } finally {
3102 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003103 }
3104 }
3105
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003106 @GuardedBy("mAppRestrictionsLock")
3107 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003108 AtomicFile restrictionsFile =
3109 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3110 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003111 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003112 }
3113
3114 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003115 @GuardedBy("mAppRestrictionsLock")
3116 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003117 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003118 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003119 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003120 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003121 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003122
3123 FileInputStream fis = null;
3124 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003125 fis = restrictionsFile.openRead();
3126 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003127 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003128 XmlUtils.nextElement(parser);
3129 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003130 Slog.e(LOG_TAG, "Unable to read restrictions file "
3131 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003132 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003133 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003134 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3135 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003136 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003137 } catch (IOException|XmlPullParserException e) {
3138 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003139 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003140 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003141 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003142 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003143 }
3144
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003145 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3146 XmlPullParser parser) throws XmlPullParserException, IOException {
3147 int type = parser.getEventType();
3148 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3149 String key = parser.getAttributeValue(null, ATTR_KEY);
3150 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3151 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3152 if (multiple != null) {
3153 values.clear();
3154 int count = Integer.parseInt(multiple);
3155 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3156 if (type == XmlPullParser.START_TAG
3157 && parser.getName().equals(TAG_VALUE)) {
3158 values.add(parser.nextText().trim());
3159 count--;
3160 }
3161 }
3162 String [] valueStrings = new String[values.size()];
3163 values.toArray(valueStrings);
3164 restrictions.putStringArray(key, valueStrings);
3165 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3166 restrictions.putBundle(key, readBundleEntry(parser, values));
3167 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3168 final int outerDepth = parser.getDepth();
3169 ArrayList<Bundle> bundleList = new ArrayList<>();
3170 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3171 Bundle childBundle = readBundleEntry(parser, values);
3172 bundleList.add(childBundle);
3173 }
3174 restrictions.putParcelableArray(key,
3175 bundleList.toArray(new Bundle[bundleList.size()]));
3176 } else {
3177 String value = parser.nextText().trim();
3178 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3179 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3180 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3181 restrictions.putInt(key, Integer.parseInt(value));
3182 } else {
3183 restrictions.putString(key, value);
3184 }
3185 }
3186 }
3187 }
3188
3189 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3190 throws IOException, XmlPullParserException {
3191 Bundle childBundle = new Bundle();
3192 final int outerDepth = parser.getDepth();
3193 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3194 readEntry(childBundle, values, parser);
3195 }
3196 return childBundle;
3197 }
3198
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003199 @GuardedBy("mAppRestrictionsLock")
3200 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003201 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003202 AtomicFile restrictionsFile = new AtomicFile(
3203 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003204 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003205 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003206 }
3207
3208 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003209 @GuardedBy("mAppRestrictionsLock")
3210 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003211 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003212 try {
3213 fos = restrictionsFile.startWrite();
3214 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3215
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003216 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003217 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003218 serializer.startDocument(null, true);
3219 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3220
3221 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003222 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003223 serializer.endTag(null, TAG_RESTRICTIONS);
3224
3225 serializer.endDocument();
3226 restrictionsFile.finishWrite(fos);
3227 } catch (Exception e) {
3228 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003229 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3230 }
3231 }
3232
3233 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3234 throws IOException {
3235 for (String key : restrictions.keySet()) {
3236 Object value = restrictions.get(key);
3237 serializer.startTag(null, TAG_ENTRY);
3238 serializer.attribute(null, ATTR_KEY, key);
3239
3240 if (value instanceof Boolean) {
3241 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3242 serializer.text(value.toString());
3243 } else if (value instanceof Integer) {
3244 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3245 serializer.text(value.toString());
3246 } else if (value == null || value instanceof String) {
3247 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3248 serializer.text(value != null ? (String) value : "");
3249 } else if (value instanceof Bundle) {
3250 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3251 writeBundle((Bundle) value, serializer);
3252 } else if (value instanceof Parcelable[]) {
3253 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3254 Parcelable[] array = (Parcelable[]) value;
3255 for (Parcelable parcelable : array) {
3256 if (!(parcelable instanceof Bundle)) {
3257 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3258 }
3259 serializer.startTag(null, TAG_ENTRY);
3260 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3261 writeBundle((Bundle) parcelable, serializer);
3262 serializer.endTag(null, TAG_ENTRY);
3263 }
3264 } else {
3265 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3266 String[] values = (String[]) value;
3267 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3268 for (String choice : values) {
3269 serializer.startTag(null, TAG_VALUE);
3270 serializer.text(choice != null ? choice : "");
3271 serializer.endTag(null, TAG_VALUE);
3272 }
3273 }
3274 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003275 }
3276 }
3277
3278 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003279 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003280 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003281 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003282 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003283 }
3284 }
3285
3286 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003287 public boolean isUserNameSet(int userHandle) {
3288 synchronized (mUsersLock) {
3289 UserInfo userInfo = getUserInfoLU(userHandle);
3290 return userInfo != null && userInfo.name != null;
3291 }
3292 }
3293
3294 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003295 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003296 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003297 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003298 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003299 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003300 }
3301 // Not found
3302 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003303 }
3304 }
3305
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003306 @Override
3307 public long getUserCreationTime(int userHandle) {
3308 int callingUserId = UserHandle.getCallingUserId();
3309 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003310 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003311 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003312 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003313 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003314 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003315 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003316 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003317 }
3318 }
3319 }
3320 if (userInfo == null) {
3321 throw new SecurityException("userHandle can only be the calling user or a managed "
3322 + "profile associated with this user");
3323 }
3324 return userInfo.creationTime;
3325 }
3326
Amith Yamasani0b285492011-04-14 17:35:23 -07003327 /**
3328 * Caches the list of user ids in an array, adjusting the array size when necessary.
3329 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003330 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003331 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003332 synchronized (mUsersLock) {
3333 final int userSize = mUsers.size();
3334 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003335 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003336 num++;
3337 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003338 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003339 final int[] newUsers = new int[num];
3340 int n = 0;
3341 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003342 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003343 newUsers[n++] = mUsers.keyAt(i);
3344 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003345 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003346 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003347 }
3348 }
3349
3350 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003351 * Called right before a user is started. This gives us a chance to prepare
3352 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003353 */
3354 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003355 UserInfo userInfo = getUserInfo(userId);
3356 if (userInfo == null) {
3357 return;
3358 }
3359 final int userSerial = userInfo.serialNumber;
3360 // Migrate only if build fingerprints mismatch
3361 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003362 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003363 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003364
3365 if (userId != UserHandle.USER_SYSTEM) {
3366 synchronized (mRestrictionsLock) {
3367 applyUserRestrictionsLR(userId);
3368 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003369 }
3370 }
3371
3372 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003373 * Called right before a user is unlocked. This gives us a chance to prepare
3374 * app storage.
3375 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003376 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003377 UserInfo userInfo = getUserInfo(userId);
3378 if (userInfo == null) {
3379 return;
3380 }
3381 final int userSerial = userInfo.serialNumber;
3382 // Migrate only if build fingerprints mismatch
3383 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003384 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003385 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003386 }
3387
3388 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003389 * Examine all users present on given mounted volume, and destroy data
3390 * belonging to users that are no longer valid, or whose user ID has been
3391 * recycled.
3392 */
3393 void reconcileUsers(String volumeUuid) {
3394 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3395 }
3396
3397 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003398 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003399 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003400 * @param userId the user that was just foregrounded
3401 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003402 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003403 UserData userData = getUserDataNoChecks(userId);
3404 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003405 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3406 return;
3407 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003408
3409 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003410 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003411 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003412 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003413 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3414 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003415 }
3416
3417 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003418 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003419 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003420 @VisibleForTesting
3421 int getNextAvailableId() {
3422 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003423 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003424 nextId = scanNextAvailableIdLocked();
3425 if (nextId >= 0) {
3426 return nextId;
3427 }
3428 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3429 // except most recently removed
3430 if (mRemovingUserIds.size() > 0) {
3431 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3432 mRemovingUserIds.clear();
3433 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3434 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003435 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003436 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003437 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003438 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003439 if (nextId < 0) {
3440 throw new IllegalStateException("No user id available!");
3441 }
3442 return nextId;
3443 }
3444
Andreas Gampea36dc622018-02-05 17:19:22 -08003445 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003446 private int scanNextAvailableIdLocked() {
3447 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3448 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3449 return i;
3450 }
3451 }
3452 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003453 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003454
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003455 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003456 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3457 }
3458
Amith Yamasani920ace02012-09-20 22:15:37 -07003459 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003460 public void setSeedAccountData(int userId, String accountName, String accountType,
3461 PersistableBundle accountOptions, boolean persist) {
3462 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3463 synchronized (mPackagesLock) {
3464 final UserData userData;
3465 synchronized (mUsersLock) {
3466 userData = getUserDataLU(userId);
3467 if (userData == null) {
3468 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3469 return;
3470 }
3471 userData.seedAccountName = accountName;
3472 userData.seedAccountType = accountType;
3473 userData.seedAccountOptions = accountOptions;
3474 userData.persistSeedData = persist;
3475 }
3476 if (persist) {
3477 writeUserLP(userData);
3478 }
3479 }
3480 }
3481
3482 @Override
3483 public String getSeedAccountName() throws RemoteException {
3484 checkManageUsersPermission("Cannot get seed account information");
3485 synchronized (mUsersLock) {
3486 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3487 return userData.seedAccountName;
3488 }
3489 }
3490
3491 @Override
3492 public String getSeedAccountType() throws RemoteException {
3493 checkManageUsersPermission("Cannot get seed account information");
3494 synchronized (mUsersLock) {
3495 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3496 return userData.seedAccountType;
3497 }
3498 }
3499
3500 @Override
3501 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3502 checkManageUsersPermission("Cannot get seed account information");
3503 synchronized (mUsersLock) {
3504 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3505 return userData.seedAccountOptions;
3506 }
3507 }
3508
3509 @Override
3510 public void clearSeedAccountData() throws RemoteException {
3511 checkManageUsersPermission("Cannot clear seed account information");
3512 synchronized (mPackagesLock) {
3513 UserData userData;
3514 synchronized (mUsersLock) {
3515 userData = getUserDataLU(UserHandle.getCallingUserId());
3516 if (userData == null) return;
3517 userData.clearSeedAccountData();
3518 }
3519 writeUserLP(userData);
3520 }
3521 }
3522
3523 @Override
3524 public boolean someUserHasSeedAccount(String accountName, String accountType)
3525 throws RemoteException {
3526 checkManageUsersPermission("Cannot check seed account information");
3527 synchronized (mUsersLock) {
3528 final int userSize = mUsers.size();
3529 for (int i = 0; i < userSize; i++) {
3530 final UserData data = mUsers.valueAt(i);
3531 if (data.info.isInitialized()) continue;
3532 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3533 continue;
3534 }
3535 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3536 continue;
3537 }
3538 return true;
3539 }
3540 }
3541 return false;
3542 }
3543
3544 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003545 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003546 FileDescriptor err, String[] args, ShellCallback callback,
3547 ResultReceiver resultReceiver) {
3548 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003549 }
3550
3551 int onShellCommand(Shell shell, String cmd) {
3552 if (cmd == null) {
3553 return shell.handleDefaultCommands(cmd);
3554 }
3555
3556 final PrintWriter pw = shell.getOutPrintWriter();
3557 try {
3558 switch(cmd) {
3559 case "list":
3560 return runList(pw);
3561 }
3562 } catch (RemoteException e) {
3563 pw.println("Remote exception: " + e);
3564 }
3565 return -1;
3566 }
3567
3568 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003569 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003570 final List<UserInfo> users = getUsers(false);
3571 if (users == null) {
3572 pw.println("Error: couldn't get users");
3573 return 1;
3574 } else {
3575 pw.println("Users:");
3576 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003577 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003578 pw.println("\t" + users.get(i).toString() + running);
3579 }
3580 return 0;
3581 }
3582 }
3583
3584 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003585 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003586 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003587
3588 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003589 final long nowRealtime = SystemClock.elapsedRealtime();
Amith Yamasani920ace02012-09-20 22:15:37 -07003590 StringBuilder sb = new StringBuilder();
3591 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003592 synchronized (mUsersLock) {
3593 pw.println("Users:");
3594 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003595 UserData userData = mUsers.valueAt(i);
3596 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003597 continue;
3598 }
Amith Yamasani12747872015-12-07 14:19:49 -08003599 UserInfo userInfo = userData.info;
3600 final int userId = userInfo.id;
3601 pw.print(" "); pw.print(userInfo);
3602 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003603 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003604 pw.print(" <removing> ");
3605 }
Amith Yamasani12747872015-12-07 14:19:49 -08003606 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003607 pw.print(" <partial>");
3608 }
3609 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003610 pw.print(" State: ");
3611 final int state;
3612 synchronized (mUserStates) {
3613 state = mUserStates.get(userId, -1);
3614 }
3615 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003616 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003617 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3618
Fyodor Kupolov82402752015-10-28 14:54:51 -07003619 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003620 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3621
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003622 pw.print(" Last logged in fingerprint: ");
3623 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003624
3625 pw.print(" Start time: ");
3626 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3627
3628 pw.print(" Unlock time: ");
3629 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3630
Makoto Onukie7927da2015-11-25 10:05:17 -08003631 pw.print(" Has profile owner: ");
3632 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003633 pw.println(" Restrictions:");
3634 synchronized (mRestrictionsLock) {
3635 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003636 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003637 pw.println(" Device policy global restrictions:");
3638 UserRestrictionsUtils.dumpRestrictions(
3639 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003640 pw.println(" Device policy local restrictions:");
3641 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003642 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003643 pw.println(" Effective restrictions:");
3644 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003645 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003646 }
Amith Yamasani12747872015-12-07 14:19:49 -08003647
3648 if (userData.account != null) {
3649 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003650 pw.println();
3651 }
Amith Yamasani12747872015-12-07 14:19:49 -08003652
3653 if (userData.seedAccountName != null) {
3654 pw.print(" Seed account name: " + userData.seedAccountName);
3655 pw.println();
3656 if (userData.seedAccountType != null) {
3657 pw.print(" account type: " + userData.seedAccountType);
3658 pw.println();
3659 }
3660 if (userData.seedAccountOptions != null) {
3661 pw.print(" account options exist");
3662 pw.println();
3663 }
3664 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003665 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003666 }
Amith Yamasani12747872015-12-07 14:19:49 -08003667 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003668 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003669 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003670 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003671 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003672 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003673 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003674 synchronized (mUsersLock) {
3675 pw.println();
3676 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003677 if (mRemovingUserIds.size() > 0) {
3678 pw.println();
3679 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3680 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003681 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003682 synchronized (mUserStates) {
3683 pw.println(" Started users state: " + mUserStates);
3684 }
Amith Yamasani12747872015-12-07 14:19:49 -08003685 // Dump some capabilities
3686 pw.println();
3687 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3688 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003689 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3690 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003691 }
3692 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003693
Makoto Onuki73dded22017-12-20 13:14:48 +09003694 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3695 if (time == 0) {
3696 pw.println("<unknown>");
3697 } else {
3698 sb.setLength(0);
3699 TimeUtils.formatDuration(nowTime - time, sb);
3700 sb.append(" ago");
3701 pw.println(sb);
3702 }
3703 }
3704
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003705 final class MainHandler extends Handler {
3706
3707 @Override
3708 public void handleMessage(Message msg) {
3709 switch (msg.what) {
3710 case WRITE_USER_MSG:
3711 removeMessages(WRITE_USER_MSG, msg.obj);
3712 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003713 int userId = ((UserData) msg.obj).info.id;
3714 UserData userData = getUserDataNoChecks(userId);
3715 if (userData != null) {
3716 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003717 }
3718 }
3719 }
3720 }
3721 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003722
3723 /**
3724 * @param userId
3725 * @return whether the user has been initialized yet
3726 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003727 boolean isUserInitialized(int userId) {
3728 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003729 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003730
3731 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003732 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003733 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3734 boolean isDeviceOwner, int cameraRestrictionScope) {
3735 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3736 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003737 }
3738
3739 @Override
3740 public Bundle getBaseUserRestrictions(int userId) {
3741 synchronized (mRestrictionsLock) {
3742 return mBaseUserRestrictions.get(userId);
3743 }
3744 }
3745
3746 @Override
3747 public void setBaseUserRestrictionsByDpmsForMigration(
3748 int userId, Bundle baseRestrictions) {
3749 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003750 if (updateRestrictionsIfNeededLR(
3751 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3752 invalidateEffectiveUserRestrictionsLR(userId);
3753 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003754 }
3755
Amith Yamasani12747872015-12-07 14:19:49 -08003756 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003757 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003758 if (userData != null) {
3759 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003760 } else {
3761 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3762 }
3763 }
3764 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003765
3766 @Override
3767 public boolean getUserRestriction(int userId, String key) {
3768 return getUserRestrictions(userId).getBoolean(key);
3769 }
3770
3771 @Override
3772 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3773 synchronized (mUserRestrictionsListeners) {
3774 mUserRestrictionsListeners.add(listener);
3775 }
3776 }
3777
3778 @Override
3779 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3780 synchronized (mUserRestrictionsListeners) {
3781 mUserRestrictionsListeners.remove(listener);
3782 }
3783 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003784
3785 @Override
3786 public void setDeviceManaged(boolean isManaged) {
3787 synchronized (mUsersLock) {
3788 mIsDeviceManaged = isManaged;
3789 }
3790 }
3791
3792 @Override
3793 public void setUserManaged(int userId, boolean isManaged) {
3794 synchronized (mUsersLock) {
3795 mIsUserManaged.put(userId, isManaged);
3796 }
3797 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003798
3799 @Override
3800 public void setUserIcon(int userId, Bitmap bitmap) {
3801 long ident = Binder.clearCallingIdentity();
3802 try {
3803 synchronized (mPackagesLock) {
3804 UserData userData = getUserDataNoChecks(userId);
3805 if (userData == null || userData.info.partial) {
3806 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3807 return;
3808 }
3809 writeBitmapLP(userData.info, bitmap);
3810 writeUserLP(userData);
3811 }
3812 sendUserInfoChangedBroadcast(userId);
3813 } finally {
3814 Binder.restoreCallingIdentity(ident);
3815 }
3816 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003817
3818 @Override
3819 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3820 synchronized (mUsersLock) {
3821 mForceEphemeralUsers = forceEphemeralUsers;
3822 }
3823 }
3824
3825 @Override
3826 public void removeAllUsers() {
3827 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3828 // Remove the non-system users straight away.
3829 removeNonSystemUsers();
3830 } else {
3831 // Switch to the system user first and then remove the other users.
3832 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3833 @Override
3834 public void onReceive(Context context, Intent intent) {
3835 int userId =
3836 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3837 if (userId != UserHandle.USER_SYSTEM) {
3838 return;
3839 }
3840 mContext.unregisterReceiver(this);
3841 removeNonSystemUsers();
3842 }
3843 };
3844 IntentFilter userSwitchedFilter = new IntentFilter();
3845 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3846 mContext.registerReceiver(
3847 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3848
3849 // Switch to the system user.
3850 ActivityManager am =
3851 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3852 am.switchUser(UserHandle.USER_SYSTEM);
3853 }
3854 }
phweisse9c44062016-02-10 12:57:38 +01003855
3856 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003857 public void onEphemeralUserStop(int userId) {
3858 synchronized (mUsersLock) {
3859 UserInfo userInfo = getUserInfoLU(userId);
3860 if (userInfo != null && userInfo.isEphemeral()) {
3861 // Do not allow switching back to the ephemeral user again as the user is going
3862 // to be deleted.
3863 userInfo.flags |= UserInfo.FLAG_DISABLED;
3864 if (userInfo.isGuest()) {
3865 // Indicate that the guest will be deleted after it stops.
3866 userInfo.guestToRemove = true;
3867 }
3868 }
3869 }
3870 }
3871
3872 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003873 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3874 String[] disallowedPackages) {
3875 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3876 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003877 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003878 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003879 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3880 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3881 }
3882 return user;
3883 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003884
3885 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003886 public boolean removeUserEvenWhenDisallowed(int userId) {
3887 return removeUserUnchecked(userId);
3888 }
3889
3890 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003891 public boolean isUserRunning(int userId) {
3892 synchronized (mUserStates) {
3893 return mUserStates.get(userId, -1) >= 0;
3894 }
3895 }
3896
3897 @Override
3898 public void setUserState(int userId, int userState) {
3899 synchronized (mUserStates) {
3900 mUserStates.put(userId, userState);
3901 }
3902 }
3903
3904 @Override
3905 public void removeUserState(int userId) {
3906 synchronized (mUserStates) {
3907 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003908 }
3909 }
3910
3911 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003912 public int[] getUserIds() {
3913 return UserManagerService.this.getUserIds();
3914 }
3915
3916 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003917 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003918 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003919 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003920 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003921 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003922 // Special case, in the stopping/shutdown state user key can still be unlocked
3923 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3924 return StorageManager.isUserKeyUnlocked(userId);
3925 }
3926 return (state == UserState.STATE_RUNNING_UNLOCKING)
3927 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003928 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003929
3930 @Override
3931 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003932 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003933 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003934 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003935 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003936 // Special case, in the stopping/shutdown state user key can still be unlocked
3937 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3938 return StorageManager.isUserKeyUnlocked(userId);
3939 }
3940 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003941 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003942
3943 @Override
3944 public boolean isUserInitialized(int userId) {
3945 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3946 }
3947
3948 @Override
3949 public boolean exists(int userId) {
3950 return getUserInfoNoChecks(userId) != null;
3951 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08003952
3953 @Override
3954 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
3955 boolean throwSecurityException) {
3956 if (targetUserId == callingUserId) {
3957 return true;
3958 }
3959 synchronized (mUsersLock) {
3960 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
3961 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
3962 if (throwSecurityException) {
3963 throw new SecurityException(
3964 debugMsg + " for another profile "
3965 + targetUserId + " from " + callingUserId);
3966 }
3967 }
3968
3969 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
3970 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
3971 // Do not throw any exception here as this could happen due to race conditions
3972 // between the system updating its state and the client getting notified.
3973 if (throwSecurityException) {
3974 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
3975 + targetUserId + " from " + callingUserId);
3976 }
3977 return false;
3978 }
3979
3980 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
3981 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
3982 if (throwSecurityException) {
3983 throw new SecurityException(
3984 debugMsg + " for unrelated profile " + targetUserId);
3985 }
3986 return false;
3987 }
3988 }
3989 return true;
3990 }
3991
3992 @Override
3993 public int getProfileParentId(int userId) {
3994 synchronized (mUsersLock) {
3995 UserInfo profileParent = getProfileParentLU(userId);
3996 if (profileParent == null) {
3997 return userId;
3998 }
3999 return profileParent.id;
4000 }
4001 }
yuemingw1d13eae2018-01-30 17:27:54 +00004002
4003 @Override
4004 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4005 String value, int callingUid) {
4006 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4007 value, callingUid);
4008 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004009 }
4010
4011 /* Remove all the users except of the system one. */
4012 private void removeNonSystemUsers() {
4013 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4014 synchronized (mUsersLock) {
4015 final int userSize = mUsers.size();
4016 for (int i = 0; i < userSize; i++) {
4017 UserInfo ui = mUsers.valueAt(i).info;
4018 if (ui.id != UserHandle.USER_SYSTEM) {
4019 usersToRemove.add(ui);
4020 }
4021 }
4022 }
4023 for (UserInfo ui: usersToRemove) {
4024 removeUser(ui.id);
4025 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004026 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004027
4028 private class Shell extends ShellCommand {
4029 @Override
4030 public int onCommand(String cmd) {
4031 return onShellCommand(this, cmd);
4032 }
4033
4034 @Override
4035 public void onHelp() {
4036 final PrintWriter pw = getOutPrintWriter();
4037 pw.println("User manager (user) commands:");
4038 pw.println(" help");
4039 pw.println(" Print this help text.");
4040 pw.println("");
4041 pw.println(" list");
4042 pw.println(" Prints all users on the system.");
4043 }
4044 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004045
4046 private static void debug(String message) {
4047 Log.d(LOG_TAG, message +
4048 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4049 }
Kenny Guy02c89902016-11-15 19:36:38 +00004050
4051 @VisibleForTesting
4052 static int getMaxManagedProfiles() {
4053 // Allow overriding max managed profiles on debuggable builds for testing
4054 // of multiple profiles.
4055 if (!Build.IS_DEBUGGABLE) {
4056 return MAX_MANAGED_PROFILES;
4057 } else {
4058 return SystemProperties.getInt("persist.sys.max_profiles",
4059 MAX_MANAGED_PROFILES);
4060 }
4061 }
4062
4063 @VisibleForTesting
4064 int getFreeProfileBadgeLU(int parentUserId) {
4065 int maxManagedProfiles = getMaxManagedProfiles();
4066 boolean[] usedBadges = new boolean[maxManagedProfiles];
4067 final int userSize = mUsers.size();
4068 for (int i = 0; i < userSize; i++) {
4069 UserInfo ui = mUsers.valueAt(i).info;
4070 // Check which badge indexes are already used by this profile group.
4071 if (ui.isManagedProfile()
4072 && ui.profileGroupId == parentUserId
4073 && !mRemovingUserIds.get(ui.id)
4074 && ui.profileBadge < maxManagedProfiles) {
4075 usedBadges[ui.profileBadge] = true;
4076 }
4077 }
4078 for (int i = 0; i < maxManagedProfiles; i++) {
4079 if (!usedBadges[i]) {
4080 return i;
4081 }
4082 }
4083 return 0;
4084 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004085
4086 /**
4087 * Checks if the given user has a managed profile associated with it.
4088 * @param userId The parent user
4089 * @return
4090 */
4091 boolean hasManagedProfile(int userId) {
4092 synchronized (mUsersLock) {
4093 UserInfo userInfo = getUserInfoLU(userId);
4094 final int userSize = mUsers.size();
4095 for (int i = 0; i < userSize; i++) {
4096 UserInfo profile = mUsers.valueAt(i).info;
4097 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4098 return true;
4099 }
4100 }
4101 return false;
4102 }
4103 }
Tony Makd390ae92017-12-28 13:23:10 +00004104
4105 /**
4106 * Check if the calling package name matches with the calling UID, throw
4107 * {@link SecurityException} if not.
4108 */
4109 private void verifyCallingPackage(String callingPackage, int callingUid) {
4110 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4111 if (packageUid != callingUid) {
4112 throw new SecurityException("Specified package " + callingPackage
4113 + " does not match the calling uid " + callingUid);
4114 }
4115 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004116}