blob: 829dd0f3cb067496012481fddf8e3fc372c88bba [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;
arangelov9b632d72018-12-07 23:21:22 +000034import android.app.admin.DevicePolicyEventLogger;
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;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070075import android.security.GateKeeper;
76import android.service.gatekeeper.IGateKeeperService;
arangelov9b632d72018-12-07 23:21:22 +000077import android.stats.devicepolicy.DevicePolicyEnums;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080092import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060093import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080094import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070095import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070096import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000097import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070098import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060099import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700100import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000101import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700102import com.android.server.storage.DeviceStorageMonitorInternal;
Felipe Leme3aad1be2019-05-31 11:43:12 -0700103import com.android.server.utils.TimingsTraceAndSlog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700104import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800105
arangelov9b632d72018-12-07 23:21:22 +0000106import libcore.io.IoUtils;
107
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800108import org.xmlpull.v1.XmlPullParser;
109import org.xmlpull.v1.XmlPullParserException;
110import org.xmlpull.v1.XmlSerializer;
111
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112import java.io.BufferedOutputStream;
113import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700114import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700116import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000118import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000119import java.io.InputStream;
120import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700121import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100122import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100124import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700125import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000127import java.util.Objects;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128
Makoto Onuki068c54a2015-10-13 14:34:03 -0700129/**
130 * Service for {@link UserManager}.
131 *
132 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700133 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700134 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800135 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700136 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
137 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
138 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700139 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700140public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700141
Amith Yamasani2a003292012-08-14 18:25:45 -0700142 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800143 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800144 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700145 // Can be used for manual testing of id recycling
146 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700147
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700148 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800149 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700151 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700153 private static final String ATTR_CREATION_TIME = "created";
154 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600155 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700156 private static final String ATTR_SERIAL_NO = "serialNumber";
157 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700158 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700159 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700160 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100161 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000162 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700163 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800164 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
165 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530166 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700168 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800169 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800170 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100171 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
172 "device_policy_global_restrictions";
173 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100174 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100175 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String TAG_ENTRY = "entry";
177 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800178 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000179 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
180 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800181 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700182 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800183 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700184
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700185 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
186 private static final String ATTR_TYPE_STRING = "s";
187 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700188 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700189 private static final String ATTR_TYPE_BUNDLE = "B";
190 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700191
Amith Yamasani0b285492011-04-14 17:35:23 -0700192 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700193 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700194 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100195 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700196
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800197 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700198 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800199
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700200 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
201 UserInfo.FLAG_MANAGED_PROFILE
202 | UserInfo.FLAG_EPHEMERAL
203 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700204 | UserInfo.FLAG_GUEST
205 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700206
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700207 @VisibleForTesting
208 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700209 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700210 @VisibleForTesting
211 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
212
213 // Max size of the queue of recently removed users
214 @VisibleForTesting
215 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700216
Pavel Grafov6a40f092016-10-25 15:46:51 +0100217 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700218
Amith Yamasani920ace02012-09-20 22:15:37 -0700219 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
220
Nicolas Prevotb8186812015-08-06 15:00:03 +0100221 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700222 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000223 @VisibleForTesting
224 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700225
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800226 static final int WRITE_USER_MSG = 1;
227 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530228
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800229 // Tron counters
230 private static final String TRON_GUEST_CREATED = "users_guest_created";
231 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700232 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800233
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 private final Context mContext;
235 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700236 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800237 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700238 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600239 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700240 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700241 // Used for serializing access to app restriction files
242 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700243
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800244 private final Handler mHandler;
245
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700246 private final File mUsersDir;
247 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700248
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800249 private static final IBinder mUserRestriconToken = new Binder();
250
Makoto Onuki068c54a2015-10-13 14:34:03 -0700251 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900252 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800253 */
Kenny Guy02c89902016-11-15 19:36:38 +0000254 @VisibleForTesting
255 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800256 // Basic user information and properties
257 UserInfo info;
258 // Account name used when there is a strong association between a user and an account
259 String account;
260 // Account information for seeding into a newly created user. This could also be
261 // used for login validation for an existing user, for updating their credentials.
262 // In the latter case, data may not need to be persisted as it is only valid for the
263 // current login session.
264 String seedAccountName;
265 String seedAccountType;
266 PersistableBundle seedAccountOptions;
267 // Whether to perist the seed account information to be available after a boot
268 boolean persistSeedData;
269
Makoto Onuki73dded22017-12-20 13:14:48 +0900270 /** Elapsed realtime since boot when the user started. */
271 long startRealtime;
272
273 /** Elapsed realtime since boot when the user was unlocked. */
274 long unlockRealtime;
275
arangelov9b632d72018-12-07 23:21:22 +0000276 private long mLastRequestQuietModeEnabledMillis;
277
278 void setLastRequestQuietModeEnabledMillis(long millis) {
279 mLastRequestQuietModeEnabledMillis = millis;
280 }
281
282 long getLastRequestQuietModeEnabledMillis() {
283 return mLastRequestQuietModeEnabledMillis;
284 }
285
Amith Yamasani12747872015-12-07 14:19:49 -0800286 void clearSeedAccountData() {
287 seedAccountName = null;
288 seedAccountType = null;
289 seedAccountOptions = null;
290 persistSeedData = false;
291 }
292 }
293
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800294 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800295 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800296
297 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700298 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100299 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700300 *
301 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
302 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
303 * maybe shared between {@link #mBaseUserRestrictions} and
304 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
305 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700306 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700307 */
308 @GuardedBy("mRestrictionsLock")
309 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
310
311 /**
312 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
313 * with device / profile owner restrictions. We'll initialize it lazily; use
314 * {@link #getEffectiveUserRestrictions} to access it.
315 *
316 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
317 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
318 * maybe shared between {@link #mBaseUserRestrictions} and
319 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
320 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700321 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700322 */
323 @GuardedBy("mRestrictionsLock")
324 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
325
Makoto Onuki4f160732015-10-27 17:15:38 -0700326 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800327 * User restrictions that have already been applied in
328 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
329 * that have changed since the last
330 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700331 */
332 @GuardedBy("mRestrictionsLock")
333 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
334
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800335 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800336 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100337 * that should be applied to all users, including guests. Only non-empty restriction bundles are
338 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800339 */
340 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100341 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800342
343 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100344 * Id of the user that set global restrictions.
345 */
346 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100347 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100348
349 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800350 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100351 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800352 */
353 @GuardedBy("mRestrictionsLock")
354 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
355
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800356 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530357 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800358
359 /**
360 * Set of user IDs being actively removed. Removed IDs linger in this set
361 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700362 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800363 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700364 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800365 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700366
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700367 /**
368 * Queue of recently removed userIds. Used for recycling of userIds
369 */
370 @GuardedBy("mUsersLock")
371 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
372
Fyodor Kupolov82402752015-10-28 14:54:51 -0700373 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700374 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800375 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700376 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700377 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700378
Jason Monk62062992014-05-06 09:55:28 -0400379 private IAppOpsService mAppOpsService;
380
Makoto Onuki068c54a2015-10-13 14:34:03 -0700381 private final LocalService mLocalService;
382
Makoto Onukie7927da2015-11-25 10:05:17 -0800383 @GuardedBy("mUsersLock")
384 private boolean mIsDeviceManaged;
385
386 @GuardedBy("mUsersLock")
387 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
388
Makoto Onukid45a4a22015-11-02 17:17:38 -0800389 @GuardedBy("mUserRestrictionsListeners")
390 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
391 new ArrayList<>();
392
Clara Bayarria1771112015-12-18 16:29:18 +0000393 private final LockPatternUtils mLockPatternUtils;
394
Ricky Waib1dd80b2016-06-07 18:00:55 +0100395 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
396 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
397
398 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
399 @Override
400 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000401 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
402 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100403 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000404 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
405 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800406 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000407 BackgroundThread.getHandler().post(() ->
408 setQuietModeEnabled(userHandle, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100409 }
410 };
411
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100412 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000413 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
414 *
Tony Makbece85d2018-01-12 12:10:17 +0000415 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000416 */
417 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
418 private final IntentSender mTarget;
419
420 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
421 Preconditions.checkNotNull(target);
422 mTarget = target;
423 }
424
425 @Override
426 public void onStarted(int id, Bundle extras) {}
427
428 @Override
429 public void onProgress(int id, int progress, Bundle extras) {}
430
431 @Override
432 public void onFinished(int id, Bundle extras) {
433 try {
434 mContext.startIntentSender(mTarget, null, 0, 0, 0);
435 } catch (IntentSender.SendIntentException e) {
436 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
437 }
438 }
439 }
440
441 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100442 * Whether all users should be created ephemeral.
443 */
444 @GuardedBy("mUsersLock")
445 private boolean mForceEphemeralUsers;
446
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000447 @GuardedBy("mUserStates")
448 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700449
Amith Yamasani258848d2012-08-10 17:06:33 -0700450 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700451
Dianne Hackborn4428e172012-08-24 17:43:05 -0700452 public static UserManagerService getInstance() {
453 synchronized (UserManagerService.class) {
454 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700455 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700456 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700457
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700458 public static class LifeCycle extends SystemService {
459
460 private UserManagerService mUms;
461
462 /**
463 * @param context
464 */
465 public LifeCycle(Context context) {
466 super(context);
467 }
468
469 @Override
470 public void onStart() {
471 mUms = UserManagerService.getInstance();
472 publishBinderService(Context.USER_SERVICE, mUms);
473 }
474
475 @Override
476 public void onBootPhase(int phase) {
477 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
478 mUms.cleanupPartialUsers();
479 }
480 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900481
482 @Override
483 public void onStartUser(int userHandle) {
484 synchronized (mUms.mUsersLock) {
485 final UserData user = mUms.getUserDataLU(userHandle);
486 if (user != null) {
487 user.startRealtime = SystemClock.elapsedRealtime();
488 }
489 }
490 }
491
492 @Override
493 public void onUnlockUser(int userHandle) {
494 synchronized (mUms.mUsersLock) {
495 final UserData user = mUms.getUserDataLU(userHandle);
496 if (user != null) {
497 user.unlockRealtime = SystemClock.elapsedRealtime();
498 }
499 }
500 }
501
502 @Override
503 public void onStopUser(int userHandle) {
504 synchronized (mUms.mUsersLock) {
505 final UserData user = mUms.getUserDataLU(userHandle);
506 if (user != null) {
507 user.startRealtime = 0;
508 user.unlockRealtime = 0;
509 }
510 }
511 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700512 }
513
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700514 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800515 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700516 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800517 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700518 }
519
Dianne Hackborn4428e172012-08-24 17:43:05 -0700520 /**
521 * Called by package manager to create the service. This is closely
522 * associated with the package manager, and the given lock is the
523 * package manager's own lock.
524 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800525 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
526 Object packagesLock) {
527 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700528 }
529
Dianne Hackborn4428e172012-08-24 17:43:05 -0700530 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800531 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700532 mContext = context;
533 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700534 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800535 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800536 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800537 synchronized (mPackagesLock) {
538 mUsersDir = new File(dataDir, USER_INFO_DIR);
539 mUsersDir.mkdirs();
540 // Make zeroth user directory, for services to migrate their files to that location
541 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
542 userZeroDir.mkdirs();
543 FileUtils.setPermissions(mUsersDir.toString(),
544 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
545 -1, -1);
546 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
547 initDefaultGuestRestrictions();
548 readUserListLP();
549 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700550 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700551 mLocalService = new LocalService();
552 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000553 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000554 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700555 }
556
557 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400558 mAppOpsService = IAppOpsService.Stub.asInterface(
559 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800560
561 synchronized (mRestrictionsLock) {
562 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400563 }
Samuel Tand9453b82016-03-14 15:57:02 -0700564
565 UserInfo currentGuestUser = findCurrentGuestUser();
566 if (currentGuestUser != null && !hasUserRestriction(
567 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
568 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
569 // to it, in case this guest was created in a previous version where this
570 // user restriction was not a default guest restriction.
571 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
572 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700573
Ricky Waib1dd80b2016-06-07 18:00:55 +0100574 mContext.registerReceiver(mDisableQuietModeCallback,
575 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
576 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700577 }
578
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700579 void cleanupPartialUsers() {
580 // Prune out any partially created, partially removed and ephemeral users.
581 ArrayList<UserInfo> partials = new ArrayList<>();
582 synchronized (mUsersLock) {
583 final int userSize = mUsers.size();
584 for (int i = 0; i < userSize; i++) {
585 UserInfo ui = mUsers.valueAt(i).info;
586 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
587 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700588 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700589 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700590 }
591 }
592 }
593 final int partialsSize = partials.size();
594 for (int i = 0; i < partialsSize; i++) {
595 UserInfo ui = partials.get(i);
596 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
597 + " (name=" + ui.name + ")");
598 removeUserState(ui.id);
599 }
600 }
601
Amith Yamasani258848d2012-08-10 17:06:33 -0700602 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800603 public String getUserAccount(int userId) {
604 checkManageUserAndAcrossUsersFullPermission("get user account");
605 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800606 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800607 }
608 }
609
610 @Override
611 public void setUserAccount(int userId, String accountName) {
612 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800613 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800614 synchronized (mPackagesLock) {
615 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800616 final UserData userData = mUsers.get(userId);
617 if (userData == null) {
618 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
619 return;
620 }
621 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000622 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800623 userData.account = accountName;
624 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800625 }
626 }
627
628 if (userToUpdate != null) {
629 writeUserLP(userToUpdate);
630 }
631 }
632 }
633
634 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700635 public UserInfo getPrimaryUser() {
636 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700637 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700638 final int userSize = mUsers.size();
639 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800640 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800641 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700642 return ui;
643 }
644 }
645 }
646 return null;
647 }
648
649 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700650 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700651 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700652 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700653 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700654 final int userSize = mUsers.size();
655 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800656 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700657 if (ui.partial) {
658 continue;
659 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800660 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700661 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700662 }
Amith Yamasani13593602012-03-22 16:16:17 -0700663 }
664 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700665 }
Amith Yamasani13593602012-03-22 16:16:17 -0700666 }
667
Amith Yamasani258848d2012-08-10 17:06:33 -0700668 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100669 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700670 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800671 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700672 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700673 } else {
674 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800675 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700676 final long ident = Binder.clearCallingIdentity();
677 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700678 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700679 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100680 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700681 } finally {
682 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000683 }
684 }
685
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700686 @Override
687 public int[] getProfileIds(int userId, boolean enabledOnly) {
688 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700689 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700690 }
691 final long ident = Binder.clearCallingIdentity();
692 try {
693 synchronized (mUsersLock) {
694 return getProfileIdsLU(userId, enabledOnly).toArray();
695 }
696 } finally {
697 Binder.restoreCallingIdentity(ident);
698 }
699 }
700
Amith Yamasanibe465322014-04-24 13:45:17 -0700701 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700702 @GuardedBy("mUsersLock")
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700703 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700704 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
705 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
706 for (int i = 0; i < profileIds.size(); i++) {
707 int profileId = profileIds.get(i);
708 UserInfo userInfo = mUsers.get(profileId).info;
709 // If full info is not required - clear PII data to prevent 3P apps from reading it
710 if (!fullInfo) {
711 userInfo = new UserInfo(userInfo);
712 userInfo.name = null;
713 userInfo.iconPath = null;
714 } else {
715 userInfo = userWithName(userInfo);
716 }
717 users.add(userInfo);
718 }
719 return users;
720 }
721
722 /**
723 * Assume permissions already checked and caller's identity cleared
724 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700725 @GuardedBy("mUsersLock")
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700726 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700727 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700728 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700729 if (user == null) {
730 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700731 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700732 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700733 final int userSize = mUsers.size();
734 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800735 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700736 if (!isProfileOf(user, profile)) {
737 continue;
738 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100739 if (enabledOnly && !profile.isEnabled()) {
740 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700741 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700742 if (mRemovingUserIds.get(profile.id)) {
743 continue;
744 }
Tony Mak80189cd2016-04-05 17:21:42 +0100745 if (profile.partial) {
746 continue;
747 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700748 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700749 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700750 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700751 }
752
Jessica Hummelbe81c802014-04-22 15:49:22 +0100753 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700754 public int getCredentialOwnerProfile(int userHandle) {
755 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000756 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700757 synchronized (mUsersLock) {
758 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700759 if (profileParent != null) {
760 return profileParent.id;
761 }
762 }
763 }
764
765 return userHandle;
766 }
767
768 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700769 public boolean isSameProfileGroup(int userId, int otherUserId) {
770 if (userId == otherUserId) return true;
771 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700772 return isSameProfileGroupNoChecks(userId, otherUserId);
773 }
774
775 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700776 synchronized (mUsersLock) {
777 UserInfo userInfo = getUserInfoLU(userId);
778 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
779 return false;
780 }
781 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
782 if (otherUserInfo == null
783 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
784 return false;
785 }
786 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700787 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700788 }
789
790 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100791 public UserInfo getProfileParent(int userHandle) {
792 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700793 synchronized (mUsersLock) {
794 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700795 }
796 }
797
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800798 @Override
799 public int getProfileParentId(int userHandle) {
800 checkManageUsersPermission("get the profile parent");
Sunny Goyal145c8f82018-02-15 14:27:09 -0800801 return mLocalService.getProfileParentId(userHandle);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800802 }
803
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700804 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700805 private UserInfo getProfileParentLU(int userHandle) {
806 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700807 if (profile == null) {
808 return null;
809 }
810 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800811 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700812 return null;
813 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700814 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100815 }
816 }
817
Fyodor Kupolov82402752015-10-28 14:54:51 -0700818 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100819 return user.id == profile.id ||
820 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
821 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000822 }
823
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000824 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000825 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100826 Intent intent = new Intent();
827 if (inQuietMode) {
828 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
829 } else {
830 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
831 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000832 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
833 intent.putExtra(Intent.EXTRA_USER, profileHandle);
834 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000835 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000836 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000837 }
838
839 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000840 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000841 int userHandle, @Nullable IntentSender target) {
842 Preconditions.checkNotNull(callingPackage);
843
Tony Makb7e6fd42017-12-05 19:40:28 +0000844 if (enableQuietMode && target != null) {
845 throw new IllegalArgumentException(
846 "target should only be specified when we are disabling quiet mode.");
847 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000848
Tony Makd390ae92017-12-28 13:23:10 +0000849 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000850 final long identity = Binder.clearCallingIdentity();
851 try {
arangelov9b632d72018-12-07 23:21:22 +0000852 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000853 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000854 setQuietModeEnabled(
855 userHandle, true /* enableQuietMode */, target, callingPackage);
856 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000857 } else {
858 boolean needToShowConfirmCredential =
859 mLockPatternUtils.isSecure(userHandle)
860 && !StorageManager.isUserKeyUnlocked(userHandle);
861 if (needToShowConfirmCredential) {
862 showConfirmCredentialToDisableQuietMode(userHandle, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000863 } else {
arangelov9b632d72018-12-07 23:21:22 +0000864 setQuietModeEnabled(
865 userHandle, false /* enableQuietMode */, target, callingPackage);
866 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000867 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000868 }
arangelov9b632d72018-12-07 23:21:22 +0000869 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000870 } finally {
871 Binder.restoreCallingIdentity(identity);
872 }
873 }
874
Tony Make3d1f652017-12-12 11:00:37 +0000875 /**
Tony Makd390ae92017-12-28 13:23:10 +0000876 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000877 * <ul>
878 * <li>Has system UID or root UID</li>
879 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
880 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
881 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000882 * <p>
883 * If caller wants to start an intent after disabling the quiet mode, it must has
884 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000885 */
Tony Makd390ae92017-12-28 13:23:10 +0000886 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
887 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000888 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000889 return;
Tony Make3d1f652017-12-12 11:00:37 +0000890 }
Tony Makd390ae92017-12-28 13:23:10 +0000891 if (startIntent) {
892 throw new SecurityException("MANAGE_USERS permission is required to start intent "
893 + "after disabling quiet mode.");
894 }
jovanakf24ad492018-05-18 12:15:59 -0700895 final boolean hasModifyQuietModePermission = hasPermissionGranted(
896 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000897 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000898 return;
Tony Make3d1f652017-12-12 11:00:37 +0000899 }
900
Tony Makd390ae92017-12-28 13:23:10 +0000901 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000902 final ShortcutServiceInternal shortcutInternal =
903 LocalServices.getService(ShortcutServiceInternal.class);
904 if (shortcutInternal != null) {
905 boolean isForegroundLauncher =
906 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
907 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000908 return;
Tony Make3d1f652017-12-12 11:00:37 +0000909 }
910 }
Tony Makd390ae92017-12-28 13:23:10 +0000911 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
912 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000913 }
914
arangelov9b632d72018-12-07 23:21:22 +0000915 private void setQuietModeEnabled(int userHandle, boolean enableQuietMode,
916 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000917 final UserInfo profile, parent;
918 final UserData profileUserData;
919 synchronized (mUsersLock) {
920 profile = getUserInfoLU(userHandle);
921 parent = getProfileParentLU(userHandle);
922
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000923 if (profile == null || !profile.isManagedProfile()) {
924 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
925 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000926 if (profile.isQuietModeEnabled() == enableQuietMode) {
927 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
928 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000929 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000930 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
931 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000932 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000933 synchronized (mPackagesLock) {
934 writeUserLP(profileUserData);
935 }
936 try {
937 if (enableQuietMode) {
938 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
939 LocalServices.getService(ActivityManagerInternal.class)
940 .killForegroundAppsForUser(userHandle);
941 } else {
942 IProgressListener callback = target != null
943 ? new DisableQuietModeUserUnlockedCallback(target)
944 : null;
945 ActivityManager.getService().startUserInBackgroundWithListener(
946 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000947 }
arangelov9b632d72018-12-07 23:21:22 +0000948 logQuietModeEnabled(userHandle, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +0000949 } catch (RemoteException e) {
950 // Should not happen, same process.
951 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000952 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000953 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
954 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000955 }
956
arangelov9b632d72018-12-07 23:21:22 +0000957 private void logQuietModeEnabled(int userHandle, boolean enableQuietMode,
958 @Nullable String callingPackage) {
959 UserData userData;
960 synchronized (mUsersLock) {
961 userData = getUserDataLU(userHandle);
962 }
963 if (userData == null) {
964 return;
965 }
966 final long now = System.currentTimeMillis();
967 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
968 ? now - userData.getLastRequestQuietModeEnabledMillis()
969 : now - userData.info.creationTime);
970 DevicePolicyEventLogger
971 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
972 .setStrings(callingPackage)
973 .setBoolean(enableQuietMode)
974 .setTimePeriod(period)
975 .write();
976 userData.setLastRequestQuietModeEnabledMillis(now);
977 }
978
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000979 @Override
980 public boolean isQuietModeEnabled(int userHandle) {
981 synchronized (mPackagesLock) {
982 UserInfo info;
983 synchronized (mUsersLock) {
984 info = getUserInfoLU(userHandle);
985 }
986 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000987 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000988 }
989 return info.isQuietModeEnabled();
990 }
991 }
992
Tony Makb7e6fd42017-12-05 19:40:28 +0000993 /**
994 * Show confirm credential screen to unlock user in order to turn off quiet mode.
995 */
996 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000997 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000998 // otherwise, we show a profile challenge to trigger decryption of the user
999 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
1000 Context.KEYGUARD_SERVICE);
1001 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
1002 // lock, confirm screenlock page will know and show personal challenge, and unlock
1003 // work profile when personal challenge is correct
1004 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
1005 userHandle);
1006 if (unlockIntent == null) {
1007 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001008 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001009 final Intent callBackIntent = new Intent(
1010 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1011 if (target != null) {
1012 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001013 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001014 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
1015 callBackIntent.setPackage(mContext.getPackageName());
1016 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1017 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1018 mContext,
1019 0,
1020 callBackIntent,
1021 PendingIntent.FLAG_CANCEL_CURRENT |
1022 PendingIntent.FLAG_ONE_SHOT |
1023 PendingIntent.FLAG_IMMUTABLE);
1024 // After unlocking the challenge, it will disable quiet mode and run the original
1025 // intentSender
1026 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1027 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1028 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001029 }
1030
1031 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001032 public void setUserEnabled(int userId) {
1033 checkManageUsersPermission("enable user");
1034 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001035 UserInfo info;
1036 synchronized (mUsersLock) {
1037 info = getUserInfoLU(userId);
1038 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001039 if (info != null && !info.isEnabled()) {
1040 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001041 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001042 }
1043 }
1044 }
1045
jovanakf24ad492018-05-18 12:15:59 -07001046 @Override
1047 public void setUserAdmin(int userId) {
1048 checkManageUserAndAcrossUsersFullPermission("set user admin");
1049
1050 synchronized (mPackagesLock) {
1051 UserInfo info;
1052 synchronized (mUsersLock) {
1053 info = getUserInfoLU(userId);
1054 }
1055 if (info == null || info.isAdmin()) {
1056 // Exit if no user found with that id, or the user is already an Admin.
1057 return;
1058 }
1059
1060 info.flags ^= UserInfo.FLAG_ADMIN;
1061 writeUserLP(getUserDataLU(info.id));
1062 }
1063
1064 // Remove non-admin restrictions.
1065 // Keep synchronized with createUserEvenWhenDisallowed.
1066 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1067 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1068 }
1069
Andrew Scull85a63bc2016-10-24 13:47:47 +01001070 /**
1071 * Evicts a user's CE key by stopping and restarting the user.
1072 *
1073 * The key is evicted automatically by the user controller when the user has stopped.
1074 */
1075 @Override
1076 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1077 checkManageUsersPermission("evict CE key");
1078 final IActivityManager am = ActivityManagerNative.getDefault();
1079 final long identity = Binder.clearCallingIdentity();
1080 try {
1081 am.restartUserInBackground(userId);
1082 } catch (RemoteException re) {
1083 throw re.rethrowAsRuntimeException();
1084 } finally {
1085 Binder.restoreCallingIdentity(identity);
1086 }
1087 }
1088
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001089 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001090 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001091 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001092 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001093 return userWithName(getUserInfoLU(userId));
1094 }
1095 }
1096
1097 /**
1098 * Returns a UserInfo object with the name filled in, for Owner, or the original
1099 * if the name is already set.
1100 */
1101 private UserInfo userWithName(UserInfo orig) {
1102 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1103 UserInfo withName = new UserInfo(orig);
1104 withName.name = getOwnerName();
1105 return withName;
1106 } else {
1107 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001108 }
1109 }
1110
1111 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001112 public int getManagedProfileBadge(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001113 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getManagedProfileBadge");
Kenny Guy02c89902016-11-15 19:36:38 +00001114 synchronized (mUsersLock) {
1115 UserInfo userInfo = getUserInfoLU(userId);
1116 return userInfo != null ? userInfo.profileBadge : 0;
1117 }
1118 }
1119
1120 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001121 public boolean isManagedProfile(int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001122 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001123 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001124 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001125 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001126 }
1127 }
1128
Amith Yamasani71e6c692013-03-24 17:39:28 -07001129 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001130 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001131 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001132 return mLocalService.isUserUnlockingOrUnlocked(userId);
1133 }
1134
1135 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001136 public boolean isUserUnlocked(int userId) {
1137 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001138 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001139 }
1140
1141 @Override
1142 public boolean isUserRunning(int userId) {
1143 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1144 return mLocalService.isUserRunning(userId);
1145 }
1146
Makoto Onuki73dded22017-12-20 13:14:48 +09001147 @Override
Bookatzcde3d922019-03-08 14:30:00 -08001148 public String getUserName() {
1149 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1150 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1151 + "permissions to: get user name");
1152 }
1153 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1154 synchronized (mUsersLock) {
1155 UserInfo userInfo = userWithName(getUserInfoLU(userId));
1156 return userInfo == null ? "" : userInfo.name;
1157 }
1158 }
1159
1160 @Override
Makoto Onuki73dded22017-12-20 13:14:48 +09001161 public long getUserStartRealtime() {
1162 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1163 synchronized (mUsersLock) {
1164 final UserData user = getUserDataLU(userId);
1165 if (user != null) {
1166 return user.startRealtime;
1167 }
1168 return 0;
1169 }
1170 }
1171
1172 @Override
1173 public long getUserUnlockRealtime() {
1174 synchronized (mUsersLock) {
1175 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1176 if (user != null) {
1177 return user.unlockRealtime;
1178 }
1179 return 0;
1180 }
1181 }
1182
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001183 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1184 int callingUserId = UserHandle.getCallingUserId();
1185 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1186 hasManageUsersPermission()) {
1187 return;
1188 }
jovanakf24ad492018-05-18 12:15:59 -07001189 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1190 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001191 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1192 + "to: check " + name);
1193 }
1194 }
1195
1196 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001197 public boolean isDemoUser(int userId) {
1198 int callingUserId = UserHandle.getCallingUserId();
1199 if (callingUserId != userId && !hasManageUsersPermission()) {
1200 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1201 + " is a demo user");
1202 }
1203 synchronized (mUsersLock) {
1204 UserInfo userInfo = getUserInfoLU(userId);
1205 return userInfo != null && userInfo.isDemo();
1206 }
1207 }
1208
1209 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001210 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001211 synchronized (mUsersLock) {
1212 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001213 }
1214 }
1215
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001216 @Override
1217 public boolean canHaveRestrictedProfile(int userId) {
1218 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001219 synchronized (mUsersLock) {
1220 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001221 if (userInfo == null || !userInfo.canHaveProfile()) {
1222 return false;
1223 }
1224 if (!userInfo.isAdmin()) {
1225 return false;
1226 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001227 // restricted profile can be created if there is no DO set and the admin user has no PO;
1228 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001229 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001230 }
1231
Fyodor Kupolovca177562017-11-09 17:43:01 -08001232 @Override
1233 public boolean hasRestrictedProfiles() {
1234 checkManageUsersPermission("hasRestrictedProfiles");
1235 final int callingUserId = UserHandle.getCallingUserId();
1236 synchronized (mUsersLock) {
1237 final int userSize = mUsers.size();
1238 for (int i = 0; i < userSize; i++) {
1239 UserInfo profile = mUsers.valueAt(i).info;
1240 if (callingUserId != profile.id
1241 && profile.restrictedProfileParentId == callingUserId) {
1242 return true;
1243 }
1244 }
1245 return false;
1246 }
1247 }
1248
Amith Yamasani195263742012-08-21 15:40:12 -07001249 /*
1250 * Should be locked on mUsers before calling this.
1251 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001252 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001253 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001254 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001255 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001256 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001257 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1258 return null;
1259 }
Amith Yamasani12747872015-12-07 14:19:49 -08001260 return userData != null ? userData.info : null;
1261 }
1262
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001263 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -08001264 private UserData getUserDataLU(int userId) {
1265 final UserData userData = mUsers.get(userId);
1266 // If it is partial and not in the process of being removed, return as unknown user.
1267 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1268 return null;
1269 }
1270 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001271 }
1272
Fyodor Kupolov82402752015-10-28 14:54:51 -07001273 /**
1274 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1275 * <p>No permissions checking or any addition checks are made</p>
1276 */
1277 private UserInfo getUserInfoNoChecks(int userId) {
1278 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001279 final UserData userData = mUsers.get(userId);
1280 return userData != null ? userData.info : null;
1281 }
1282 }
1283
1284 /**
1285 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1286 * <p>No permissions checking or any addition checks are made</p>
1287 */
1288 private UserData getUserDataNoChecks(int userId) {
1289 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001290 return mUsers.get(userId);
1291 }
1292 }
1293
Amith Yamasani236b2b52015-08-18 14:32:14 -07001294 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001295 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001296 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001297 }
1298
Amith Yamasani258848d2012-08-10 17:06:33 -07001299 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001300 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001301 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001302 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001303 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001304 UserData userData = getUserDataNoChecks(userId);
1305 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001306 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1307 return;
1308 }
Amith Yamasani12747872015-12-07 14:19:49 -08001309 if (name != null && !name.equals(userData.info.name)) {
1310 userData.info.name = name;
1311 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001312 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001313 }
1314 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001315 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001316 long ident = Binder.clearCallingIdentity();
1317 try {
1318 sendUserInfoChangedBroadcast(userId);
1319 } finally {
1320 Binder.restoreCallingIdentity(ident);
1321 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001322 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001323 }
1324
Amith Yamasani258848d2012-08-10 17:06:33 -07001325 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001326 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001327 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001328 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1329 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1330 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001331 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001332 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001333 }
1334
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001335
1336
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001337 private void sendUserInfoChangedBroadcast(int userId) {
1338 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1339 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1340 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001341 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001342 }
1343
Amith Yamasani258848d2012-08-10 17:06:33 -07001344 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001345 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Bookatzcde3d922019-03-08 14:30:00 -08001346 if (!hasManageUsersOrPermission(android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED)) {
1347 throw new SecurityException("You need MANAGE_USERS or GET_ACCOUNTS_PRIVILEGED "
1348 + "permissions to: get user icon");
1349 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001350 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001351 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001352 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1353 if (targetUserInfo == null || targetUserInfo.partial) {
1354 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001355 return null;
1356 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001357
1358 final int callingUserId = UserHandle.getCallingUserId();
1359 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1360 final int targetGroupId = targetUserInfo.profileGroupId;
1361 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1362 && callingGroupId == targetGroupId);
1363 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001364 checkManageUsersPermission("get the icon of a user who is not related");
1365 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001366
1367 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001368 return null;
1369 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001370 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001371 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001372
1373 try {
1374 return ParcelFileDescriptor.open(
1375 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1376 } catch (FileNotFoundException e) {
1377 Log.e(LOG_TAG, "Couldn't find icon file", e);
1378 }
1379 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001380 }
1381
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001382 public void makeInitialized(int userId) {
1383 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001384 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001385 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001386 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001387 userData = mUsers.get(userId);
1388 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001389 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001390 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001391 }
Amith Yamasani12747872015-12-07 14:19:49 -08001392 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1393 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001394 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001395 }
1396 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001397 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001398 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001399 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001400 }
1401
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001402 /**
1403 * If default guest restrictions haven't been initialized yet, add the basic
1404 * restrictions.
1405 */
1406 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001407 synchronized (mGuestRestrictions) {
1408 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001409 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001410 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001411 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1412 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1413 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001414 }
1415 }
1416
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001417 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301418 public Bundle getDefaultGuestRestrictions() {
1419 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001420 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301421 return new Bundle(mGuestRestrictions);
1422 }
1423 }
1424
1425 @Override
1426 public void setDefaultGuestRestrictions(Bundle restrictions) {
1427 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001428 synchronized (mGuestRestrictions) {
1429 mGuestRestrictions.clear();
1430 mGuestRestrictions.putAll(restrictions);
1431 }
1432 synchronized (mPackagesLock) {
1433 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301434 }
1435 }
1436
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001437 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001438 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001440 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1441 boolean isDeviceOwner, int cameraRestrictionScope) {
1442 final Bundle global = new Bundle();
1443 final Bundle local = new Bundle();
1444
1445 // Sort restrictions into local and global ensuring they don't overlap.
1446 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1447 cameraRestrictionScope, global, local);
1448
1449 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001450 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001451 // Update global and local restrictions if they were changed.
1452 globalChanged = updateRestrictionsIfNeededLR(
1453 userId, global, mDevicePolicyGlobalUserRestrictions);
1454 localChanged = updateRestrictionsIfNeededLR(
1455 userId, local, mDevicePolicyLocalUserRestrictions);
1456
1457 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001458 // Remember the global restriction owner userId to be able to make a distinction
1459 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001460 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001461 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001462 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001463 // When profile owner sets restrictions it passes null global bundle and we
1464 // reset global restriction owner userId.
1465 // This means this user used to have DO, but now the DO is gone and the user
1466 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001467 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001468 }
1469 }
1470 }
1471 if (DBG) {
1472 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1473 + " global=" + global + (globalChanged ? " (changed)" : "")
1474 + " local=" + local + (localChanged ? " (changed)" : "")
1475 );
1476 }
1477 // Don't call them within the mRestrictionsLock.
1478 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001479 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001480 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001481 }
1482 }
1483
1484 synchronized (mRestrictionsLock) {
1485 if (globalChanged) {
1486 applyUserRestrictionsForAllUsersLR();
1487 } else if (localChanged) {
1488 applyUserRestrictionsLR(userId);
1489 }
1490 }
1491 }
1492
Pavel Grafov6a40f092016-10-25 15:46:51 +01001493 /**
1494 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1495 * empty, record is removed from the array.
1496 * @return whether restrictions bundle is different from the old one.
1497 */
1498 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1499 SparseArray<Bundle> restrictionsArray) {
1500 final boolean changed =
1501 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1502 if (changed) {
1503 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1504 restrictionsArray.put(userId, restrictions);
1505 } else {
1506 restrictionsArray.delete(userId);
1507 }
1508 }
1509 return changed;
1510 }
1511
Makoto Onuki068c54a2015-10-13 14:34:03 -07001512 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001513 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001514 final Bundle baseRestrictions =
1515 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001516 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001517 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001518
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001519 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1520 // Common case first.
1521 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001522 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001523 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1524 UserRestrictionsUtils.merge(effective, global);
1525 UserRestrictionsUtils.merge(effective, local);
1526
Makoto Onuki068c54a2015-10-13 14:34:03 -07001527 return effective;
1528 }
1529
1530 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001531 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001532 if (DBG) {
1533 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1534 }
1535 mCachedEffectiveUserRestrictions.remove(userId);
1536 }
1537
1538 private Bundle getEffectiveUserRestrictions(int userId) {
1539 synchronized (mRestrictionsLock) {
1540 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1541 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001542 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001543 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1544 }
1545 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001546 }
1547 }
1548
Makoto Onuki068c54a2015-10-13 14:34:03 -07001549 /** @return a specific user restriction that's in effect currently. */
1550 @Override
1551 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001552 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1553 return false;
1554 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001555 Bundle restrictions = getEffectiveUserRestrictions(userId);
1556 return restrictions != null && restrictions.getBoolean(restrictionKey);
1557 }
1558
Makoto Onukiacc50462018-02-14 14:13:49 -08001559 /** @return if any user has the given restriction. */
1560 @Override
1561 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1562 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1563 return false;
1564 }
1565 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1566 for (int i = 0; i < users.size(); i++) {
1567 final int userId = users.get(i).id;
1568 Bundle restrictions = getEffectiveUserRestrictions(userId);
1569 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1570 return true;
1571 }
1572 }
1573 return false;
1574 }
1575
Makoto Onuki068c54a2015-10-13 14:34:03 -07001576 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001577 * @hide
1578 *
1579 * Returns who set a user restriction on a user.
1580 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1581 * @param restrictionKey the string key representing the restriction
1582 * @param userId the id of the user for whom to retrieve the restrictions.
1583 * @return The source of user restriction. Any combination of
1584 * {@link UserManager#RESTRICTION_NOT_SET},
1585 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1586 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1587 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1588 */
1589 @Override
1590 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001591 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1592 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001593 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001594 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1595 result |= enforcingUsers.get(i).getUserRestrictionSource();
1596 }
1597 return result;
1598 }
1599
1600 @Override
1601 public List<EnforcingUser> getUserRestrictionSources(
1602 String restrictionKey, @UserIdInt int userId) {
1603 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001604
1605 // Shortcut for the most common case
1606 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001607 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001608 }
1609
Pavel Grafov6a40f092016-10-25 15:46:51 +01001610 final List<EnforcingUser> result = new ArrayList<>();
1611
1612 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001613 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001614 result.add(new EnforcingUser(
1615 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001616 }
1617
Pavel Grafov6a40f092016-10-25 15:46:51 +01001618 synchronized (mRestrictionsLock) {
1619 // Check if it is set by profile owner.
1620 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1621 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1622 result.add(getEnforcingUserLocked(userId));
1623 }
1624
1625 // Iterate over all users who enforce global restrictions.
1626 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1627 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1628 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1629 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1630 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001631 }
1632 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001633 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001634 return result;
1635 }
1636
Andreas Gampea36dc622018-02-05 17:19:22 -08001637 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001638 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1639 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1640 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1641 return new EnforcingUser(userId, source);
1642 }
1643
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001644 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001645 * @return UserRestrictions that are in effect currently. This always returns a new
1646 * {@link Bundle}.
1647 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001648 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001649 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001651 }
1652
1653 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001654 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1655 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001656 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1657 return false;
1658 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001659 synchronized (mRestrictionsLock) {
1660 Bundle bundle = mBaseUserRestrictions.get(userId);
1661 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1662 }
1663 }
1664
1665 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001666 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001667 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001668 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1669 return;
1670 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001671 synchronized (mRestrictionsLock) {
1672 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1673 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1675 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001676 newRestrictions.putBoolean(key, value);
1677
Fyodor Kupolov82402752015-10-28 14:54:51 -07001678 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001679 }
1680 }
1681
Makoto Onuki068c54a2015-10-13 14:34:03 -07001682 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 * Optionally updating user restrictions, calculate the effective user restrictions and also
1684 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001685 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001686 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001688 * @param userId target user ID.
1689 */
1690 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001691 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001692 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1694 mAppliedUserRestrictions.get(userId));
1695
1696 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001697 if (newBaseRestrictions != null) {
1698 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001699 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1700
Pavel Grafov6a40f092016-10-25 15:46:51 +01001701 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001702 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001703 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001704
Pavel Grafov6a40f092016-10-25 15:46:51 +01001705 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001706 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001708 }
1709
Fyodor Kupolov82402752015-10-28 14:54:51 -07001710 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001711
Makoto Onuki759a7632015-10-28 16:43:10 -07001712 mCachedEffectiveUserRestrictions.put(userId, effective);
1713
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001714 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001715 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716 debug("Applying user restrictions: userId=" + userId
1717 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001718 }
1719
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001721 mHandler.post(new Runnable() {
1722 @Override
1723 public void run() {
1724 try {
1725 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1726 } catch (RemoteException e) {
1727 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1728 }
1729 }
1730 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001731 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001732
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001733 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001734
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001735 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001736 }
1737
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001738 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001739 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001740 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1741 // actually, but we still need some kind of synchronization otherwise we might end up
1742 // calling listeners out-of-order, thus "LR".
1743
1744 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1745 return;
1746 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001747
1748 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1749 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1750
1751 mHandler.post(new Runnable() {
1752 @Override
1753 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001754 UserRestrictionsUtils.applyUserRestrictions(
1755 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001756
Makoto Onukid45a4a22015-11-02 17:17:38 -08001757 final UserRestrictionsListener[] listeners;
1758 synchronized (mUserRestrictionsListeners) {
1759 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1760 mUserRestrictionsListeners.toArray(listeners);
1761 }
1762 for (int i = 0; i < listeners.length; i++) {
1763 listeners[i].onUserRestrictionsChanged(userId,
1764 newRestrictionsFinal, prevRestrictionsFinal);
1765 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001766
1767 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1768 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1769 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001770 }
1771 });
1772 }
1773
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001774 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001775 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001776 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001777 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001778 }
1779
1780 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001781 // Package private for the inner class.
1782 void applyUserRestrictionsForAllUsersLR() {
1783 if (DBG) {
1784 debug("applyUserRestrictionsForAllUsersLR");
1785 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001786 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001787 mCachedEffectiveUserRestrictions.clear();
1788
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001789 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001790 // it on a handler.
1791 final Runnable r = new Runnable() {
1792 @Override
1793 public void run() {
1794 // Then get the list of running users.
1795 final int[] runningUsers;
1796 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001797 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001798 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001799 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001800 return;
1801 }
1802 // Then re-calculate the effective restrictions and apply, only for running users.
1803 // It's okay if a new user has started after the getRunningUserIds() call,
1804 // because we'll do the same thing (re-calculate the restrictions and apply)
1805 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001806 synchronized (mRestrictionsLock) {
1807 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001808 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001809 }
1810 }
1811 }
1812 };
1813 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001814 }
1815
Amith Yamasani258848d2012-08-10 17:06:33 -07001816 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001817 * Check if we've hit the limit of how many users can be created.
1818 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001819 private boolean isUserLimitReached() {
1820 int count;
1821 synchronized (mUsersLock) {
1822 count = getAliveUsersExcludingGuestsCountLU();
1823 }
1824 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001825 }
1826
1827 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001828 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001829 checkManageUsersPermission("check if more managed profiles can be added.");
1830 if (ActivityManager.isLowRamDeviceStatic()) {
1831 return false;
1832 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001833 if (!mContext.getPackageManager().hasSystemFeature(
1834 PackageManager.FEATURE_MANAGED_USERS)) {
1835 return false;
1836 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001837 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001838 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001839 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001840 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001841 return false;
1842 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001843 synchronized(mUsersLock) {
1844 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001845 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001846 return false;
1847 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001848 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1849 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001850 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001851 return usersCountAfterRemoving == 1
1852 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001853 }
1854 }
1855
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001856 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001857 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001858 int aliveUserCount = 0;
1859 final int totalUserCount = mUsers.size();
1860 // Skip over users being removed
1861 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001862 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001863 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001864 aliveUserCount++;
1865 }
1866 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001867 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001868 }
1869
1870 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001871 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001872 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1873 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1874 * permissions can make certain calls to the UserManager.
1875 *
1876 * @param message used as message if SecurityException is thrown
1877 * @throws SecurityException if the caller does not have enough privilege.
1878 */
1879 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1880 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001881
1882 if (uid == Process.SYSTEM_UID || uid == 0) {
1883 // System UID or root's UID are granted privilege.
1884 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001885 }
jovanakf24ad492018-05-18 12:15:59 -07001886
1887 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1888 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1889 // Apps with both permissions are granted privilege.
1890 return;
1891 }
1892
1893 throw new SecurityException(
1894 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1895 }
1896
1897 private static boolean hasPermissionGranted(String permission, int uid) {
1898 return ActivityManager.checkComponentPermission(
1899 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1900 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001901 }
1902
1903 /**
1904 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001905 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001906 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001907 *
1908 * @param message used as message if SecurityException is thrown
1909 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001910 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001911 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001912 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001913 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001914 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1915 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001916 }
1917
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001918 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001919 * Enforces that only the system UID or root's UID or apps that have the
1920 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1921 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1922 * can make certain calls to the UserManager.
1923 *
1924 * @param message used as message if SecurityException is thrown
1925 * @throws SecurityException if the caller is not system or root
1926 * @see #hasManageOrCreateUsersPermission()
1927 */
1928 private static final void checkManageOrCreateUsersPermission(String message) {
1929 if (!hasManageOrCreateUsersPermission()) {
1930 throw new SecurityException(
1931 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1932 }
1933 }
1934
1935 /**
1936 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1937 * to create user/profiles other than what is allowed for
1938 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1939 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1940 */
1941 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1942 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1943 if (!hasManageOrCreateUsersPermission()) {
1944 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1945 + "permission to create an user with flags: " + creationFlags);
1946 }
1947 } else if (!hasManageUsersPermission()) {
1948 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1949 + " with flags: " + creationFlags);
1950 }
1951 }
1952
1953 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001954 * @return whether the calling UID is system UID or root's UID or the calling app has the
1955 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1956 */
1957 private static final boolean hasManageUsersPermission() {
1958 final int callingUid = Binder.getCallingUid();
1959 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1960 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001961 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001962 }
1963
1964 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001965 * @return whether the calling UID is system UID or root's UID or the calling app has the
Bookatzcde3d922019-03-08 14:30:00 -08001966 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or the provided permission.
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001967 */
Bookatzcde3d922019-03-08 14:30:00 -08001968 private static final boolean hasManageUsersOrPermission(String alternativePermission) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001969 final int callingUid = Binder.getCallingUid();
1970 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1971 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001972 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
Bookatzcde3d922019-03-08 14:30:00 -08001973 || hasPermissionGranted(alternativePermission, callingUid);
1974 }
1975
1976 /**
1977 * @return whether the calling UID is system UID or root's UID or the calling app has the
1978 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1979 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1980 */
1981 private static final boolean hasManageOrCreateUsersPermission() {
1982 return hasManageUsersOrPermission(android.Manifest.permission.CREATE_USERS);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001983 }
1984
1985 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001986 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1987 * UserManager.
1988 *
1989 * @param message used as message if SecurityException is thrown
1990 * @throws SecurityException if the caller is not system or root
1991 */
1992 private static void checkSystemOrRoot(String message) {
1993 final int uid = Binder.getCallingUid();
1994 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1995 throw new SecurityException("Only system may: " + message);
1996 }
1997 }
1998
Fyodor Kupolov82402752015-10-28 14:54:51 -07001999 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002000 try {
2001 File dir = new File(mUsersDir, Integer.toString(info.id));
2002 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01002003 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002004 if (!dir.exists()) {
2005 dir.mkdir();
2006 FileUtils.setPermissions(
2007 dir.getPath(),
2008 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2009 -1, -1);
2010 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002011 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01002012 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01002013 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07002014 info.iconPath = file.getAbsolutePath();
2015 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07002016 try {
2017 os.close();
2018 } catch (IOException ioe) {
2019 // What the ... !
2020 }
Adrian Roos1bdff912015-02-17 15:51:35 +01002021 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002022 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002023 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002024 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002025 }
2026
Amith Yamasani0b285492011-04-14 17:35:23 -07002027 /**
2028 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2029 * cache it elsewhere.
2030 * @return the array of user ids.
2031 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002032 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002033 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002034 return mUserIds;
2035 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002036 }
2037
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002038 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002039 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002040 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002041 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002042 return;
2043 }
2044 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002045 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002046 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002047 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002048 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002049 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002050 int type;
2051 while ((type = parser.next()) != XmlPullParser.START_TAG
2052 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002053 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002054 }
2055
2056 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002057 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002058 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002059 return;
2060 }
2061
Amith Yamasani2a003292012-08-14 18:25:45 -07002062 mNextSerialNumber = -1;
2063 if (parser.getName().equals(TAG_USERS)) {
2064 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2065 if (lastSerialNumber != null) {
2066 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2067 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002068 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2069 if (versionNumber != null) {
2070 mUserVersion = Integer.parseInt(versionNumber);
2071 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002072 }
2073
Pavel Grafov6a40f092016-10-25 15:46:51 +01002074 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2075 // currently), take care of it in case of upgrade.
2076 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002077
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002078 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302079 if (type == XmlPullParser.START_TAG) {
2080 final String name = parser.getName();
2081 if (name.equals(TAG_USER)) {
2082 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002083
Amith Yamasani12747872015-12-07 14:19:49 -08002084 UserData userData = readUserLP(Integer.parseInt(id));
2085
2086 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002087 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002088 mUsers.put(userData.info.id, userData);
2089 if (mNextSerialNumber < 0
2090 || mNextSerialNumber <= userData.info.id) {
2091 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002092 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302093 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002094 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302095 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002096 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2097 && type != XmlPullParser.END_TAG) {
2098 if (type == XmlPullParser.START_TAG) {
2099 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002100 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002101 UserRestrictionsUtils
2102 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002103 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002104 }
2105 break;
2106 }
2107 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002108 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2109 // Legacy name, should only be encountered when upgrading from pre-O.
2110 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002111 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2112 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002113 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002114 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002115 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2116 // Should only happen when upgrading from pre-O (version < 7).
2117 oldDevicePolicyGlobalUserRestrictions =
2118 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002119 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002120 }
2121 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002122
Fyodor Kupolov82402752015-10-28 14:54:51 -07002123 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002124 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002125 } catch (IOException | XmlPullParserException e) {
2126 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002127 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002128 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002129 }
2130 }
2131
Amith Yamasani6f34b412012-10-22 18:19:27 -07002132 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002133 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002134 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002135 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002136 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002137 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002138 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002139 int userVersion = mUserVersion;
2140 if (userVersion < 1) {
2141 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002142 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2143 if ("Primary".equals(userData.info.name)) {
2144 userData.info.name =
2145 mContext.getResources().getString(com.android.internal.R.string.owner_name);
2146 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002147 }
2148 userVersion = 1;
2149 }
2150
Amith Yamasanibc9625052012-11-15 14:39:18 -08002151 if (userVersion < 2) {
2152 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002153 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2154 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2155 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2156 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002157 }
2158 userVersion = 2;
2159 }
2160
Amith Yamasani350962c2013-08-06 11:18:53 -07002161
Amith Yamasani5e486f52013-08-07 11:06:44 -07002162 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002163 userVersion = 4;
2164 }
2165
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002166 if (userVersion < 5) {
2167 initDefaultGuestRestrictions();
2168 userVersion = 5;
2169 }
2170
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002171 if (userVersion < 6) {
2172 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002173 synchronized (mUsersLock) {
2174 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002175 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002176 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002177 if (!splitSystemUser && userData.info.isRestricted()
2178 && (userData.info.restrictedProfileParentId
2179 == UserInfo.NO_PROFILE_GROUP_ID)) {
2180 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2181 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002182 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002183 }
2184 }
2185 userVersion = 6;
2186 }
2187
Pavel Grafov6a40f092016-10-25 15:46:51 +01002188 if (userVersion < 7) {
2189 // Previously only one user could enforce global restrictions, now it is per-user.
2190 synchronized (mRestrictionsLock) {
2191 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2192 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2193 mDevicePolicyGlobalUserRestrictions.put(
2194 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2195 }
2196 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2197 // it from local to global bundle for all users who set it.
2198 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2199 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2200 );
2201 }
2202 userVersion = 7;
2203 }
2204
Amith Yamasani6f34b412012-10-22 18:19:27 -07002205 if (userVersion < USER_VERSION) {
2206 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2207 + USER_VERSION);
2208 } else {
2209 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002210
2211 if (originalVersion < mUserVersion) {
2212 writeUserListLP();
2213 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002214 }
2215 }
2216
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002217 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002218 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002219 int flags = UserInfo.FLAG_INITIALIZED;
2220 // In split system user mode, the admin and primary flags are assigned to the first human
2221 // user.
2222 if (!UserManager.isSplitSystemUser()) {
2223 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2224 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002225 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002226 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002227 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002228 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002229 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002230
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002231 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002232 try {
2233 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2234 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2235 for (String userRestriction : defaultFirstUserRestrictions) {
2236 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2237 restrictions.putBoolean(userRestriction, true);
2238 }
2239 }
2240 } catch (Resources.NotFoundException e) {
2241 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2242 }
2243
Pavel Grafov6a40f092016-10-25 15:46:51 +01002244 if (!restrictions.isEmpty()) {
2245 synchronized (mRestrictionsLock) {
2246 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2247 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002248 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002249
Fyodor Kupolov82402752015-10-28 14:54:51 -07002250 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002251 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002252
Amith Yamasani12747872015-12-07 14:19:49 -08002253 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002254 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002255 }
2256
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002257 private String getOwnerName() {
2258 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2259 }
2260
Amith Yamasani12747872015-12-07 14:19:49 -08002261 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002262 if (DBG) {
2263 debug("scheduleWriteUser");
2264 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002265 // No need to wrap it within a lock -- worst case, we'll just post the same message
2266 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002267 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2268 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002269 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2270 }
2271 }
2272
Amith Yamasani12747872015-12-07 14:19:49 -08002273 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002274 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002275 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002276 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002277 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002278 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002279 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002280 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002281 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002282 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002283 userFile.finishWrite(fos);
2284 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002285 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002286 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002287 }
2288 }
2289
2290 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002291 * Writes the user file in this format:
2292 *
2293 * <user flags="20039023" id="0">
2294 * <name>Primary</name>
2295 * </user>
2296 */
2297 @VisibleForTesting
2298 void writeUserLP(UserData userData, OutputStream os)
2299 throws IOException, XmlPullParserException {
2300 // XmlSerializer serializer = XmlUtils.serializerInstance();
2301 final XmlSerializer serializer = new FastXmlSerializer();
2302 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2303 serializer.startDocument(null, true);
2304 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2305
2306 final UserInfo userInfo = userData.info;
2307 serializer.startTag(null, TAG_USER);
2308 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2309 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2310 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2311 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2312 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2313 Long.toString(userInfo.lastLoggedInTime));
2314 if (userInfo.lastLoggedInFingerprint != null) {
2315 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2316 userInfo.lastLoggedInFingerprint);
2317 }
2318 if (userInfo.iconPath != null) {
2319 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2320 }
2321 if (userInfo.partial) {
2322 serializer.attribute(null, ATTR_PARTIAL, "true");
2323 }
2324 if (userInfo.guestToRemove) {
2325 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2326 }
2327 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2328 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2329 Integer.toString(userInfo.profileGroupId));
2330 }
2331 serializer.attribute(null, ATTR_PROFILE_BADGE,
2332 Integer.toString(userInfo.profileBadge));
2333 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2334 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2335 Integer.toString(userInfo.restrictedProfileParentId));
2336 }
2337 // Write seed data
2338 if (userData.persistSeedData) {
2339 if (userData.seedAccountName != null) {
2340 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2341 }
2342 if (userData.seedAccountType != null) {
2343 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2344 }
2345 }
2346 if (userInfo.name != null) {
2347 serializer.startTag(null, TAG_NAME);
2348 serializer.text(userInfo.name);
2349 serializer.endTag(null, TAG_NAME);
2350 }
2351 synchronized (mRestrictionsLock) {
2352 UserRestrictionsUtils.writeRestrictions(serializer,
2353 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2354 UserRestrictionsUtils.writeRestrictions(serializer,
2355 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2356 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002357 UserRestrictionsUtils.writeRestrictions(serializer,
2358 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2359 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002360 }
2361
2362 if (userData.account != null) {
2363 serializer.startTag(null, TAG_ACCOUNT);
2364 serializer.text(userData.account);
2365 serializer.endTag(null, TAG_ACCOUNT);
2366 }
2367
2368 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2369 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2370 userData.seedAccountOptions.saveToXml(serializer);
2371 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2372 }
2373
arangelov9b632d72018-12-07 23:21:22 +00002374 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2375 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2376 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2377 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2378 }
2379
Kenny Guy02c89902016-11-15 19:36:38 +00002380 serializer.endTag(null, TAG_USER);
2381
2382 serializer.endDocument();
2383 }
2384
2385 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002386 * Writes the user list file in this format:
2387 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002388 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002389 * <user id="0"></user>
2390 * <user id="2"></user>
2391 * </users>
2392 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002393 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002394 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002395 if (DBG) {
2396 debug("writeUserList");
2397 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002398 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002399 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002400 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002401 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002402 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2403
2404 // XmlSerializer serializer = XmlUtils.serializerInstance();
2405 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002406 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002407 serializer.startDocument(null, true);
2408 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2409
2410 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002411 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002412 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002413
Adam Lesinskieddeb492014-09-08 17:50:03 -07002414 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002415 synchronized (mGuestRestrictions) {
2416 UserRestrictionsUtils
2417 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2418 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302419 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002420 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2421 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2422 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002423 int[] userIdsToWrite;
2424 synchronized (mUsersLock) {
2425 userIdsToWrite = new int[mUsers.size()];
2426 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002427 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002428 userIdsToWrite[i] = user.id;
2429 }
2430 }
2431 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002432 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002433 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002434 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002435 }
2436
2437 serializer.endTag(null, TAG_USERS);
2438
2439 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002440 userListFile.finishWrite(fos);
2441 } catch (Exception e) {
2442 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002443 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002444 }
2445 }
2446
Amith Yamasani12747872015-12-07 14:19:49 -08002447 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002448 FileInputStream fis = null;
2449 try {
2450 AtomicFile userFile =
2451 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2452 fis = userFile.openRead();
2453 return readUserLP(id, fis);
2454 } catch (IOException ioe) {
2455 Slog.e(LOG_TAG, "Error reading user list");
2456 } catch (XmlPullParserException pe) {
2457 Slog.e(LOG_TAG, "Error reading user list");
2458 } finally {
2459 IoUtils.closeQuietly(fis);
2460 }
2461 return null;
2462 }
2463
2464 @VisibleForTesting
2465 UserData readUserLP(int id, InputStream is) throws IOException,
2466 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002467 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002468 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002469 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002470 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002471 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002472 long creationTime = 0L;
2473 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002474 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002475 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002476 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002477 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002478 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002479 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002480 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002481 boolean persistSeedData = false;
2482 String seedAccountName = null;
2483 String seedAccountType = null;
2484 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002485 Bundle baseRestrictions = null;
2486 Bundle localRestrictions = null;
2487 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002488
Kenny Guy02c89902016-11-15 19:36:38 +00002489 XmlPullParser parser = Xml.newPullParser();
2490 parser.setInput(is, StandardCharsets.UTF_8.name());
2491 int type;
2492 while ((type = parser.next()) != XmlPullParser.START_TAG
2493 && type != XmlPullParser.END_DOCUMENT) {
2494 // Skip
2495 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002496
Kenny Guy02c89902016-11-15 19:36:38 +00002497 if (type != XmlPullParser.START_TAG) {
2498 Slog.e(LOG_TAG, "Unable to read user " + id);
2499 return null;
2500 }
2501
2502 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2503 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2504 if (storedId != id) {
2505 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002506 return null;
2507 }
Kenny Guy02c89902016-11-15 19:36:38 +00002508 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2509 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2510 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2511 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2512 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2513 lastLoggedInFingerprint = parser.getAttributeValue(null,
2514 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2515 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2516 UserInfo.NO_PROFILE_GROUP_ID);
2517 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2518 restrictedProfileParentId = readIntAttribute(parser,
2519 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2520 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2521 if ("true".equals(valueString)) {
2522 partial = true;
2523 }
2524 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2525 if ("true".equals(valueString)) {
2526 guestToRemove = true;
2527 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002528
Kenny Guy02c89902016-11-15 19:36:38 +00002529 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2530 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2531 if (seedAccountName != null || seedAccountType != null) {
2532 persistSeedData = true;
2533 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002534
Kenny Guy02c89902016-11-15 19:36:38 +00002535 int outerDepth = parser.getDepth();
2536 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2537 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2538 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2539 continue;
2540 }
2541 String tag = parser.getName();
2542 if (TAG_NAME.equals(tag)) {
2543 type = parser.next();
2544 if (type == XmlPullParser.TEXT) {
2545 name = parser.getText();
2546 }
2547 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002548 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002549 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002550 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2551 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2552 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002553 } else if (TAG_ACCOUNT.equals(tag)) {
2554 type = parser.next();
2555 if (type == XmlPullParser.TEXT) {
2556 account = parser.getText();
2557 }
2558 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2559 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002560 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002561 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2562 type = parser.next();
2563 if (type == XmlPullParser.TEXT) {
2564 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2565 }
Amith Yamasani12747872015-12-07 14:19:49 -08002566 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002567 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002568 }
Kenny Guy02c89902016-11-15 19:36:38 +00002569
2570 // Create the UserInfo object that gets passed around
2571 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2572 userInfo.serialNumber = serialNumber;
2573 userInfo.creationTime = creationTime;
2574 userInfo.lastLoggedInTime = lastLoggedInTime;
2575 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2576 userInfo.partial = partial;
2577 userInfo.guestToRemove = guestToRemove;
2578 userInfo.profileGroupId = profileGroupId;
2579 userInfo.profileBadge = profileBadge;
2580 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2581
2582 // Create the UserData object that's internal to this class
2583 UserData userData = new UserData();
2584 userData.info = userInfo;
2585 userData.account = account;
2586 userData.seedAccountName = seedAccountName;
2587 userData.seedAccountType = seedAccountType;
2588 userData.persistSeedData = persistSeedData;
2589 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002590 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002591
2592 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002593 if (baseRestrictions != null) {
2594 mBaseUserRestrictions.put(id, baseRestrictions);
2595 }
2596 if (localRestrictions != null) {
2597 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2598 }
2599 if (globalRestrictions != null) {
2600 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2601 }
Kenny Guy02c89902016-11-15 19:36:38 +00002602 }
2603 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002604 }
2605
Amith Yamasani920ace02012-09-20 22:15:37 -07002606 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2607 String valueString = parser.getAttributeValue(null, attr);
2608 if (valueString == null) return defaultValue;
2609 try {
2610 return Integer.parseInt(valueString);
2611 } catch (NumberFormatException nfe) {
2612 return defaultValue;
2613 }
2614 }
2615
2616 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2617 String valueString = parser.getAttributeValue(null, attr);
2618 if (valueString == null) return defaultValue;
2619 try {
2620 return Long.parseLong(valueString);
2621 } catch (NumberFormatException nfe) {
2622 return defaultValue;
2623 }
2624 }
2625
Amith Yamasanib82add22013-07-09 11:24:44 -07002626 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002627 * Removes the app restrictions file for a specific package and user id, if it exists.
2628 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002629 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2630 File dir = Environment.getUserSystemDirectory(userId);
2631 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2632 if (resFile.exists()) {
2633 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002634 }
2635 }
2636
Kenny Guya52dc3e2014-02-11 15:33:14 +00002637 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002638 public UserInfo createProfileForUser(String name, int flags, int userId,
2639 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002640 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002641 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002642 }
2643
Amith Yamasani258848d2012-08-10 17:06:33 -07002644 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002645 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2646 String[] disallowedPackages) {
2647 checkManageOrCreateUsersPermission(flags);
2648 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2649 }
2650
2651 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002652 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2653 checkManageOrCreateUsersPermission("Only the system can remove users");
2654 return removeUserUnchecked(userHandle);
2655 }
2656
2657 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002658 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002659 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002660 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002661 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002662
Jessica Hummelbe81c802014-04-22 15:49:22 +01002663 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002664 return createUserInternal(name, flags, parentId, null);
2665 }
2666
2667 private UserInfo createUserInternal(String name, int flags, int parentId,
2668 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002669 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2670 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2671 : UserManager.DISALLOW_ADD_USER;
2672 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2673 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002674 return null;
2675 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002676 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2677 }
2678
2679 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2680 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002681 DeviceStorageMonitorInternal dsm = LocalServices
2682 .getService(DeviceStorageMonitorInternal.class);
2683 if (dsm.isMemoryLow()) {
2684 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2685 return null;
2686 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002687 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002688 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002689 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002690 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002691 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002692 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002693 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002694 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002695 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002696 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002697 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002698 if (parentId != UserHandle.USER_NULL) {
2699 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002700 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002701 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002702 if (parent == null) return null;
2703 }
2704 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2705 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2706 return null;
2707 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002708 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2709 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002710 // been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002711 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002712 return null;
2713 }
2714 // If we're adding a guest and there already exists one, bail.
2715 if (isGuest && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002716 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002717 return null;
2718 }
2719 // In legacy mode, restricted profile's parent can only be the owner user
2720 if (isRestricted && !UserManager.isSplitSystemUser()
2721 && (parentId != UserHandle.USER_SYSTEM)) {
2722 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2723 return null;
2724 }
2725 if (isRestricted && UserManager.isSplitSystemUser()) {
2726 if (parent == null) {
2727 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2728 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002729 return null;
2730 }
Amith Yamasani12747872015-12-07 14:19:49 -08002731 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002732 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2733 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002734 return null;
2735 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002736 }
2737 // In split system user mode, we assign the first human user the primary flag.
2738 // And if there is no device owner, we also assign the admin flag to primary user.
2739 if (UserManager.isSplitSystemUser()
2740 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2741 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002742 synchronized (mUsersLock) {
2743 if (!mIsDeviceManaged) {
2744 flags |= UserInfo.FLAG_ADMIN;
2745 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002746 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002747 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002748
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002749 userId = getNextAvailableId();
2750 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002751 boolean ephemeralGuests = Resources.getSystem()
2752 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002753
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002754 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002755 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2756 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2757 || (parent != null && parent.info.isEphemeral())) {
2758 flags |= UserInfo.FLAG_EPHEMERAL;
2759 }
2760
2761 userInfo = new UserInfo(userId, name, null, flags);
2762 userInfo.serialNumber = mNextSerialNumber++;
2763 long now = System.currentTimeMillis();
2764 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2765 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002766 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002767 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2768 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2769 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002770 userData = new UserData();
2771 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002772 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002773 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002774 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002775 writeUserListLP();
2776 if (parent != null) {
2777 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002778 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2779 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002780 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002781 }
Amith Yamasani12747872015-12-07 14:19:49 -08002782 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002783 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002784 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2785 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002786 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002787 }
Amith Yamasani12747872015-12-07 14:19:49 -08002788 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002789 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002790 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002791 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002792 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002793 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002794 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002795 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002796 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002797 userInfo.partial = false;
2798 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002799 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002800 }
2801 updateUserIds();
2802 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002803 if (isGuest) {
2804 synchronized (mGuestRestrictions) {
2805 restrictions.putAll(mGuestRestrictions);
2806 }
2807 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002808 synchronized (mRestrictionsLock) {
2809 mBaseUserRestrictions.append(userId, restrictions);
2810 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002811 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002812 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2813 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2814 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2815 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002816 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2817 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002818 } finally {
2819 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002820 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002821 return userInfo;
2822 }
2823
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002824 @VisibleForTesting
2825 UserData putUserInfo(UserInfo userInfo) {
2826 final UserData userData = new UserData();
2827 userData.info = userInfo;
2828 synchronized (mUsers) {
2829 mUsers.put(userInfo.id, userData);
2830 }
2831 return userData;
2832 }
2833
2834 @VisibleForTesting
2835 void removeUserInfo(int userId) {
2836 synchronized (mUsers) {
2837 mUsers.remove(userId);
2838 }
2839 }
2840
Amith Yamasani0b285492011-04-14 17:35:23 -07002841 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002842 * @hide
2843 */
Amith Yamasani12747872015-12-07 14:19:49 -08002844 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002845 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002846 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002847 final UserInfo user = createProfileForUser(
2848 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002849 if (user == null) {
2850 return null;
2851 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002852 long identity = Binder.clearCallingIdentity();
2853 try {
2854 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2855 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2856 // the putIntForUser() will fail.
2857 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2858 android.provider.Settings.Secure.LOCATION_MODE,
2859 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2860 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2861 } finally {
2862 Binder.restoreCallingIdentity(identity);
2863 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002864 return user;
2865 }
2866
2867 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002868 * Find the current guest user. If the Guest user is partial,
2869 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002870 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002871 private UserInfo findCurrentGuestUser() {
2872 synchronized (mUsersLock) {
2873 final int size = mUsers.size();
2874 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002875 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002876 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2877 return user;
2878 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002879 }
2880 }
2881 return null;
2882 }
2883
2884 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002885 * Mark this guest user for deletion to allow us to create another guest
2886 * and switch to that user before actually removing this guest.
2887 * @param userHandle the userid of the current guest
2888 * @return whether the user could be marked for deletion
2889 */
Amith Yamasani12747872015-12-07 14:19:49 -08002890 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002891 public boolean markGuestForDeletion(int userHandle) {
2892 checkManageUsersPermission("Only the system can remove users");
2893 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2894 UserManager.DISALLOW_REMOVE_USER, false)) {
2895 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2896 return false;
2897 }
2898
2899 long ident = Binder.clearCallingIdentity();
2900 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002901 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002902 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002903 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002904 userData = mUsers.get(userHandle);
2905 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002906 return false;
2907 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002908 }
Amith Yamasani12747872015-12-07 14:19:49 -08002909 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002910 return false;
2911 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002912 // We set this to a guest user that is to be removed. This is a temporary state
2913 // where we are allowed to add new Guest users, even if this one is still not
2914 // removed. This user will still show up in getUserInfo() calls.
2915 // If we don't get around to removing this Guest user, it will be purged on next
2916 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002917 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002918 // Mark it as disabled, so that it isn't returned any more when
2919 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002920 userData.info.flags |= UserInfo.FLAG_DISABLED;
2921 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002922 }
2923 } finally {
2924 Binder.restoreCallingIdentity(ident);
2925 }
2926 return true;
2927 }
2928
2929 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002930 * Removes a user and all data directories created for that user. This method should be called
2931 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002932 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002933 */
Amith Yamasani12747872015-12-07 14:19:49 -08002934 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002935 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002936 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002937 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002938
2939 final boolean isManagedProfile;
2940 synchronized (mUsersLock) {
2941 UserInfo userInfo = getUserInfoLU(userHandle);
2942 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2943 }
2944 String restriction = isManagedProfile
2945 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2946 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2947 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002948 return false;
2949 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002950 return removeUserUnchecked(userHandle);
2951 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002952
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002953 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002954 long ident = Binder.clearCallingIdentity();
2955 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002956 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002957 int currentUser = ActivityManager.getCurrentUser();
2958 if (currentUser == userHandle) {
jovanaka6763a32018-12-03 17:23:20 -08002959 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002960 return false;
2961 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002962 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002963 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002964 userData = mUsers.get(userHandle);
jovanaka6763a32018-12-03 17:23:20 -08002965 if (userHandle == UserHandle.USER_SYSTEM) {
2966 Log.e(LOG_TAG, "System user cannot be removed.");
2967 return false;
2968 }
2969
2970 if (userData == null) {
2971 Log.e(LOG_TAG, String.format(
2972 "Cannot remove user %d, invalid user id provided.", userHandle));
2973 return false;
2974 }
2975
2976 if (mRemovingUserIds.get(userHandle)) {
2977 Log.e(LOG_TAG, String.format(
2978 "User %d is already scheduled for removal.", userHandle));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002979 return false;
2980 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002981
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002982 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002983 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002984
Kenny Guyee58b4f2014-05-23 15:19:53 +01002985 // Set this to a partially created user, so that the user will be purged
2986 // on next startup, in case the runtime stops now before stopping and
2987 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002988 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002989 // Mark it as disabled, so that it isn't returned any more when
2990 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002991 userData.info.flags |= UserInfo.FLAG_DISABLED;
2992 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002993 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002994 try {
2995 mAppOpsService.removeUser(userHandle);
2996 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08002997 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002998 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002999
Amith Yamasani12747872015-12-07 14:19:49 -08003000 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
3001 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003002 // Send broadcast to notify system that the user removed was a
3003 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08003004 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01003005 }
3006
3007 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
3008 int res;
3009 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003010 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07003011 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01003012 @Override
3013 public void userStopped(int userId) {
3014 finishRemoveUser(userId);
3015 }
3016 @Override
3017 public void userStopAborted(int userId) {
3018 }
3019 });
3020 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08003021 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003022 return false;
3023 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01003024 return res == ActivityManager.USER_OP_SUCCESS;
3025 } finally {
3026 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003027 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003028 }
3029
Andreas Gampea36dc622018-02-05 17:19:22 -08003030 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003031 @VisibleForTesting
3032 void addRemovingUserIdLocked(int userId) {
3033 // We remember deleted user IDs to prevent them from being
3034 // reused during the current boot; they can still be reused
3035 // after a reboot or recycling of userIds.
3036 mRemovingUserIds.put(userId, true);
3037 mRecentlyRemovedIds.add(userId);
3038 // Keep LRU queue of recently removed IDs for recycling
3039 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3040 mRecentlyRemovedIds.removeFirst();
3041 }
3042 }
3043
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003044 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07003045 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003046 // Let other services shutdown any activity and clean up their state before completely
3047 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003048 long ident = Binder.clearCallingIdentity();
3049 try {
3050 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
3051 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003052 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3053 android.Manifest.permission.MANAGE_USERS,
3054
3055 new BroadcastReceiver() {
3056 @Override
3057 public void onReceive(Context context, Intent intent) {
3058 if (DBG) {
3059 Slog.i(LOG_TAG,
3060 "USER_REMOVED broadcast sent, cleaning up user data "
3061 + userHandle);
3062 }
3063 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003064 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003065 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003066 // Clean up any ActivityTaskManager state
3067 LocalServices.getService(ActivityTaskManagerInternal.class)
3068 .onUserStopped(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003069 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003070 }
3071 }.start();
3072 }
3073 },
3074
3075 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003076 } finally {
3077 Binder.restoreCallingIdentity(ident);
3078 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003079 }
3080
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003081 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07003082 try {
3083 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
3084 } catch (IllegalStateException e) {
3085 // This may be simply because the user was partially created.
3086 Slog.i(LOG_TAG,
3087 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
3088 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003089
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003090 // Cleanup gatekeeper secure user id
3091 try {
3092 final IGateKeeperService gk = GateKeeper.getService();
3093 if (gk != null) {
3094 gk.clearSecureUserId(userHandle);
3095 }
3096 } catch (Exception ex) {
3097 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3098 }
3099
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003100 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003101 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003102
3103 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003104 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003105 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3106
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003107 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003108 synchronized (mUsersLock) {
3109 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003110 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003111 }
3112 synchronized (mUserStates) {
3113 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003114 }
3115 synchronized (mRestrictionsLock) {
3116 mBaseUserRestrictions.remove(userHandle);
3117 mAppliedUserRestrictions.remove(userHandle);
3118 mCachedEffectiveUserRestrictions.remove(userHandle);
3119 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003120 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3121 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3122 applyUserRestrictionsForAllUsersLR();
3123 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003124 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003125 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003126 synchronized (mPackagesLock) {
3127 writeUserListLP();
3128 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003129 // Remove user file
3130 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3131 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003132 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003133 if (RELEASE_DELETED_USER_ID) {
3134 synchronized (mUsers) {
3135 mRemovingUserIds.delete(userHandle);
3136 }
3137 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003138 }
3139
Kenny Guyf8d3a232014-05-15 16:09:52 +01003140 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003141 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003142 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3143 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003144 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003145 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003146 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003147 }
3148
Amith Yamasani2a003292012-08-14 18:25:45 -07003149 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003150 public Bundle getApplicationRestrictions(String packageName) {
3151 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3152 }
3153
3154 @Override
3155 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003156 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003157 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003158 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003159 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003160 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003161 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003162 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003163 }
3164 }
3165
3166 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003167 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003168 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003169 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003170 if (restrictions != null) {
3171 restrictions.setDefusable(true);
3172 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003173 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003174 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003175 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003176 } else {
3177 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003178 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003179 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003180 }
Robin Lee66e5d962014-04-09 16:44:21 +01003181
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003182 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3183 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3184 changeIntent.setPackage(packageName);
3185 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3186 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003187 }
3188
3189 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003190 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003191 try {
3192 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003193 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003194 } catch (NameNotFoundException nnfe) {
3195 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003196 } finally {
3197 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003198 }
3199 }
3200
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003201 @GuardedBy("mAppRestrictionsLock")
3202 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003203 AtomicFile restrictionsFile =
3204 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3205 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003206 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003207 }
3208
3209 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003210 @GuardedBy("mAppRestrictionsLock")
3211 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003212 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003213 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003214 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003215 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003216 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003217
3218 FileInputStream fis = null;
3219 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003220 fis = restrictionsFile.openRead();
3221 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003222 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003223 XmlUtils.nextElement(parser);
3224 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003225 Slog.e(LOG_TAG, "Unable to read restrictions file "
3226 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003227 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003228 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003229 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3230 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003231 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003232 } catch (IOException|XmlPullParserException e) {
3233 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003234 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003235 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003236 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003237 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003238 }
3239
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003240 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3241 XmlPullParser parser) throws XmlPullParserException, IOException {
3242 int type = parser.getEventType();
3243 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3244 String key = parser.getAttributeValue(null, ATTR_KEY);
3245 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3246 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3247 if (multiple != null) {
3248 values.clear();
3249 int count = Integer.parseInt(multiple);
3250 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3251 if (type == XmlPullParser.START_TAG
3252 && parser.getName().equals(TAG_VALUE)) {
3253 values.add(parser.nextText().trim());
3254 count--;
3255 }
3256 }
3257 String [] valueStrings = new String[values.size()];
3258 values.toArray(valueStrings);
3259 restrictions.putStringArray(key, valueStrings);
3260 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3261 restrictions.putBundle(key, readBundleEntry(parser, values));
3262 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3263 final int outerDepth = parser.getDepth();
3264 ArrayList<Bundle> bundleList = new ArrayList<>();
3265 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3266 Bundle childBundle = readBundleEntry(parser, values);
3267 bundleList.add(childBundle);
3268 }
3269 restrictions.putParcelableArray(key,
3270 bundleList.toArray(new Bundle[bundleList.size()]));
3271 } else {
3272 String value = parser.nextText().trim();
3273 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3274 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3275 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3276 restrictions.putInt(key, Integer.parseInt(value));
3277 } else {
3278 restrictions.putString(key, value);
3279 }
3280 }
3281 }
3282 }
3283
3284 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3285 throws IOException, XmlPullParserException {
3286 Bundle childBundle = new Bundle();
3287 final int outerDepth = parser.getDepth();
3288 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3289 readEntry(childBundle, values, parser);
3290 }
3291 return childBundle;
3292 }
3293
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003294 @GuardedBy("mAppRestrictionsLock")
3295 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003296 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003297 AtomicFile restrictionsFile = new AtomicFile(
3298 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003299 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003300 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003301 }
3302
3303 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003304 @GuardedBy("mAppRestrictionsLock")
3305 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003306 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003307 try {
3308 fos = restrictionsFile.startWrite();
3309 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3310
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003311 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003312 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003313 serializer.startDocument(null, true);
3314 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3315
3316 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003317 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003318 serializer.endTag(null, TAG_RESTRICTIONS);
3319
3320 serializer.endDocument();
3321 restrictionsFile.finishWrite(fos);
3322 } catch (Exception e) {
3323 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003324 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3325 }
3326 }
3327
3328 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3329 throws IOException {
3330 for (String key : restrictions.keySet()) {
3331 Object value = restrictions.get(key);
3332 serializer.startTag(null, TAG_ENTRY);
3333 serializer.attribute(null, ATTR_KEY, key);
3334
3335 if (value instanceof Boolean) {
3336 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3337 serializer.text(value.toString());
3338 } else if (value instanceof Integer) {
3339 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3340 serializer.text(value.toString());
3341 } else if (value == null || value instanceof String) {
3342 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3343 serializer.text(value != null ? (String) value : "");
3344 } else if (value instanceof Bundle) {
3345 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3346 writeBundle((Bundle) value, serializer);
3347 } else if (value instanceof Parcelable[]) {
3348 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3349 Parcelable[] array = (Parcelable[]) value;
3350 for (Parcelable parcelable : array) {
3351 if (!(parcelable instanceof Bundle)) {
3352 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3353 }
3354 serializer.startTag(null, TAG_ENTRY);
3355 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3356 writeBundle((Bundle) parcelable, serializer);
3357 serializer.endTag(null, TAG_ENTRY);
3358 }
3359 } else {
3360 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3361 String[] values = (String[]) value;
3362 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3363 for (String choice : values) {
3364 serializer.startTag(null, TAG_VALUE);
3365 serializer.text(choice != null ? choice : "");
3366 serializer.endTag(null, TAG_VALUE);
3367 }
3368 }
3369 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003370 }
3371 }
3372
3373 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003374 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003375 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003376 final UserInfo userInfo = getUserInfoLU(userHandle);
3377 return userInfo != null ? userInfo.serialNumber : -1;
Amith Yamasani2a003292012-08-14 18:25:45 -07003378 }
3379 }
3380
3381 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003382 public boolean isUserNameSet(int userHandle) {
3383 synchronized (mUsersLock) {
Pavel Grafov9c295d42019-03-26 19:42:08 +00003384 final UserInfo userInfo = getUserInfoLU(userHandle);
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003385 return userInfo != null && userInfo.name != null;
3386 }
3387 }
3388
3389 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003390 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003391 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003392 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003393 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003394 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003395 }
3396 // Not found
3397 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003398 }
3399 }
3400
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003401 @Override
3402 public long getUserCreationTime(int userHandle) {
3403 int callingUserId = UserHandle.getCallingUserId();
3404 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003405 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003406 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003407 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003408 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003409 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003410 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003411 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003412 }
3413 }
3414 }
3415 if (userInfo == null) {
3416 throw new SecurityException("userHandle can only be the calling user or a managed "
3417 + "profile associated with this user");
3418 }
3419 return userInfo.creationTime;
3420 }
3421
Amith Yamasani0b285492011-04-14 17:35:23 -07003422 /**
3423 * Caches the list of user ids in an array, adjusting the array size when necessary.
3424 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003425 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003426 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003427 synchronized (mUsersLock) {
3428 final int userSize = mUsers.size();
3429 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003430 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003431 num++;
3432 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003433 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003434 final int[] newUsers = new int[num];
3435 int n = 0;
3436 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003437 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003438 newUsers[n++] = mUsers.keyAt(i);
3439 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003440 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003441 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003442 }
3443 }
3444
3445 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003446 * Called right before a user is started. This gives us a chance to prepare
3447 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003448 */
3449 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003450 UserInfo userInfo = getUserInfo(userId);
3451 if (userInfo == null) {
3452 return;
3453 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003454 TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3455 t.traceBegin("onBeforeStartUser-" + userId);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003456 final int userSerial = userInfo.serialNumber;
3457 // Migrate only if build fingerprints mismatch
3458 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003459 t.traceBegin("prepareUserData");
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003460 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003461 t.traceEnd();
3462 t.traceBegin("reconcileAppsData");
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003463 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Felipe Leme3aad1be2019-05-31 11:43:12 -07003464 t.traceEnd();
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003465
3466 if (userId != UserHandle.USER_SYSTEM) {
Felipe Leme3aad1be2019-05-31 11:43:12 -07003467 t.traceBegin("applyUserRestrictions");
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003468 synchronized (mRestrictionsLock) {
3469 applyUserRestrictionsLR(userId);
3470 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003471 t.traceEnd();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003472 }
Felipe Leme3aad1be2019-05-31 11:43:12 -07003473 t.traceEnd(); // onBeforeStartUser
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003474 }
3475
3476 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003477 * Called right before a user is unlocked. This gives us a chance to prepare
3478 * app storage.
3479 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003480 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003481 UserInfo userInfo = getUserInfo(userId);
3482 if (userInfo == null) {
3483 return;
3484 }
3485 final int userSerial = userInfo.serialNumber;
3486 // Migrate only if build fingerprints mismatch
3487 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003488 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003489 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003490 }
3491
3492 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003493 * Examine all users present on given mounted volume, and destroy data
3494 * belonging to users that are no longer valid, or whose user ID has been
3495 * recycled.
3496 */
3497 void reconcileUsers(String volumeUuid) {
3498 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3499 }
3500
3501 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003502 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003503 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003504 * @param userId the user that was just foregrounded
3505 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003506 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003507 UserData userData = getUserDataNoChecks(userId);
3508 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003509 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3510 return;
3511 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003512
3513 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003514 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003515 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003516 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003517 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3518 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003519 }
3520
3521 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003522 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003523 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003524 @VisibleForTesting
3525 int getNextAvailableId() {
3526 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003527 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003528 nextId = scanNextAvailableIdLocked();
3529 if (nextId >= 0) {
3530 return nextId;
3531 }
3532 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3533 // except most recently removed
3534 if (mRemovingUserIds.size() > 0) {
3535 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3536 mRemovingUserIds.clear();
3537 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3538 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003539 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003540 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003541 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003542 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003543 if (nextId < 0) {
3544 throw new IllegalStateException("No user id available!");
3545 }
3546 return nextId;
3547 }
3548
Andreas Gampea36dc622018-02-05 17:19:22 -08003549 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003550 private int scanNextAvailableIdLocked() {
3551 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3552 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3553 return i;
3554 }
3555 }
3556 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003557 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003558
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003559 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003560 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3561 }
3562
Amith Yamasani920ace02012-09-20 22:15:37 -07003563 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003564 public void setSeedAccountData(int userId, String accountName, String accountType,
3565 PersistableBundle accountOptions, boolean persist) {
3566 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3567 synchronized (mPackagesLock) {
3568 final UserData userData;
3569 synchronized (mUsersLock) {
3570 userData = getUserDataLU(userId);
3571 if (userData == null) {
3572 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3573 return;
3574 }
3575 userData.seedAccountName = accountName;
3576 userData.seedAccountType = accountType;
3577 userData.seedAccountOptions = accountOptions;
3578 userData.persistSeedData = persist;
3579 }
3580 if (persist) {
3581 writeUserLP(userData);
3582 }
3583 }
3584 }
3585
3586 @Override
3587 public String getSeedAccountName() throws RemoteException {
3588 checkManageUsersPermission("Cannot get seed account information");
3589 synchronized (mUsersLock) {
3590 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3591 return userData.seedAccountName;
3592 }
3593 }
3594
3595 @Override
3596 public String getSeedAccountType() throws RemoteException {
3597 checkManageUsersPermission("Cannot get seed account information");
3598 synchronized (mUsersLock) {
3599 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3600 return userData.seedAccountType;
3601 }
3602 }
3603
3604 @Override
3605 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3606 checkManageUsersPermission("Cannot get seed account information");
3607 synchronized (mUsersLock) {
3608 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3609 return userData.seedAccountOptions;
3610 }
3611 }
3612
3613 @Override
3614 public void clearSeedAccountData() throws RemoteException {
3615 checkManageUsersPermission("Cannot clear seed account information");
3616 synchronized (mPackagesLock) {
3617 UserData userData;
3618 synchronized (mUsersLock) {
3619 userData = getUserDataLU(UserHandle.getCallingUserId());
3620 if (userData == null) return;
3621 userData.clearSeedAccountData();
3622 }
3623 writeUserLP(userData);
3624 }
3625 }
3626
3627 @Override
3628 public boolean someUserHasSeedAccount(String accountName, String accountType)
3629 throws RemoteException {
3630 checkManageUsersPermission("Cannot check seed account information");
3631 synchronized (mUsersLock) {
3632 final int userSize = mUsers.size();
3633 for (int i = 0; i < userSize; i++) {
3634 final UserData data = mUsers.valueAt(i);
3635 if (data.info.isInitialized()) continue;
3636 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3637 continue;
3638 }
3639 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3640 continue;
3641 }
3642 return true;
3643 }
3644 }
3645 return false;
3646 }
3647
3648 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003649 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003650 FileDescriptor err, String[] args, ShellCallback callback,
3651 ResultReceiver resultReceiver) {
3652 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003653 }
3654
3655 int onShellCommand(Shell shell, String cmd) {
3656 if (cmd == null) {
3657 return shell.handleDefaultCommands(cmd);
3658 }
3659
3660 final PrintWriter pw = shell.getOutPrintWriter();
3661 try {
3662 switch(cmd) {
3663 case "list":
3664 return runList(pw);
Hui Yu8ba65972018-04-16 18:45:48 -07003665 default:
3666 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003667 }
3668 } catch (RemoteException e) {
3669 pw.println("Remote exception: " + e);
3670 }
3671 return -1;
3672 }
3673
3674 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003675 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003676 final List<UserInfo> users = getUsers(false);
3677 if (users == null) {
3678 pw.println("Error: couldn't get users");
3679 return 1;
3680 } else {
3681 pw.println("Users:");
3682 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003683 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003684 pw.println("\t" + users.get(i).toString() + running);
3685 }
3686 return 0;
3687 }
3688 }
3689
3690 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003691 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003692 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003693
3694 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003695 final long nowRealtime = SystemClock.elapsedRealtime();
Amith Yamasani920ace02012-09-20 22:15:37 -07003696 StringBuilder sb = new StringBuilder();
3697 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003698 synchronized (mUsersLock) {
3699 pw.println("Users:");
3700 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003701 UserData userData = mUsers.valueAt(i);
3702 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003703 continue;
3704 }
Amith Yamasani12747872015-12-07 14:19:49 -08003705 UserInfo userInfo = userData.info;
3706 final int userId = userInfo.id;
3707 pw.print(" "); pw.print(userInfo);
3708 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003709 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003710 pw.print(" <removing> ");
3711 }
Amith Yamasani12747872015-12-07 14:19:49 -08003712 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003713 pw.print(" <partial>");
3714 }
3715 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003716 pw.print(" State: ");
3717 final int state;
3718 synchronized (mUserStates) {
3719 state = mUserStates.get(userId, -1);
3720 }
3721 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003722 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003723 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3724
Fyodor Kupolov82402752015-10-28 14:54:51 -07003725 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003726 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3727
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003728 pw.print(" Last logged in fingerprint: ");
3729 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003730
3731 pw.print(" Start time: ");
3732 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3733
3734 pw.print(" Unlock time: ");
3735 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3736
Makoto Onukie7927da2015-11-25 10:05:17 -08003737 pw.print(" Has profile owner: ");
3738 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003739 pw.println(" Restrictions:");
3740 synchronized (mRestrictionsLock) {
3741 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003742 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003743 pw.println(" Device policy global restrictions:");
3744 UserRestrictionsUtils.dumpRestrictions(
3745 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003746 pw.println(" Device policy local restrictions:");
3747 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003748 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003749 pw.println(" Effective restrictions:");
3750 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003751 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003752 }
Amith Yamasani12747872015-12-07 14:19:49 -08003753
3754 if (userData.account != null) {
3755 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003756 pw.println();
3757 }
Amith Yamasani12747872015-12-07 14:19:49 -08003758
3759 if (userData.seedAccountName != null) {
3760 pw.print(" Seed account name: " + userData.seedAccountName);
3761 pw.println();
3762 if (userData.seedAccountType != null) {
3763 pw.print(" account type: " + userData.seedAccountType);
3764 pw.println();
3765 }
3766 if (userData.seedAccountOptions != null) {
3767 pw.print(" account options exist");
3768 pw.println();
3769 }
3770 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003771 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003772 }
Amith Yamasani12747872015-12-07 14:19:49 -08003773 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003774 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003775 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003776 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003777 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003778 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003779 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003780 synchronized (mUsersLock) {
3781 pw.println();
3782 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003783 if (mRemovingUserIds.size() > 0) {
3784 pw.println();
3785 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3786 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003787 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003788 synchronized (mUserStates) {
3789 pw.println(" Started users state: " + mUserStates);
3790 }
Amith Yamasani12747872015-12-07 14:19:49 -08003791 // Dump some capabilities
3792 pw.println();
3793 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3794 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003795 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3796 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003797 }
3798 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003799
Makoto Onuki73dded22017-12-20 13:14:48 +09003800 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3801 if (time == 0) {
3802 pw.println("<unknown>");
3803 } else {
3804 sb.setLength(0);
3805 TimeUtils.formatDuration(nowTime - time, sb);
3806 sb.append(" ago");
3807 pw.println(sb);
3808 }
3809 }
3810
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003811 final class MainHandler extends Handler {
3812
3813 @Override
3814 public void handleMessage(Message msg) {
3815 switch (msg.what) {
3816 case WRITE_USER_MSG:
3817 removeMessages(WRITE_USER_MSG, msg.obj);
3818 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003819 int userId = ((UserData) msg.obj).info.id;
3820 UserData userData = getUserDataNoChecks(userId);
3821 if (userData != null) {
3822 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003823 }
3824 }
3825 }
3826 }
3827 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003828
3829 /**
3830 * @param userId
3831 * @return whether the user has been initialized yet
3832 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003833 boolean isUserInitialized(int userId) {
3834 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003835 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003836
3837 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003838 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003839 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3840 boolean isDeviceOwner, int cameraRestrictionScope) {
3841 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3842 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003843 }
3844
3845 @Override
3846 public Bundle getBaseUserRestrictions(int userId) {
3847 synchronized (mRestrictionsLock) {
3848 return mBaseUserRestrictions.get(userId);
3849 }
3850 }
3851
3852 @Override
3853 public void setBaseUserRestrictionsByDpmsForMigration(
3854 int userId, Bundle baseRestrictions) {
3855 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003856 if (updateRestrictionsIfNeededLR(
3857 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3858 invalidateEffectiveUserRestrictionsLR(userId);
3859 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003860 }
3861
Amith Yamasani12747872015-12-07 14:19:49 -08003862 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003863 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003864 if (userData != null) {
3865 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003866 } else {
3867 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3868 }
3869 }
3870 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003871
3872 @Override
3873 public boolean getUserRestriction(int userId, String key) {
3874 return getUserRestrictions(userId).getBoolean(key);
3875 }
3876
3877 @Override
3878 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3879 synchronized (mUserRestrictionsListeners) {
3880 mUserRestrictionsListeners.add(listener);
3881 }
3882 }
3883
3884 @Override
3885 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3886 synchronized (mUserRestrictionsListeners) {
3887 mUserRestrictionsListeners.remove(listener);
3888 }
3889 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003890
3891 @Override
3892 public void setDeviceManaged(boolean isManaged) {
3893 synchronized (mUsersLock) {
3894 mIsDeviceManaged = isManaged;
3895 }
3896 }
3897
3898 @Override
3899 public void setUserManaged(int userId, boolean isManaged) {
3900 synchronized (mUsersLock) {
3901 mIsUserManaged.put(userId, isManaged);
3902 }
3903 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003904
3905 @Override
3906 public void setUserIcon(int userId, Bitmap bitmap) {
3907 long ident = Binder.clearCallingIdentity();
3908 try {
3909 synchronized (mPackagesLock) {
3910 UserData userData = getUserDataNoChecks(userId);
3911 if (userData == null || userData.info.partial) {
3912 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3913 return;
3914 }
3915 writeBitmapLP(userData.info, bitmap);
3916 writeUserLP(userData);
3917 }
3918 sendUserInfoChangedBroadcast(userId);
3919 } finally {
3920 Binder.restoreCallingIdentity(ident);
3921 }
3922 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003923
3924 @Override
3925 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3926 synchronized (mUsersLock) {
3927 mForceEphemeralUsers = forceEphemeralUsers;
3928 }
3929 }
3930
3931 @Override
3932 public void removeAllUsers() {
3933 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3934 // Remove the non-system users straight away.
3935 removeNonSystemUsers();
3936 } else {
3937 // Switch to the system user first and then remove the other users.
3938 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3939 @Override
3940 public void onReceive(Context context, Intent intent) {
3941 int userId =
3942 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3943 if (userId != UserHandle.USER_SYSTEM) {
3944 return;
3945 }
3946 mContext.unregisterReceiver(this);
3947 removeNonSystemUsers();
3948 }
3949 };
3950 IntentFilter userSwitchedFilter = new IntentFilter();
3951 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3952 mContext.registerReceiver(
3953 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3954
3955 // Switch to the system user.
3956 ActivityManager am =
3957 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3958 am.switchUser(UserHandle.USER_SYSTEM);
3959 }
3960 }
phweisse9c44062016-02-10 12:57:38 +01003961
3962 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003963 public void onEphemeralUserStop(int userId) {
3964 synchronized (mUsersLock) {
3965 UserInfo userInfo = getUserInfoLU(userId);
3966 if (userInfo != null && userInfo.isEphemeral()) {
3967 // Do not allow switching back to the ephemeral user again as the user is going
3968 // to be deleted.
3969 userInfo.flags |= UserInfo.FLAG_DISABLED;
3970 if (userInfo.isGuest()) {
3971 // Indicate that the guest will be deleted after it stops.
3972 userInfo.guestToRemove = true;
3973 }
3974 }
3975 }
3976 }
3977
3978 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003979 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3980 String[] disallowedPackages) {
3981 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3982 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003983 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003984 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003985 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3986 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3987 }
3988 return user;
3989 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003990
3991 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003992 public boolean removeUserEvenWhenDisallowed(int userId) {
3993 return removeUserUnchecked(userId);
3994 }
3995
3996 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003997 public boolean isUserRunning(int userId) {
3998 synchronized (mUserStates) {
3999 return mUserStates.get(userId, -1) >= 0;
4000 }
4001 }
4002
4003 @Override
4004 public void setUserState(int userId, int userState) {
4005 synchronized (mUserStates) {
4006 mUserStates.put(userId, userState);
4007 }
4008 }
4009
4010 @Override
4011 public void removeUserState(int userId) {
4012 synchronized (mUserStates) {
4013 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004014 }
4015 }
4016
4017 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07004018 public int[] getUserIds() {
4019 return UserManagerService.this.getUserIds();
4020 }
4021
4022 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004023 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004024 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00004025 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004026 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004027 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004028 // Special case, in the stopping/shutdown state user key can still be unlocked
4029 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4030 return StorageManager.isUserKeyUnlocked(userId);
4031 }
4032 return (state == UserState.STATE_RUNNING_UNLOCKING)
4033 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004034 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004035
4036 @Override
4037 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004038 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004039 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004040 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004041 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004042 // Special case, in the stopping/shutdown state user key can still be unlocked
4043 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4044 return StorageManager.isUserKeyUnlocked(userId);
4045 }
4046 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004047 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004048
4049 @Override
4050 public boolean isUserInitialized(int userId) {
4051 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4052 }
4053
4054 @Override
4055 public boolean exists(int userId) {
4056 return getUserInfoNoChecks(userId) != null;
4057 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004058
4059 @Override
4060 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4061 boolean throwSecurityException) {
4062 if (targetUserId == callingUserId) {
4063 return true;
4064 }
4065 synchronized (mUsersLock) {
4066 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4067 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4068 if (throwSecurityException) {
4069 throw new SecurityException(
4070 debugMsg + " for another profile "
4071 + targetUserId + " from " + callingUserId);
4072 }
4073 }
4074
4075 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4076 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4077 // Do not throw any exception here as this could happen due to race conditions
4078 // between the system updating its state and the client getting notified.
4079 if (throwSecurityException) {
4080 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4081 + targetUserId + " from " + callingUserId);
4082 }
4083 return false;
4084 }
4085
4086 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4087 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4088 if (throwSecurityException) {
4089 throw new SecurityException(
4090 debugMsg + " for unrelated profile " + targetUserId);
4091 }
4092 return false;
4093 }
4094 }
4095 return true;
4096 }
4097
4098 @Override
4099 public int getProfileParentId(int userId) {
4100 synchronized (mUsersLock) {
4101 UserInfo profileParent = getProfileParentLU(userId);
4102 if (profileParent == null) {
4103 return userId;
4104 }
4105 return profileParent.id;
4106 }
4107 }
yuemingw1d13eae2018-01-30 17:27:54 +00004108
4109 @Override
4110 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4111 String value, int callingUid) {
4112 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4113 value, callingUid);
4114 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004115 }
4116
4117 /* Remove all the users except of the system one. */
4118 private void removeNonSystemUsers() {
4119 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4120 synchronized (mUsersLock) {
4121 final int userSize = mUsers.size();
4122 for (int i = 0; i < userSize; i++) {
4123 UserInfo ui = mUsers.valueAt(i).info;
4124 if (ui.id != UserHandle.USER_SYSTEM) {
4125 usersToRemove.add(ui);
4126 }
4127 }
4128 }
4129 for (UserInfo ui: usersToRemove) {
4130 removeUser(ui.id);
4131 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004132 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004133
4134 private class Shell extends ShellCommand {
4135 @Override
4136 public int onCommand(String cmd) {
4137 return onShellCommand(this, cmd);
4138 }
4139
4140 @Override
4141 public void onHelp() {
4142 final PrintWriter pw = getOutPrintWriter();
4143 pw.println("User manager (user) commands:");
4144 pw.println(" help");
4145 pw.println(" Print this help text.");
4146 pw.println("");
4147 pw.println(" list");
4148 pw.println(" Prints all users on the system.");
4149 }
4150 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004151
4152 private static void debug(String message) {
4153 Log.d(LOG_TAG, message +
4154 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4155 }
Kenny Guy02c89902016-11-15 19:36:38 +00004156
4157 @VisibleForTesting
4158 static int getMaxManagedProfiles() {
4159 // Allow overriding max managed profiles on debuggable builds for testing
4160 // of multiple profiles.
4161 if (!Build.IS_DEBUGGABLE) {
4162 return MAX_MANAGED_PROFILES;
4163 } else {
4164 return SystemProperties.getInt("persist.sys.max_profiles",
4165 MAX_MANAGED_PROFILES);
4166 }
4167 }
4168
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004169 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004170 @VisibleForTesting
4171 int getFreeProfileBadgeLU(int parentUserId) {
4172 int maxManagedProfiles = getMaxManagedProfiles();
4173 boolean[] usedBadges = new boolean[maxManagedProfiles];
4174 final int userSize = mUsers.size();
4175 for (int i = 0; i < userSize; i++) {
4176 UserInfo ui = mUsers.valueAt(i).info;
4177 // Check which badge indexes are already used by this profile group.
4178 if (ui.isManagedProfile()
4179 && ui.profileGroupId == parentUserId
4180 && !mRemovingUserIds.get(ui.id)
4181 && ui.profileBadge < maxManagedProfiles) {
4182 usedBadges[ui.profileBadge] = true;
4183 }
4184 }
4185 for (int i = 0; i < maxManagedProfiles; i++) {
4186 if (!usedBadges[i]) {
4187 return i;
4188 }
4189 }
4190 return 0;
4191 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004192
4193 /**
4194 * Checks if the given user has a managed profile associated with it.
4195 * @param userId The parent user
4196 * @return
4197 */
4198 boolean hasManagedProfile(int userId) {
4199 synchronized (mUsersLock) {
4200 UserInfo userInfo = getUserInfoLU(userId);
4201 final int userSize = mUsers.size();
4202 for (int i = 0; i < userSize; i++) {
4203 UserInfo profile = mUsers.valueAt(i).info;
4204 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4205 return true;
4206 }
4207 }
4208 return false;
4209 }
4210 }
Tony Makd390ae92017-12-28 13:23:10 +00004211
4212 /**
4213 * Check if the calling package name matches with the calling UID, throw
4214 * {@link SecurityException} if not.
4215 */
4216 private void verifyCallingPackage(String callingPackage, int callingUid) {
4217 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4218 if (packageUid != callingUid) {
4219 throw new SecurityException("Specified package " + callingPackage
4220 + " does not match the calling uid " + callingUid);
4221 }
4222 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004223}