blob: f2d4cf31beaa6569111fee66dc926f1bf575aaae [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;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700103import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800104
arangelov9b632d72018-12-07 23:21:22 +0000105import libcore.io.IoUtils;
106
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800107import org.xmlpull.v1.XmlPullParser;
108import org.xmlpull.v1.XmlPullParserException;
109import org.xmlpull.v1.XmlSerializer;
110
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.BufferedOutputStream;
112import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700113import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700115import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000117import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000118import java.io.InputStream;
119import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700120import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100121import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100123import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700124import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700125import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000126import java.util.Objects;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127
Makoto Onuki068c54a2015-10-13 14:34:03 -0700128/**
129 * Service for {@link UserManager}.
130 *
131 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700132 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700133 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800134 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700135 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
136 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
137 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700138 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700139public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700140
Amith Yamasani2a003292012-08-14 18:25:45 -0700141 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800142 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800143 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700144 // Can be used for manual testing of id recycling
145 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700146
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800148 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700150 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700152 private static final String ATTR_CREATION_TIME = "created";
153 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600154 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700155 private static final String ATTR_SERIAL_NO = "serialNumber";
156 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700157 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700158 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700159 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100160 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000161 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700162 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800163 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
164 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530165 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800168 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800169 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100170 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
171 "device_policy_global_restrictions";
172 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100173 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100174 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800175 private static final String TAG_ENTRY = "entry";
176 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800177 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
arangelov9b632d72018-12-07 23:21:22 +0000178 private static final String TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL =
179 "lastRequestQuietModeEnabledCall";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800180 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700181 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800182 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700184 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
185 private static final String ATTR_TYPE_STRING = "s";
186 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700187 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700188 private static final String ATTR_TYPE_BUNDLE = "B";
189 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700190
Amith Yamasani0b285492011-04-14 17:35:23 -0700191 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700192 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700193 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100194 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700195
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800196 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700197 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800198
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700199 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
200 UserInfo.FLAG_MANAGED_PROFILE
201 | UserInfo.FLAG_EPHEMERAL
202 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700203 | UserInfo.FLAG_GUEST
204 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700205
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700206 @VisibleForTesting
207 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700208 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700209 @VisibleForTesting
210 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
211
212 // Max size of the queue of recently removed users
213 @VisibleForTesting
214 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700215
Pavel Grafov6a40f092016-10-25 15:46:51 +0100216 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700217
Amith Yamasani920ace02012-09-20 22:15:37 -0700218 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
219
Nicolas Prevotb8186812015-08-06 15:00:03 +0100220 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700221 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000222 @VisibleForTesting
223 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700224
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800225 static final int WRITE_USER_MSG = 1;
226 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530227
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800228 // Tron counters
229 private static final String TRON_GUEST_CREATED = "users_guest_created";
230 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700231 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800232
Dianne Hackborn4428e172012-08-24 17:43:05 -0700233 private final Context mContext;
234 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700235 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800236 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700237 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600238 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700239 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700240 // Used for serializing access to app restriction files
241 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700242
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800243 private final Handler mHandler;
244
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700245 private final File mUsersDir;
246 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700247
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800248 private static final IBinder mUserRestriconToken = new Binder();
249
Makoto Onuki068c54a2015-10-13 14:34:03 -0700250 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900251 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800252 */
Kenny Guy02c89902016-11-15 19:36:38 +0000253 @VisibleForTesting
254 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800255 // Basic user information and properties
256 UserInfo info;
257 // Account name used when there is a strong association between a user and an account
258 String account;
259 // Account information for seeding into a newly created user. This could also be
260 // used for login validation for an existing user, for updating their credentials.
261 // In the latter case, data may not need to be persisted as it is only valid for the
262 // current login session.
263 String seedAccountName;
264 String seedAccountType;
265 PersistableBundle seedAccountOptions;
266 // Whether to perist the seed account information to be available after a boot
267 boolean persistSeedData;
268
Makoto Onuki73dded22017-12-20 13:14:48 +0900269 /** Elapsed realtime since boot when the user started. */
270 long startRealtime;
271
272 /** Elapsed realtime since boot when the user was unlocked. */
273 long unlockRealtime;
274
arangelov9b632d72018-12-07 23:21:22 +0000275 private long mLastRequestQuietModeEnabledMillis;
276
277 void setLastRequestQuietModeEnabledMillis(long millis) {
278 mLastRequestQuietModeEnabledMillis = millis;
279 }
280
281 long getLastRequestQuietModeEnabledMillis() {
282 return mLastRequestQuietModeEnabledMillis;
283 }
284
Amith Yamasani12747872015-12-07 14:19:49 -0800285 void clearSeedAccountData() {
286 seedAccountName = null;
287 seedAccountType = null;
288 seedAccountOptions = null;
289 persistSeedData = false;
290 }
291 }
292
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800293 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800294 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800295
296 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700297 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100298 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700299 *
300 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
301 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
302 * maybe shared between {@link #mBaseUserRestrictions} and
303 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
304 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700305 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700306 */
307 @GuardedBy("mRestrictionsLock")
308 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
309
310 /**
311 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
312 * with device / profile owner restrictions. We'll initialize it lazily; use
313 * {@link #getEffectiveUserRestrictions} to access it.
314 *
315 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
316 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
317 * maybe shared between {@link #mBaseUserRestrictions} and
318 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
319 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700320 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700321 */
322 @GuardedBy("mRestrictionsLock")
323 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
324
Makoto Onuki4f160732015-10-27 17:15:38 -0700325 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800326 * User restrictions that have already been applied in
327 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
328 * that have changed since the last
329 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700330 */
331 @GuardedBy("mRestrictionsLock")
332 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
333
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800334 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800335 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100336 * that should be applied to all users, including guests. Only non-empty restriction bundles are
337 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800338 */
339 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100340 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800341
342 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100343 * Id of the user that set global restrictions.
344 */
345 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100346 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100347
348 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800349 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100350 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800351 */
352 @GuardedBy("mRestrictionsLock")
353 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
354
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800355 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530356 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800357
358 /**
359 * Set of user IDs being actively removed. Removed IDs linger in this set
360 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700361 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800362 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700363 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800364 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700365
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700366 /**
367 * Queue of recently removed userIds. Used for recycling of userIds
368 */
369 @GuardedBy("mUsersLock")
370 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
371
Fyodor Kupolov82402752015-10-28 14:54:51 -0700372 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700373 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800374 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700375 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700376 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700377
Jason Monk62062992014-05-06 09:55:28 -0400378 private IAppOpsService mAppOpsService;
379
Makoto Onuki068c54a2015-10-13 14:34:03 -0700380 private final LocalService mLocalService;
381
Makoto Onukie7927da2015-11-25 10:05:17 -0800382 @GuardedBy("mUsersLock")
383 private boolean mIsDeviceManaged;
384
385 @GuardedBy("mUsersLock")
386 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
387
Makoto Onukid45a4a22015-11-02 17:17:38 -0800388 @GuardedBy("mUserRestrictionsListeners")
389 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
390 new ArrayList<>();
391
Clara Bayarria1771112015-12-18 16:29:18 +0000392 private final LockPatternUtils mLockPatternUtils;
393
Ricky Waib1dd80b2016-06-07 18:00:55 +0100394 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
395 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
396
397 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
398 @Override
399 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000400 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
401 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100402 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000403 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
404 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800405 // Call setQuietModeEnabled on bg thread to avoid ANR
arangelov9b632d72018-12-07 23:21:22 +0000406 BackgroundThread.getHandler().post(() ->
407 setQuietModeEnabled(userHandle, false, target, /* callingPackage */ null));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100408 }
409 };
410
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100411 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000412 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
413 *
Tony Makbece85d2018-01-12 12:10:17 +0000414 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000415 */
416 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
417 private final IntentSender mTarget;
418
419 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
420 Preconditions.checkNotNull(target);
421 mTarget = target;
422 }
423
424 @Override
425 public void onStarted(int id, Bundle extras) {}
426
427 @Override
428 public void onProgress(int id, int progress, Bundle extras) {}
429
430 @Override
431 public void onFinished(int id, Bundle extras) {
432 try {
433 mContext.startIntentSender(mTarget, null, 0, 0, 0);
434 } catch (IntentSender.SendIntentException e) {
435 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
436 }
437 }
438 }
439
440 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100441 * Whether all users should be created ephemeral.
442 */
443 @GuardedBy("mUsersLock")
444 private boolean mForceEphemeralUsers;
445
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000446 @GuardedBy("mUserStates")
447 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700448
Amith Yamasani258848d2012-08-10 17:06:33 -0700449 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700450
Dianne Hackborn4428e172012-08-24 17:43:05 -0700451 public static UserManagerService getInstance() {
452 synchronized (UserManagerService.class) {
453 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700454 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700455 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700456
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700457 public static class LifeCycle extends SystemService {
458
459 private UserManagerService mUms;
460
461 /**
462 * @param context
463 */
464 public LifeCycle(Context context) {
465 super(context);
466 }
467
468 @Override
469 public void onStart() {
470 mUms = UserManagerService.getInstance();
471 publishBinderService(Context.USER_SERVICE, mUms);
472 }
473
474 @Override
475 public void onBootPhase(int phase) {
476 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
477 mUms.cleanupPartialUsers();
478 }
479 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900480
481 @Override
482 public void onStartUser(int userHandle) {
483 synchronized (mUms.mUsersLock) {
484 final UserData user = mUms.getUserDataLU(userHandle);
485 if (user != null) {
486 user.startRealtime = SystemClock.elapsedRealtime();
487 }
488 }
489 }
490
491 @Override
492 public void onUnlockUser(int userHandle) {
493 synchronized (mUms.mUsersLock) {
494 final UserData user = mUms.getUserDataLU(userHandle);
495 if (user != null) {
496 user.unlockRealtime = SystemClock.elapsedRealtime();
497 }
498 }
499 }
500
501 @Override
502 public void onStopUser(int userHandle) {
503 synchronized (mUms.mUsersLock) {
504 final UserData user = mUms.getUserDataLU(userHandle);
505 if (user != null) {
506 user.startRealtime = 0;
507 user.unlockRealtime = 0;
508 }
509 }
510 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700511 }
512
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700513 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800514 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700515 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800516 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700517 }
518
Dianne Hackborn4428e172012-08-24 17:43:05 -0700519 /**
520 * Called by package manager to create the service. This is closely
521 * associated with the package manager, and the given lock is the
522 * package manager's own lock.
523 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800524 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
525 Object packagesLock) {
526 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700527 }
528
Dianne Hackborn4428e172012-08-24 17:43:05 -0700529 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800530 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700531 mContext = context;
532 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700533 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800534 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800535 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800536 synchronized (mPackagesLock) {
537 mUsersDir = new File(dataDir, USER_INFO_DIR);
538 mUsersDir.mkdirs();
539 // Make zeroth user directory, for services to migrate their files to that location
540 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
541 userZeroDir.mkdirs();
542 FileUtils.setPermissions(mUsersDir.toString(),
543 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
544 -1, -1);
545 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
546 initDefaultGuestRestrictions();
547 readUserListLP();
548 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700549 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700550 mLocalService = new LocalService();
551 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000552 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000553 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700554 }
555
556 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400557 mAppOpsService = IAppOpsService.Stub.asInterface(
558 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800559
560 synchronized (mRestrictionsLock) {
561 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400562 }
Samuel Tand9453b82016-03-14 15:57:02 -0700563
564 UserInfo currentGuestUser = findCurrentGuestUser();
565 if (currentGuestUser != null && !hasUserRestriction(
566 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
567 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
568 // to it, in case this guest was created in a previous version where this
569 // user restriction was not a default guest restriction.
570 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
571 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700572
Ricky Waib1dd80b2016-06-07 18:00:55 +0100573 mContext.registerReceiver(mDisableQuietModeCallback,
574 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
575 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700576 }
577
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700578 void cleanupPartialUsers() {
579 // Prune out any partially created, partially removed and ephemeral users.
580 ArrayList<UserInfo> partials = new ArrayList<>();
581 synchronized (mUsersLock) {
582 final int userSize = mUsers.size();
583 for (int i = 0; i < userSize; i++) {
584 UserInfo ui = mUsers.valueAt(i).info;
585 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
586 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700587 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700588 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700589 }
590 }
591 }
592 final int partialsSize = partials.size();
593 for (int i = 0; i < partialsSize; i++) {
594 UserInfo ui = partials.get(i);
595 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
596 + " (name=" + ui.name + ")");
597 removeUserState(ui.id);
598 }
599 }
600
Amith Yamasani258848d2012-08-10 17:06:33 -0700601 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800602 public String getUserAccount(int userId) {
603 checkManageUserAndAcrossUsersFullPermission("get user account");
604 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800605 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800606 }
607 }
608
609 @Override
610 public void setUserAccount(int userId, String accountName) {
611 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800612 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800613 synchronized (mPackagesLock) {
614 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800615 final UserData userData = mUsers.get(userId);
616 if (userData == null) {
617 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
618 return;
619 }
620 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000621 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800622 userData.account = accountName;
623 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800624 }
625 }
626
627 if (userToUpdate != null) {
628 writeUserLP(userToUpdate);
629 }
630 }
631 }
632
633 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700634 public UserInfo getPrimaryUser() {
635 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700636 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700637 final int userSize = mUsers.size();
638 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800639 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800640 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700641 return ui;
642 }
643 }
644 }
645 return null;
646 }
647
648 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700649 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700650 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700651 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700652 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700653 final int userSize = mUsers.size();
654 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800655 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700656 if (ui.partial) {
657 continue;
658 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800659 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700660 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700661 }
Amith Yamasani13593602012-03-22 16:16:17 -0700662 }
663 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700664 }
Amith Yamasani13593602012-03-22 16:16:17 -0700665 }
666
Amith Yamasani258848d2012-08-10 17:06:33 -0700667 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100668 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700669 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800670 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700671 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700672 } else {
673 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800674 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700675 final long ident = Binder.clearCallingIdentity();
676 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700677 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700678 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100679 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700680 } finally {
681 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000682 }
683 }
684
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700685 @Override
686 public int[] getProfileIds(int userId, boolean enabledOnly) {
687 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700688 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700689 }
690 final long ident = Binder.clearCallingIdentity();
691 try {
692 synchronized (mUsersLock) {
693 return getProfileIdsLU(userId, enabledOnly).toArray();
694 }
695 } finally {
696 Binder.restoreCallingIdentity(ident);
697 }
698 }
699
Amith Yamasanibe465322014-04-24 13:45:17 -0700700 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700701 @GuardedBy("mUsersLock")
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700702 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700703 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
704 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
705 for (int i = 0; i < profileIds.size(); i++) {
706 int profileId = profileIds.get(i);
707 UserInfo userInfo = mUsers.get(profileId).info;
708 // If full info is not required - clear PII data to prevent 3P apps from reading it
709 if (!fullInfo) {
710 userInfo = new UserInfo(userInfo);
711 userInfo.name = null;
712 userInfo.iconPath = null;
713 } else {
714 userInfo = userWithName(userInfo);
715 }
716 users.add(userInfo);
717 }
718 return users;
719 }
720
721 /**
722 * Assume permissions already checked and caller's identity cleared
723 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700724 @GuardedBy("mUsersLock")
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700725 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700726 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700727 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700728 if (user == null) {
729 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700730 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700731 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700732 final int userSize = mUsers.size();
733 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800734 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700735 if (!isProfileOf(user, profile)) {
736 continue;
737 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100738 if (enabledOnly && !profile.isEnabled()) {
739 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700740 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700741 if (mRemovingUserIds.get(profile.id)) {
742 continue;
743 }
Tony Mak80189cd2016-04-05 17:21:42 +0100744 if (profile.partial) {
745 continue;
746 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700747 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700748 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700749 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700750 }
751
Jessica Hummelbe81c802014-04-22 15:49:22 +0100752 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700753 public int getCredentialOwnerProfile(int userHandle) {
754 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000755 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700756 synchronized (mUsersLock) {
757 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700758 if (profileParent != null) {
759 return profileParent.id;
760 }
761 }
762 }
763
764 return userHandle;
765 }
766
767 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700768 public boolean isSameProfileGroup(int userId, int otherUserId) {
769 if (userId == otherUserId) return true;
770 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700771 return isSameProfileGroupNoChecks(userId, otherUserId);
772 }
773
774 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700775 synchronized (mUsersLock) {
776 UserInfo userInfo = getUserInfoLU(userId);
777 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
778 return false;
779 }
780 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
781 if (otherUserInfo == null
782 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
783 return false;
784 }
785 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700786 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700787 }
788
789 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100790 public UserInfo getProfileParent(int userHandle) {
791 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700792 synchronized (mUsersLock) {
793 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700794 }
795 }
796
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800797 @Override
798 public int getProfileParentId(int userHandle) {
799 checkManageUsersPermission("get the profile parent");
Sunny Goyal145c8f82018-02-15 14:27:09 -0800800 return mLocalService.getProfileParentId(userHandle);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800801 }
802
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700803 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700804 private UserInfo getProfileParentLU(int userHandle) {
805 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700806 if (profile == null) {
807 return null;
808 }
809 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800810 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700811 return null;
812 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700813 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100814 }
815 }
816
Fyodor Kupolov82402752015-10-28 14:54:51 -0700817 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100818 return user.id == profile.id ||
819 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
820 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000821 }
822
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000823 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000824 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100825 Intent intent = new Intent();
826 if (inQuietMode) {
827 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
828 } else {
829 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
830 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000831 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
832 intent.putExtra(Intent.EXTRA_USER, profileHandle);
833 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000834 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000835 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000836 }
837
838 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000839 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000840 int userHandle, @Nullable IntentSender target) {
841 Preconditions.checkNotNull(callingPackage);
842
Tony Makb7e6fd42017-12-05 19:40:28 +0000843 if (enableQuietMode && target != null) {
844 throw new IllegalArgumentException(
845 "target should only be specified when we are disabling quiet mode.");
846 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000847
Tony Makd390ae92017-12-28 13:23:10 +0000848 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000849 final long identity = Binder.clearCallingIdentity();
850 try {
arangelov9b632d72018-12-07 23:21:22 +0000851 boolean result = false;
Tony Makb7e6fd42017-12-05 19:40:28 +0000852 if (enableQuietMode) {
arangelov9b632d72018-12-07 23:21:22 +0000853 setQuietModeEnabled(
854 userHandle, true /* enableQuietMode */, target, callingPackage);
855 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000856 } else {
857 boolean needToShowConfirmCredential =
858 mLockPatternUtils.isSecure(userHandle)
859 && !StorageManager.isUserKeyUnlocked(userHandle);
860 if (needToShowConfirmCredential) {
861 showConfirmCredentialToDisableQuietMode(userHandle, target);
Tony Makb7e6fd42017-12-05 19:40:28 +0000862 } else {
arangelov9b632d72018-12-07 23:21:22 +0000863 setQuietModeEnabled(
864 userHandle, false /* enableQuietMode */, target, callingPackage);
865 result = true;
Tony Makb7e6fd42017-12-05 19:40:28 +0000866 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000867 }
arangelov9b632d72018-12-07 23:21:22 +0000868 return result;
Tony Makb7e6fd42017-12-05 19:40:28 +0000869 } finally {
870 Binder.restoreCallingIdentity(identity);
871 }
872 }
873
Tony Make3d1f652017-12-12 11:00:37 +0000874 /**
Tony Makd390ae92017-12-28 13:23:10 +0000875 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000876 * <ul>
877 * <li>Has system UID or root UID</li>
878 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
879 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
880 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000881 * <p>
882 * If caller wants to start an intent after disabling the quiet mode, it must has
883 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000884 */
Tony Makd390ae92017-12-28 13:23:10 +0000885 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
886 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000887 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000888 return;
Tony Make3d1f652017-12-12 11:00:37 +0000889 }
Tony Makd390ae92017-12-28 13:23:10 +0000890 if (startIntent) {
891 throw new SecurityException("MANAGE_USERS permission is required to start intent "
892 + "after disabling quiet mode.");
893 }
jovanakf24ad492018-05-18 12:15:59 -0700894 final boolean hasModifyQuietModePermission = hasPermissionGranted(
895 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000896 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000897 return;
Tony Make3d1f652017-12-12 11:00:37 +0000898 }
899
Tony Makd390ae92017-12-28 13:23:10 +0000900 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000901 final ShortcutServiceInternal shortcutInternal =
902 LocalServices.getService(ShortcutServiceInternal.class);
903 if (shortcutInternal != null) {
904 boolean isForegroundLauncher =
905 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
906 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000907 return;
Tony Make3d1f652017-12-12 11:00:37 +0000908 }
909 }
Tony Makd390ae92017-12-28 13:23:10 +0000910 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
911 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000912 }
913
arangelov9b632d72018-12-07 23:21:22 +0000914 private void setQuietModeEnabled(int userHandle, boolean enableQuietMode,
915 IntentSender target, @Nullable String callingPackage) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000916 final UserInfo profile, parent;
917 final UserData profileUserData;
918 synchronized (mUsersLock) {
919 profile = getUserInfoLU(userHandle);
920 parent = getProfileParentLU(userHandle);
921
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000922 if (profile == null || !profile.isManagedProfile()) {
923 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
924 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000925 if (profile.isQuietModeEnabled() == enableQuietMode) {
926 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
927 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000928 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000929 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
930 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000931 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000932 synchronized (mPackagesLock) {
933 writeUserLP(profileUserData);
934 }
935 try {
936 if (enableQuietMode) {
937 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
938 LocalServices.getService(ActivityManagerInternal.class)
939 .killForegroundAppsForUser(userHandle);
940 } else {
941 IProgressListener callback = target != null
942 ? new DisableQuietModeUserUnlockedCallback(target)
943 : null;
944 ActivityManager.getService().startUserInBackgroundWithListener(
945 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000946 }
arangelov9b632d72018-12-07 23:21:22 +0000947 logQuietModeEnabled(userHandle, enableQuietMode, callingPackage);
Tony Makb7e6fd42017-12-05 19:40:28 +0000948 } catch (RemoteException e) {
949 // Should not happen, same process.
950 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000951 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000952 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
953 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000954 }
955
arangelov9b632d72018-12-07 23:21:22 +0000956 private void logQuietModeEnabled(int userHandle, boolean enableQuietMode,
957 @Nullable String callingPackage) {
958 UserData userData;
959 synchronized (mUsersLock) {
960 userData = getUserDataLU(userHandle);
961 }
962 if (userData == null) {
963 return;
964 }
965 final long now = System.currentTimeMillis();
966 final long period = (userData.getLastRequestQuietModeEnabledMillis() != 0L
967 ? now - userData.getLastRequestQuietModeEnabledMillis()
968 : now - userData.info.creationTime);
969 DevicePolicyEventLogger
970 .createEvent(DevicePolicyEnums.REQUEST_QUIET_MODE_ENABLED)
971 .setStrings(callingPackage)
972 .setBoolean(enableQuietMode)
973 .setTimePeriod(period)
974 .write();
975 userData.setLastRequestQuietModeEnabledMillis(now);
976 }
977
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000978 @Override
979 public boolean isQuietModeEnabled(int userHandle) {
980 synchronized (mPackagesLock) {
981 UserInfo info;
982 synchronized (mUsersLock) {
983 info = getUserInfoLU(userHandle);
984 }
985 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000986 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000987 }
988 return info.isQuietModeEnabled();
989 }
990 }
991
Tony Makb7e6fd42017-12-05 19:40:28 +0000992 /**
993 * Show confirm credential screen to unlock user in order to turn off quiet mode.
994 */
995 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000996 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000997 // otherwise, we show a profile challenge to trigger decryption of the user
998 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
999 Context.KEYGUARD_SERVICE);
1000 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
1001 // lock, confirm screenlock page will know and show personal challenge, and unlock
1002 // work profile when personal challenge is correct
1003 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
1004 userHandle);
1005 if (unlockIntent == null) {
1006 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +01001007 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001008 final Intent callBackIntent = new Intent(
1009 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
1010 if (target != null) {
1011 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001012 }
Tony Makb7e6fd42017-12-05 19:40:28 +00001013 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
1014 callBackIntent.setPackage(mContext.getPackageName());
1015 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1016 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
1017 mContext,
1018 0,
1019 callBackIntent,
1020 PendingIntent.FLAG_CANCEL_CURRENT |
1021 PendingIntent.FLAG_ONE_SHOT |
1022 PendingIntent.FLAG_IMMUTABLE);
1023 // After unlocking the challenge, it will disable quiet mode and run the original
1024 // intentSender
1025 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
1026 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1027 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +01001028 }
1029
1030 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001031 public void setUserEnabled(int userId) {
1032 checkManageUsersPermission("enable user");
1033 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001034 UserInfo info;
1035 synchronized (mUsersLock) {
1036 info = getUserInfoLU(userId);
1037 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001038 if (info != null && !info.isEnabled()) {
1039 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001040 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001041 }
1042 }
1043 }
1044
jovanakf24ad492018-05-18 12:15:59 -07001045 @Override
1046 public void setUserAdmin(int userId) {
1047 checkManageUserAndAcrossUsersFullPermission("set user admin");
1048
1049 synchronized (mPackagesLock) {
1050 UserInfo info;
1051 synchronized (mUsersLock) {
1052 info = getUserInfoLU(userId);
1053 }
1054 if (info == null || info.isAdmin()) {
1055 // Exit if no user found with that id, or the user is already an Admin.
1056 return;
1057 }
1058
1059 info.flags ^= UserInfo.FLAG_ADMIN;
1060 writeUserLP(getUserDataLU(info.id));
1061 }
1062
1063 // Remove non-admin restrictions.
1064 // Keep synchronized with createUserEvenWhenDisallowed.
1065 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1066 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1067 }
1068
Andrew Scull85a63bc2016-10-24 13:47:47 +01001069 /**
1070 * Evicts a user's CE key by stopping and restarting the user.
1071 *
1072 * The key is evicted automatically by the user controller when the user has stopped.
1073 */
1074 @Override
1075 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1076 checkManageUsersPermission("evict CE key");
1077 final IActivityManager am = ActivityManagerNative.getDefault();
1078 final long identity = Binder.clearCallingIdentity();
1079 try {
1080 am.restartUserInBackground(userId);
1081 } catch (RemoteException re) {
1082 throw re.rethrowAsRuntimeException();
1083 } finally {
1084 Binder.restoreCallingIdentity(identity);
1085 }
1086 }
1087
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001088 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001089 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001090 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001091 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001092 return userWithName(getUserInfoLU(userId));
1093 }
1094 }
1095
1096 /**
1097 * Returns a UserInfo object with the name filled in, for Owner, or the original
1098 * if the name is already set.
1099 */
1100 private UserInfo userWithName(UserInfo orig) {
1101 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1102 UserInfo withName = new UserInfo(orig);
1103 withName.name = getOwnerName();
1104 return withName;
1105 } else {
1106 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001107 }
1108 }
1109
1110 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001111 public int getManagedProfileBadge(@UserIdInt int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001112 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getManagedProfileBadge");
Kenny Guy02c89902016-11-15 19:36:38 +00001113 synchronized (mUsersLock) {
1114 UserInfo userInfo = getUserInfoLU(userId);
1115 return userInfo != null ? userInfo.profileBadge : 0;
1116 }
1117 }
1118
1119 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001120 public boolean isManagedProfile(int userId) {
Jon Miranda2b340a22019-01-25 14:03:49 -08001121 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001122 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001123 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001124 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001125 }
1126 }
1127
Amith Yamasani71e6c692013-03-24 17:39:28 -07001128 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001129 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001130 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001131 return mLocalService.isUserUnlockingOrUnlocked(userId);
1132 }
1133
1134 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001135 public boolean isUserUnlocked(int userId) {
1136 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001137 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001138 }
1139
1140 @Override
1141 public boolean isUserRunning(int userId) {
1142 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1143 return mLocalService.isUserRunning(userId);
1144 }
1145
Makoto Onuki73dded22017-12-20 13:14:48 +09001146 @Override
1147 public long getUserStartRealtime() {
1148 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1149 synchronized (mUsersLock) {
1150 final UserData user = getUserDataLU(userId);
1151 if (user != null) {
1152 return user.startRealtime;
1153 }
1154 return 0;
1155 }
1156 }
1157
1158 @Override
1159 public long getUserUnlockRealtime() {
1160 synchronized (mUsersLock) {
1161 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1162 if (user != null) {
1163 return user.unlockRealtime;
1164 }
1165 return 0;
1166 }
1167 }
1168
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001169 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1170 int callingUserId = UserHandle.getCallingUserId();
1171 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1172 hasManageUsersPermission()) {
1173 return;
1174 }
jovanakf24ad492018-05-18 12:15:59 -07001175 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1176 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001177 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1178 + "to: check " + name);
1179 }
1180 }
1181
1182 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001183 public boolean isDemoUser(int userId) {
1184 int callingUserId = UserHandle.getCallingUserId();
1185 if (callingUserId != userId && !hasManageUsersPermission()) {
1186 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1187 + " is a demo user");
1188 }
1189 synchronized (mUsersLock) {
1190 UserInfo userInfo = getUserInfoLU(userId);
1191 return userInfo != null && userInfo.isDemo();
1192 }
1193 }
1194
1195 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001196 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001197 synchronized (mUsersLock) {
1198 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001199 }
1200 }
1201
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001202 @Override
1203 public boolean canHaveRestrictedProfile(int userId) {
1204 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001205 synchronized (mUsersLock) {
1206 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001207 if (userInfo == null || !userInfo.canHaveProfile()) {
1208 return false;
1209 }
1210 if (!userInfo.isAdmin()) {
1211 return false;
1212 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001213 // restricted profile can be created if there is no DO set and the admin user has no PO;
1214 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001215 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001216 }
1217
Fyodor Kupolovca177562017-11-09 17:43:01 -08001218 @Override
1219 public boolean hasRestrictedProfiles() {
1220 checkManageUsersPermission("hasRestrictedProfiles");
1221 final int callingUserId = UserHandle.getCallingUserId();
1222 synchronized (mUsersLock) {
1223 final int userSize = mUsers.size();
1224 for (int i = 0; i < userSize; i++) {
1225 UserInfo profile = mUsers.valueAt(i).info;
1226 if (callingUserId != profile.id
1227 && profile.restrictedProfileParentId == callingUserId) {
1228 return true;
1229 }
1230 }
1231 return false;
1232 }
1233 }
1234
Amith Yamasani195263742012-08-21 15:40:12 -07001235 /*
1236 * Should be locked on mUsers before calling this.
1237 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001238 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001239 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001240 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001241 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001242 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001243 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1244 return null;
1245 }
Amith Yamasani12747872015-12-07 14:19:49 -08001246 return userData != null ? userData.info : null;
1247 }
1248
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001249 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -08001250 private UserData getUserDataLU(int userId) {
1251 final UserData userData = mUsers.get(userId);
1252 // If it is partial and not in the process of being removed, return as unknown user.
1253 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1254 return null;
1255 }
1256 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001257 }
1258
Fyodor Kupolov82402752015-10-28 14:54:51 -07001259 /**
1260 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1261 * <p>No permissions checking or any addition checks are made</p>
1262 */
1263 private UserInfo getUserInfoNoChecks(int userId) {
1264 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001265 final UserData userData = mUsers.get(userId);
1266 return userData != null ? userData.info : null;
1267 }
1268 }
1269
1270 /**
1271 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1272 * <p>No permissions checking or any addition checks are made</p>
1273 */
1274 private UserData getUserDataNoChecks(int userId) {
1275 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001276 return mUsers.get(userId);
1277 }
1278 }
1279
Amith Yamasani236b2b52015-08-18 14:32:14 -07001280 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001281 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001282 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001283 }
1284
Amith Yamasani258848d2012-08-10 17:06:33 -07001285 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001286 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001287 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001288 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001289 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001290 UserData userData = getUserDataNoChecks(userId);
1291 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001292 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1293 return;
1294 }
Amith Yamasani12747872015-12-07 14:19:49 -08001295 if (name != null && !name.equals(userData.info.name)) {
1296 userData.info.name = name;
1297 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001298 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001299 }
1300 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001301 if (changed) {
Bookatzf9368552019-03-14 11:57:09 -07001302 long ident = Binder.clearCallingIdentity();
1303 try {
1304 sendUserInfoChangedBroadcast(userId);
1305 } finally {
1306 Binder.restoreCallingIdentity(ident);
1307 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001308 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001309 }
1310
Amith Yamasani258848d2012-08-10 17:06:33 -07001311 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001312 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001313 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001314 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1315 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1316 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001317 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001318 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001319 }
1320
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001321
1322
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001323 private void sendUserInfoChangedBroadcast(int userId) {
1324 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1325 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1326 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001327 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001328 }
1329
Amith Yamasani258848d2012-08-10 17:06:33 -07001330 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001331 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Leo Hsuab28fff2019-01-30 15:40:56 +08001332 checkManageUsersPermission("get user icon");
Adrian Roos1bdff912015-02-17 15:51:35 +01001333 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001334 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001335 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1336 if (targetUserInfo == null || targetUserInfo.partial) {
1337 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001338 return null;
1339 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001340
1341 final int callingUserId = UserHandle.getCallingUserId();
1342 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1343 final int targetGroupId = targetUserInfo.profileGroupId;
1344 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1345 && callingGroupId == targetGroupId);
1346 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001347 checkManageUsersPermission("get the icon of a user who is not related");
1348 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001349
1350 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001351 return null;
1352 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001353 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001354 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001355
1356 try {
1357 return ParcelFileDescriptor.open(
1358 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1359 } catch (FileNotFoundException e) {
1360 Log.e(LOG_TAG, "Couldn't find icon file", e);
1361 }
1362 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001363 }
1364
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001365 public void makeInitialized(int userId) {
1366 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001367 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001368 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001369 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001370 userData = mUsers.get(userId);
1371 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001372 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001373 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001374 }
Amith Yamasani12747872015-12-07 14:19:49 -08001375 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1376 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001377 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001378 }
1379 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001380 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001381 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001382 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001383 }
1384
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001385 /**
1386 * If default guest restrictions haven't been initialized yet, add the basic
1387 * restrictions.
1388 */
1389 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001390 synchronized (mGuestRestrictions) {
1391 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001392 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001393 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001394 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1395 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1396 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001397 }
1398 }
1399
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001400 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301401 public Bundle getDefaultGuestRestrictions() {
1402 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001403 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301404 return new Bundle(mGuestRestrictions);
1405 }
1406 }
1407
1408 @Override
1409 public void setDefaultGuestRestrictions(Bundle restrictions) {
1410 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001411 synchronized (mGuestRestrictions) {
1412 mGuestRestrictions.clear();
1413 mGuestRestrictions.putAll(restrictions);
1414 }
1415 synchronized (mPackagesLock) {
1416 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301417 }
1418 }
1419
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001420 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001421 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001422 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001423 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1424 boolean isDeviceOwner, int cameraRestrictionScope) {
1425 final Bundle global = new Bundle();
1426 final Bundle local = new Bundle();
1427
1428 // Sort restrictions into local and global ensuring they don't overlap.
1429 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1430 cameraRestrictionScope, global, local);
1431
1432 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001433 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001434 // Update global and local restrictions if they were changed.
1435 globalChanged = updateRestrictionsIfNeededLR(
1436 userId, global, mDevicePolicyGlobalUserRestrictions);
1437 localChanged = updateRestrictionsIfNeededLR(
1438 userId, local, mDevicePolicyLocalUserRestrictions);
1439
1440 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001441 // Remember the global restriction owner userId to be able to make a distinction
1442 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001443 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001444 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001445 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001446 // When profile owner sets restrictions it passes null global bundle and we
1447 // reset global restriction owner userId.
1448 // This means this user used to have DO, but now the DO is gone and the user
1449 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001450 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001451 }
1452 }
1453 }
1454 if (DBG) {
1455 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1456 + " global=" + global + (globalChanged ? " (changed)" : "")
1457 + " local=" + local + (localChanged ? " (changed)" : "")
1458 );
1459 }
1460 // Don't call them within the mRestrictionsLock.
1461 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001462 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001463 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 }
1465 }
1466
1467 synchronized (mRestrictionsLock) {
1468 if (globalChanged) {
1469 applyUserRestrictionsForAllUsersLR();
1470 } else if (localChanged) {
1471 applyUserRestrictionsLR(userId);
1472 }
1473 }
1474 }
1475
Pavel Grafov6a40f092016-10-25 15:46:51 +01001476 /**
1477 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1478 * empty, record is removed from the array.
1479 * @return whether restrictions bundle is different from the old one.
1480 */
1481 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1482 SparseArray<Bundle> restrictionsArray) {
1483 final boolean changed =
1484 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1485 if (changed) {
1486 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1487 restrictionsArray.put(userId, restrictions);
1488 } else {
1489 restrictionsArray.delete(userId);
1490 }
1491 }
1492 return changed;
1493 }
1494
Makoto Onuki068c54a2015-10-13 14:34:03 -07001495 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001496 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001497 final Bundle baseRestrictions =
1498 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001499 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001501
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001502 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1503 // Common case first.
1504 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001505 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001506 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1507 UserRestrictionsUtils.merge(effective, global);
1508 UserRestrictionsUtils.merge(effective, local);
1509
Makoto Onuki068c54a2015-10-13 14:34:03 -07001510 return effective;
1511 }
1512
1513 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001514 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001515 if (DBG) {
1516 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1517 }
1518 mCachedEffectiveUserRestrictions.remove(userId);
1519 }
1520
1521 private Bundle getEffectiveUserRestrictions(int userId) {
1522 synchronized (mRestrictionsLock) {
1523 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1524 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001525 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001526 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1527 }
1528 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001529 }
1530 }
1531
Makoto Onuki068c54a2015-10-13 14:34:03 -07001532 /** @return a specific user restriction that's in effect currently. */
1533 @Override
1534 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001535 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1536 return false;
1537 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001538 Bundle restrictions = getEffectiveUserRestrictions(userId);
1539 return restrictions != null && restrictions.getBoolean(restrictionKey);
1540 }
1541
Makoto Onukiacc50462018-02-14 14:13:49 -08001542 /** @return if any user has the given restriction. */
1543 @Override
1544 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1545 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1546 return false;
1547 }
1548 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1549 for (int i = 0; i < users.size(); i++) {
1550 final int userId = users.get(i).id;
1551 Bundle restrictions = getEffectiveUserRestrictions(userId);
1552 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1553 return true;
1554 }
1555 }
1556 return false;
1557 }
1558
Makoto Onuki068c54a2015-10-13 14:34:03 -07001559 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001560 * @hide
1561 *
1562 * Returns who set a user restriction on a user.
1563 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1564 * @param restrictionKey the string key representing the restriction
1565 * @param userId the id of the user for whom to retrieve the restrictions.
1566 * @return The source of user restriction. Any combination of
1567 * {@link UserManager#RESTRICTION_NOT_SET},
1568 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1569 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1570 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1571 */
1572 @Override
1573 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001574 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1575 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001576 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001577 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1578 result |= enforcingUsers.get(i).getUserRestrictionSource();
1579 }
1580 return result;
1581 }
1582
1583 @Override
1584 public List<EnforcingUser> getUserRestrictionSources(
1585 String restrictionKey, @UserIdInt int userId) {
1586 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001587
1588 // Shortcut for the most common case
1589 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001590 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001591 }
1592
Pavel Grafov6a40f092016-10-25 15:46:51 +01001593 final List<EnforcingUser> result = new ArrayList<>();
1594
1595 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001596 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001597 result.add(new EnforcingUser(
1598 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001599 }
1600
Pavel Grafov6a40f092016-10-25 15:46:51 +01001601 synchronized (mRestrictionsLock) {
1602 // Check if it is set by profile owner.
1603 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1604 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1605 result.add(getEnforcingUserLocked(userId));
1606 }
1607
1608 // Iterate over all users who enforce global restrictions.
1609 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1610 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1611 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1612 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1613 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001614 }
1615 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001616 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001617 return result;
1618 }
1619
Andreas Gampea36dc622018-02-05 17:19:22 -08001620 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001621 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1622 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1623 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1624 return new EnforcingUser(userId, source);
1625 }
1626
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001627 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001628 * @return UserRestrictions that are in effect currently. This always returns a new
1629 * {@link Bundle}.
1630 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001631 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001632 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001634 }
1635
1636 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001637 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1638 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001639 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1640 return false;
1641 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001642 synchronized (mRestrictionsLock) {
1643 Bundle bundle = mBaseUserRestrictions.get(userId);
1644 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1645 }
1646 }
1647
1648 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001649 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001650 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001651 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1652 return;
1653 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001654 synchronized (mRestrictionsLock) {
1655 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1656 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001657 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1658 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001659 newRestrictions.putBoolean(key, value);
1660
Fyodor Kupolov82402752015-10-28 14:54:51 -07001661 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001662 }
1663 }
1664
Makoto Onuki068c54a2015-10-13 14:34:03 -07001665 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001666 * Optionally updating user restrictions, calculate the effective user restrictions and also
1667 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001668 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001669 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001671 * @param userId target user ID.
1672 */
1673 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001674 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001675 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001676 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1677 mAppliedUserRestrictions.get(userId));
1678
1679 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001680 if (newBaseRestrictions != null) {
1681 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1683
Pavel Grafov6a40f092016-10-25 15:46:51 +01001684 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001685 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001686 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687
Pavel Grafov6a40f092016-10-25 15:46:51 +01001688 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001689 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001691 }
1692
Fyodor Kupolov82402752015-10-28 14:54:51 -07001693 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001694
Makoto Onuki759a7632015-10-28 16:43:10 -07001695 mCachedEffectiveUserRestrictions.put(userId, effective);
1696
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001697 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001698 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001699 debug("Applying user restrictions: userId=" + userId
1700 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001701 }
1702
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001703 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001704 mHandler.post(new Runnable() {
1705 @Override
1706 public void run() {
1707 try {
1708 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1709 } catch (RemoteException e) {
1710 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1711 }
1712 }
1713 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001714 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001715
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001717
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001718 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001719 }
1720
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001721 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001722 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1724 // actually, but we still need some kind of synchronization otherwise we might end up
1725 // calling listeners out-of-order, thus "LR".
1726
1727 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1728 return;
1729 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001730
1731 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1732 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1733
1734 mHandler.post(new Runnable() {
1735 @Override
1736 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001737 UserRestrictionsUtils.applyUserRestrictions(
1738 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739
Makoto Onukid45a4a22015-11-02 17:17:38 -08001740 final UserRestrictionsListener[] listeners;
1741 synchronized (mUserRestrictionsListeners) {
1742 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1743 mUserRestrictionsListeners.toArray(listeners);
1744 }
1745 for (int i = 0; i < listeners.length; i++) {
1746 listeners[i].onUserRestrictionsChanged(userId,
1747 newRestrictionsFinal, prevRestrictionsFinal);
1748 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001749
1750 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1751 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1752 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001753 }
1754 });
1755 }
1756
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001757 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001758 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001759 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001760 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001761 }
1762
1763 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001764 // Package private for the inner class.
1765 void applyUserRestrictionsForAllUsersLR() {
1766 if (DBG) {
1767 debug("applyUserRestrictionsForAllUsersLR");
1768 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001769 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001770 mCachedEffectiveUserRestrictions.clear();
1771
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001772 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001773 // it on a handler.
1774 final Runnable r = new Runnable() {
1775 @Override
1776 public void run() {
1777 // Then get the list of running users.
1778 final int[] runningUsers;
1779 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001780 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001781 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001782 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001783 return;
1784 }
1785 // Then re-calculate the effective restrictions and apply, only for running users.
1786 // It's okay if a new user has started after the getRunningUserIds() call,
1787 // because we'll do the same thing (re-calculate the restrictions and apply)
1788 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001789 synchronized (mRestrictionsLock) {
1790 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001791 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001792 }
1793 }
1794 }
1795 };
1796 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001797 }
1798
Amith Yamasani258848d2012-08-10 17:06:33 -07001799 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001800 * Check if we've hit the limit of how many users can be created.
1801 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001802 private boolean isUserLimitReached() {
1803 int count;
1804 synchronized (mUsersLock) {
1805 count = getAliveUsersExcludingGuestsCountLU();
1806 }
1807 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001808 }
1809
1810 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001811 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001812 checkManageUsersPermission("check if more managed profiles can be added.");
1813 if (ActivityManager.isLowRamDeviceStatic()) {
1814 return false;
1815 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001816 if (!mContext.getPackageManager().hasSystemFeature(
1817 PackageManager.FEATURE_MANAGED_USERS)) {
1818 return false;
1819 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001820 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001821 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001822 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001823 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001824 return false;
1825 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001826 synchronized(mUsersLock) {
1827 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001828 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001829 return false;
1830 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001831 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1832 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001833 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001834 return usersCountAfterRemoving == 1
1835 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001836 }
1837 }
1838
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001839 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001840 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001841 int aliveUserCount = 0;
1842 final int totalUserCount = mUsers.size();
1843 // Skip over users being removed
1844 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001845 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001846 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001847 aliveUserCount++;
1848 }
1849 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001850 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001851 }
1852
1853 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001854 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001855 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1856 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1857 * permissions can make certain calls to the UserManager.
1858 *
1859 * @param message used as message if SecurityException is thrown
1860 * @throws SecurityException if the caller does not have enough privilege.
1861 */
1862 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1863 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001864
1865 if (uid == Process.SYSTEM_UID || uid == 0) {
1866 // System UID or root's UID are granted privilege.
1867 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001868 }
jovanakf24ad492018-05-18 12:15:59 -07001869
1870 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1871 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1872 // Apps with both permissions are granted privilege.
1873 return;
1874 }
1875
1876 throw new SecurityException(
1877 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1878 }
1879
1880 private static boolean hasPermissionGranted(String permission, int uid) {
1881 return ActivityManager.checkComponentPermission(
1882 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1883 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001884 }
1885
1886 /**
1887 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001888 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001889 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001890 *
1891 * @param message used as message if SecurityException is thrown
1892 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001893 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001894 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001895 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001896 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001897 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1898 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001899 }
1900
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001901 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001902 * Enforces that only the system UID or root's UID or apps that have the
1903 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1904 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1905 * can make certain calls to the UserManager.
1906 *
1907 * @param message used as message if SecurityException is thrown
1908 * @throws SecurityException if the caller is not system or root
1909 * @see #hasManageOrCreateUsersPermission()
1910 */
1911 private static final void checkManageOrCreateUsersPermission(String message) {
1912 if (!hasManageOrCreateUsersPermission()) {
1913 throw new SecurityException(
1914 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1915 }
1916 }
1917
1918 /**
1919 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1920 * to create user/profiles other than what is allowed for
1921 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1922 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1923 */
1924 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1925 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1926 if (!hasManageOrCreateUsersPermission()) {
1927 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1928 + "permission to create an user with flags: " + creationFlags);
1929 }
1930 } else if (!hasManageUsersPermission()) {
1931 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1932 + " with flags: " + creationFlags);
1933 }
1934 }
1935
1936 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001937 * @return whether the calling UID is system UID or root's UID or the calling app has the
1938 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1939 */
1940 private static final boolean hasManageUsersPermission() {
1941 final int callingUid = Binder.getCallingUid();
1942 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1943 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001944 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001945 }
1946
1947 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001948 * @return whether the calling UID is system UID or root's UID or the calling app has the
1949 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1950 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1951 */
1952 private static final boolean hasManageOrCreateUsersPermission() {
1953 final int callingUid = Binder.getCallingUid();
1954 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1955 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001956 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
1957 || hasPermissionGranted(android.Manifest.permission.CREATE_USERS, callingUid);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001958 }
1959
1960 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001961 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1962 * UserManager.
1963 *
1964 * @param message used as message if SecurityException is thrown
1965 * @throws SecurityException if the caller is not system or root
1966 */
1967 private static void checkSystemOrRoot(String message) {
1968 final int uid = Binder.getCallingUid();
1969 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1970 throw new SecurityException("Only system may: " + message);
1971 }
1972 }
1973
Fyodor Kupolov82402752015-10-28 14:54:51 -07001974 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001975 try {
1976 File dir = new File(mUsersDir, Integer.toString(info.id));
1977 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001978 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001979 if (!dir.exists()) {
1980 dir.mkdir();
1981 FileUtils.setPermissions(
1982 dir.getPath(),
1983 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1984 -1, -1);
1985 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001986 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001987 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001988 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001989 info.iconPath = file.getAbsolutePath();
1990 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001991 try {
1992 os.close();
1993 } catch (IOException ioe) {
1994 // What the ... !
1995 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001996 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001997 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001998 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001999 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002000 }
2001
Amith Yamasani0b285492011-04-14 17:35:23 -07002002 /**
2003 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
2004 * cache it elsewhere.
2005 * @return the array of user ids.
2006 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07002007 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002008 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002009 return mUserIds;
2010 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002011 }
2012
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002013 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002014 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002015 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002016 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002017 return;
2018 }
2019 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002020 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002021 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002022 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002023 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002024 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002025 int type;
2026 while ((type = parser.next()) != XmlPullParser.START_TAG
2027 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002028 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002029 }
2030
2031 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002032 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002033 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002034 return;
2035 }
2036
Amith Yamasani2a003292012-08-14 18:25:45 -07002037 mNextSerialNumber = -1;
2038 if (parser.getName().equals(TAG_USERS)) {
2039 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2040 if (lastSerialNumber != null) {
2041 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2042 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002043 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2044 if (versionNumber != null) {
2045 mUserVersion = Integer.parseInt(versionNumber);
2046 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002047 }
2048
Pavel Grafov6a40f092016-10-25 15:46:51 +01002049 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2050 // currently), take care of it in case of upgrade.
2051 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002052
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002053 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302054 if (type == XmlPullParser.START_TAG) {
2055 final String name = parser.getName();
2056 if (name.equals(TAG_USER)) {
2057 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002058
Amith Yamasani12747872015-12-07 14:19:49 -08002059 UserData userData = readUserLP(Integer.parseInt(id));
2060
2061 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002062 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002063 mUsers.put(userData.info.id, userData);
2064 if (mNextSerialNumber < 0
2065 || mNextSerialNumber <= userData.info.id) {
2066 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002067 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302068 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002069 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302070 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002071 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2072 && type != XmlPullParser.END_TAG) {
2073 if (type == XmlPullParser.START_TAG) {
2074 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002075 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002076 UserRestrictionsUtils
2077 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002078 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002079 }
2080 break;
2081 }
2082 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002083 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2084 // Legacy name, should only be encountered when upgrading from pre-O.
2085 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002086 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2087 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002088 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002089 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002090 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2091 // Should only happen when upgrading from pre-O (version < 7).
2092 oldDevicePolicyGlobalUserRestrictions =
2093 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002094 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002095 }
2096 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002097
Fyodor Kupolov82402752015-10-28 14:54:51 -07002098 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002099 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002100 } catch (IOException | XmlPullParserException e) {
2101 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002102 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002103 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002104 }
2105 }
2106
Amith Yamasani6f34b412012-10-22 18:19:27 -07002107 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002108 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002109 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002110 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002111 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002112 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002113 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002114 int userVersion = mUserVersion;
2115 if (userVersion < 1) {
2116 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002117 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2118 if ("Primary".equals(userData.info.name)) {
2119 userData.info.name =
2120 mContext.getResources().getString(com.android.internal.R.string.owner_name);
2121 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002122 }
2123 userVersion = 1;
2124 }
2125
Amith Yamasanibc9625052012-11-15 14:39:18 -08002126 if (userVersion < 2) {
2127 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002128 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2129 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2130 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2131 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002132 }
2133 userVersion = 2;
2134 }
2135
Amith Yamasani350962c2013-08-06 11:18:53 -07002136
Amith Yamasani5e486f52013-08-07 11:06:44 -07002137 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002138 userVersion = 4;
2139 }
2140
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002141 if (userVersion < 5) {
2142 initDefaultGuestRestrictions();
2143 userVersion = 5;
2144 }
2145
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002146 if (userVersion < 6) {
2147 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002148 synchronized (mUsersLock) {
2149 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002150 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002151 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002152 if (!splitSystemUser && userData.info.isRestricted()
2153 && (userData.info.restrictedProfileParentId
2154 == UserInfo.NO_PROFILE_GROUP_ID)) {
2155 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2156 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002157 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002158 }
2159 }
2160 userVersion = 6;
2161 }
2162
Pavel Grafov6a40f092016-10-25 15:46:51 +01002163 if (userVersion < 7) {
2164 // Previously only one user could enforce global restrictions, now it is per-user.
2165 synchronized (mRestrictionsLock) {
2166 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2167 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2168 mDevicePolicyGlobalUserRestrictions.put(
2169 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2170 }
2171 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2172 // it from local to global bundle for all users who set it.
2173 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2174 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2175 );
2176 }
2177 userVersion = 7;
2178 }
2179
Amith Yamasani6f34b412012-10-22 18:19:27 -07002180 if (userVersion < USER_VERSION) {
2181 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2182 + USER_VERSION);
2183 } else {
2184 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002185
2186 if (originalVersion < mUserVersion) {
2187 writeUserListLP();
2188 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002189 }
2190 }
2191
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002192 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002193 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002194 int flags = UserInfo.FLAG_INITIALIZED;
2195 // In split system user mode, the admin and primary flags are assigned to the first human
2196 // user.
2197 if (!UserManager.isSplitSystemUser()) {
2198 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2199 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002200 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002201 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002202 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002203 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002204 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002205
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002206 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002207 try {
2208 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2209 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2210 for (String userRestriction : defaultFirstUserRestrictions) {
2211 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2212 restrictions.putBoolean(userRestriction, true);
2213 }
2214 }
2215 } catch (Resources.NotFoundException e) {
2216 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2217 }
2218
Pavel Grafov6a40f092016-10-25 15:46:51 +01002219 if (!restrictions.isEmpty()) {
2220 synchronized (mRestrictionsLock) {
2221 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2222 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002223 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002224
Fyodor Kupolov82402752015-10-28 14:54:51 -07002225 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002226 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002227
Amith Yamasani12747872015-12-07 14:19:49 -08002228 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002229 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002230 }
2231
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002232 private String getOwnerName() {
2233 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2234 }
2235
Amith Yamasani12747872015-12-07 14:19:49 -08002236 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002237 if (DBG) {
2238 debug("scheduleWriteUser");
2239 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002240 // No need to wrap it within a lock -- worst case, we'll just post the same message
2241 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002242 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2243 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002244 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2245 }
2246 }
2247
Amith Yamasani12747872015-12-07 14:19:49 -08002248 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002249 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002250 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002251 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002252 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002253 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002254 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002255 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002256 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002257 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002258 userFile.finishWrite(fos);
2259 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002260 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002261 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002262 }
2263 }
2264
2265 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002266 * Writes the user file in this format:
2267 *
2268 * <user flags="20039023" id="0">
2269 * <name>Primary</name>
2270 * </user>
2271 */
2272 @VisibleForTesting
2273 void writeUserLP(UserData userData, OutputStream os)
2274 throws IOException, XmlPullParserException {
2275 // XmlSerializer serializer = XmlUtils.serializerInstance();
2276 final XmlSerializer serializer = new FastXmlSerializer();
2277 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2278 serializer.startDocument(null, true);
2279 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2280
2281 final UserInfo userInfo = userData.info;
2282 serializer.startTag(null, TAG_USER);
2283 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2284 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2285 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2286 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2287 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2288 Long.toString(userInfo.lastLoggedInTime));
2289 if (userInfo.lastLoggedInFingerprint != null) {
2290 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2291 userInfo.lastLoggedInFingerprint);
2292 }
2293 if (userInfo.iconPath != null) {
2294 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2295 }
2296 if (userInfo.partial) {
2297 serializer.attribute(null, ATTR_PARTIAL, "true");
2298 }
2299 if (userInfo.guestToRemove) {
2300 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2301 }
2302 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2303 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2304 Integer.toString(userInfo.profileGroupId));
2305 }
2306 serializer.attribute(null, ATTR_PROFILE_BADGE,
2307 Integer.toString(userInfo.profileBadge));
2308 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2309 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2310 Integer.toString(userInfo.restrictedProfileParentId));
2311 }
2312 // Write seed data
2313 if (userData.persistSeedData) {
2314 if (userData.seedAccountName != null) {
2315 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2316 }
2317 if (userData.seedAccountType != null) {
2318 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2319 }
2320 }
2321 if (userInfo.name != null) {
2322 serializer.startTag(null, TAG_NAME);
2323 serializer.text(userInfo.name);
2324 serializer.endTag(null, TAG_NAME);
2325 }
2326 synchronized (mRestrictionsLock) {
2327 UserRestrictionsUtils.writeRestrictions(serializer,
2328 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2329 UserRestrictionsUtils.writeRestrictions(serializer,
2330 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2331 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002332 UserRestrictionsUtils.writeRestrictions(serializer,
2333 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2334 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002335 }
2336
2337 if (userData.account != null) {
2338 serializer.startTag(null, TAG_ACCOUNT);
2339 serializer.text(userData.account);
2340 serializer.endTag(null, TAG_ACCOUNT);
2341 }
2342
2343 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2344 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2345 userData.seedAccountOptions.saveToXml(serializer);
2346 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2347 }
2348
arangelov9b632d72018-12-07 23:21:22 +00002349 if (userData.getLastRequestQuietModeEnabledMillis() != 0L) {
2350 serializer.startTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2351 serializer.text(String.valueOf(userData.getLastRequestQuietModeEnabledMillis()));
2352 serializer.endTag(/* namespace */ null, TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL);
2353 }
2354
Kenny Guy02c89902016-11-15 19:36:38 +00002355 serializer.endTag(null, TAG_USER);
2356
2357 serializer.endDocument();
2358 }
2359
2360 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002361 * Writes the user list file in this format:
2362 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002363 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002364 * <user id="0"></user>
2365 * <user id="2"></user>
2366 * </users>
2367 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002368 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002369 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002370 if (DBG) {
2371 debug("writeUserList");
2372 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002373 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002374 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002375 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002376 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002377 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2378
2379 // XmlSerializer serializer = XmlUtils.serializerInstance();
2380 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002381 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002382 serializer.startDocument(null, true);
2383 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2384
2385 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002386 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002387 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002388
Adam Lesinskieddeb492014-09-08 17:50:03 -07002389 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002390 synchronized (mGuestRestrictions) {
2391 UserRestrictionsUtils
2392 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2393 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302394 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002395 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2396 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2397 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002398 int[] userIdsToWrite;
2399 synchronized (mUsersLock) {
2400 userIdsToWrite = new int[mUsers.size()];
2401 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002402 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002403 userIdsToWrite[i] = user.id;
2404 }
2405 }
2406 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002407 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002408 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002409 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002410 }
2411
2412 serializer.endTag(null, TAG_USERS);
2413
2414 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002415 userListFile.finishWrite(fos);
2416 } catch (Exception e) {
2417 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002418 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002419 }
2420 }
2421
Amith Yamasani12747872015-12-07 14:19:49 -08002422 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002423 FileInputStream fis = null;
2424 try {
2425 AtomicFile userFile =
2426 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2427 fis = userFile.openRead();
2428 return readUserLP(id, fis);
2429 } catch (IOException ioe) {
2430 Slog.e(LOG_TAG, "Error reading user list");
2431 } catch (XmlPullParserException pe) {
2432 Slog.e(LOG_TAG, "Error reading user list");
2433 } finally {
2434 IoUtils.closeQuietly(fis);
2435 }
2436 return null;
2437 }
2438
2439 @VisibleForTesting
2440 UserData readUserLP(int id, InputStream is) throws IOException,
2441 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002442 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002443 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002444 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002445 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002446 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002447 long creationTime = 0L;
2448 long lastLoggedInTime = 0L;
arangelov9b632d72018-12-07 23:21:22 +00002449 long lastRequestQuietModeEnabledTimestamp = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002450 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002451 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002452 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002453 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002454 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002455 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002456 boolean persistSeedData = false;
2457 String seedAccountName = null;
2458 String seedAccountType = null;
2459 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002460 Bundle baseRestrictions = null;
2461 Bundle localRestrictions = null;
2462 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002463
Kenny Guy02c89902016-11-15 19:36:38 +00002464 XmlPullParser parser = Xml.newPullParser();
2465 parser.setInput(is, StandardCharsets.UTF_8.name());
2466 int type;
2467 while ((type = parser.next()) != XmlPullParser.START_TAG
2468 && type != XmlPullParser.END_DOCUMENT) {
2469 // Skip
2470 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002471
Kenny Guy02c89902016-11-15 19:36:38 +00002472 if (type != XmlPullParser.START_TAG) {
2473 Slog.e(LOG_TAG, "Unable to read user " + id);
2474 return null;
2475 }
2476
2477 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2478 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2479 if (storedId != id) {
2480 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002481 return null;
2482 }
Kenny Guy02c89902016-11-15 19:36:38 +00002483 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2484 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2485 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2486 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2487 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2488 lastLoggedInFingerprint = parser.getAttributeValue(null,
2489 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2490 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2491 UserInfo.NO_PROFILE_GROUP_ID);
2492 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2493 restrictedProfileParentId = readIntAttribute(parser,
2494 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2495 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2496 if ("true".equals(valueString)) {
2497 partial = true;
2498 }
2499 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2500 if ("true".equals(valueString)) {
2501 guestToRemove = true;
2502 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002503
Kenny Guy02c89902016-11-15 19:36:38 +00002504 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2505 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2506 if (seedAccountName != null || seedAccountType != null) {
2507 persistSeedData = true;
2508 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002509
Kenny Guy02c89902016-11-15 19:36:38 +00002510 int outerDepth = parser.getDepth();
2511 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2512 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2513 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2514 continue;
2515 }
2516 String tag = parser.getName();
2517 if (TAG_NAME.equals(tag)) {
2518 type = parser.next();
2519 if (type == XmlPullParser.TEXT) {
2520 name = parser.getText();
2521 }
2522 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002523 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002524 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002525 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2526 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2527 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002528 } else if (TAG_ACCOUNT.equals(tag)) {
2529 type = parser.next();
2530 if (type == XmlPullParser.TEXT) {
2531 account = parser.getText();
2532 }
2533 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2534 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002535 persistSeedData = true;
arangelov9b632d72018-12-07 23:21:22 +00002536 } else if (TAG_LAST_REQUEST_QUIET_MODE_ENABLED_CALL.equals(tag)) {
2537 type = parser.next();
2538 if (type == XmlPullParser.TEXT) {
2539 lastRequestQuietModeEnabledTimestamp = Long.parseLong(parser.getText());
2540 }
Amith Yamasani12747872015-12-07 14:19:49 -08002541 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002542 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002543 }
Kenny Guy02c89902016-11-15 19:36:38 +00002544
2545 // Create the UserInfo object that gets passed around
2546 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2547 userInfo.serialNumber = serialNumber;
2548 userInfo.creationTime = creationTime;
2549 userInfo.lastLoggedInTime = lastLoggedInTime;
2550 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2551 userInfo.partial = partial;
2552 userInfo.guestToRemove = guestToRemove;
2553 userInfo.profileGroupId = profileGroupId;
2554 userInfo.profileBadge = profileBadge;
2555 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2556
2557 // Create the UserData object that's internal to this class
2558 UserData userData = new UserData();
2559 userData.info = userInfo;
2560 userData.account = account;
2561 userData.seedAccountName = seedAccountName;
2562 userData.seedAccountType = seedAccountType;
2563 userData.persistSeedData = persistSeedData;
2564 userData.seedAccountOptions = seedAccountOptions;
arangelov9b632d72018-12-07 23:21:22 +00002565 userData.setLastRequestQuietModeEnabledMillis(lastRequestQuietModeEnabledTimestamp);
Kenny Guy02c89902016-11-15 19:36:38 +00002566
2567 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002568 if (baseRestrictions != null) {
2569 mBaseUserRestrictions.put(id, baseRestrictions);
2570 }
2571 if (localRestrictions != null) {
2572 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2573 }
2574 if (globalRestrictions != null) {
2575 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2576 }
Kenny Guy02c89902016-11-15 19:36:38 +00002577 }
2578 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002579 }
2580
Amith Yamasani920ace02012-09-20 22:15:37 -07002581 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2582 String valueString = parser.getAttributeValue(null, attr);
2583 if (valueString == null) return defaultValue;
2584 try {
2585 return Integer.parseInt(valueString);
2586 } catch (NumberFormatException nfe) {
2587 return defaultValue;
2588 }
2589 }
2590
2591 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2592 String valueString = parser.getAttributeValue(null, attr);
2593 if (valueString == null) return defaultValue;
2594 try {
2595 return Long.parseLong(valueString);
2596 } catch (NumberFormatException nfe) {
2597 return defaultValue;
2598 }
2599 }
2600
Amith Yamasanib82add22013-07-09 11:24:44 -07002601 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002602 * Removes the app restrictions file for a specific package and user id, if it exists.
2603 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002604 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2605 File dir = Environment.getUserSystemDirectory(userId);
2606 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2607 if (resFile.exists()) {
2608 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002609 }
2610 }
2611
Kenny Guya52dc3e2014-02-11 15:33:14 +00002612 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002613 public UserInfo createProfileForUser(String name, int flags, int userId,
2614 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002615 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002616 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002617 }
2618
Amith Yamasani258848d2012-08-10 17:06:33 -07002619 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002620 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2621 String[] disallowedPackages) {
2622 checkManageOrCreateUsersPermission(flags);
2623 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2624 }
2625
2626 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002627 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2628 checkManageOrCreateUsersPermission("Only the system can remove users");
2629 return removeUserUnchecked(userHandle);
2630 }
2631
2632 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002633 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002634 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002635 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002636 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002637
Jessica Hummelbe81c802014-04-22 15:49:22 +01002638 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002639 return createUserInternal(name, flags, parentId, null);
2640 }
2641
2642 private UserInfo createUserInternal(String name, int flags, int parentId,
2643 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002644 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2645 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2646 : UserManager.DISALLOW_ADD_USER;
2647 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2648 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002649 return null;
2650 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002651 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2652 }
2653
2654 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2655 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002656 DeviceStorageMonitorInternal dsm = LocalServices
2657 .getService(DeviceStorageMonitorInternal.class);
2658 if (dsm.isMemoryLow()) {
2659 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2660 return null;
2661 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002662 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002663 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002664 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002665 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002666 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002667 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002668 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002669 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002670 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002671 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002672 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002673 if (parentId != UserHandle.USER_NULL) {
2674 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002675 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002676 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002677 if (parent == null) return null;
2678 }
2679 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2680 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2681 return null;
2682 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002683 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2684 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002685 // been reached, cannot add a user.
jovanaka6763a32018-12-03 17:23:20 -08002686 Log.e(LOG_TAG, "Cannot add user. Maximum user limit is reached.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002687 return null;
2688 }
2689 // If we're adding a guest and there already exists one, bail.
2690 if (isGuest && findCurrentGuestUser() != null) {
jovanaka6763a32018-12-03 17:23:20 -08002691 Log.e(LOG_TAG, "Cannot add guest user. Guest user already exists.");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002692 return null;
2693 }
2694 // In legacy mode, restricted profile's parent can only be the owner user
2695 if (isRestricted && !UserManager.isSplitSystemUser()
2696 && (parentId != UserHandle.USER_SYSTEM)) {
2697 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2698 return null;
2699 }
2700 if (isRestricted && UserManager.isSplitSystemUser()) {
2701 if (parent == null) {
2702 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2703 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002704 return null;
2705 }
Amith Yamasani12747872015-12-07 14:19:49 -08002706 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002707 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2708 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002709 return null;
2710 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002711 }
2712 // In split system user mode, we assign the first human user the primary flag.
2713 // And if there is no device owner, we also assign the admin flag to primary user.
2714 if (UserManager.isSplitSystemUser()
2715 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2716 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002717 synchronized (mUsersLock) {
2718 if (!mIsDeviceManaged) {
2719 flags |= UserInfo.FLAG_ADMIN;
2720 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002721 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002722 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002723
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002724 userId = getNextAvailableId();
2725 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002726 boolean ephemeralGuests = Resources.getSystem()
2727 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002728
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002729 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002730 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2731 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2732 || (parent != null && parent.info.isEphemeral())) {
2733 flags |= UserInfo.FLAG_EPHEMERAL;
2734 }
2735
2736 userInfo = new UserInfo(userId, name, null, flags);
2737 userInfo.serialNumber = mNextSerialNumber++;
2738 long now = System.currentTimeMillis();
2739 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2740 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002741 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002742 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2743 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2744 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002745 userData = new UserData();
2746 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002747 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002748 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002749 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002750 writeUserListLP();
2751 if (parent != null) {
2752 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002753 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2754 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002755 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002756 }
Amith Yamasani12747872015-12-07 14:19:49 -08002757 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002758 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002759 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2760 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002761 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002762 }
Amith Yamasani12747872015-12-07 14:19:49 -08002763 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002764 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002765 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002766 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002767 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002768 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002769 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002770 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002771 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002772 userInfo.partial = false;
2773 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002774 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002775 }
2776 updateUserIds();
2777 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002778 if (isGuest) {
2779 synchronized (mGuestRestrictions) {
2780 restrictions.putAll(mGuestRestrictions);
2781 }
2782 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002783 synchronized (mRestrictionsLock) {
2784 mBaseUserRestrictions.append(userId, restrictions);
2785 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002786 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002787 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2788 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2789 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2790 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002791 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2792 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002793 } finally {
2794 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002795 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002796 return userInfo;
2797 }
2798
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002799 @VisibleForTesting
2800 UserData putUserInfo(UserInfo userInfo) {
2801 final UserData userData = new UserData();
2802 userData.info = userInfo;
2803 synchronized (mUsers) {
2804 mUsers.put(userInfo.id, userData);
2805 }
2806 return userData;
2807 }
2808
2809 @VisibleForTesting
2810 void removeUserInfo(int userId) {
2811 synchronized (mUsers) {
2812 mUsers.remove(userId);
2813 }
2814 }
2815
Amith Yamasani0b285492011-04-14 17:35:23 -07002816 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002817 * @hide
2818 */
Amith Yamasani12747872015-12-07 14:19:49 -08002819 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002820 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002821 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002822 final UserInfo user = createProfileForUser(
2823 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002824 if (user == null) {
2825 return null;
2826 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002827 long identity = Binder.clearCallingIdentity();
2828 try {
2829 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2830 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2831 // the putIntForUser() will fail.
2832 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2833 android.provider.Settings.Secure.LOCATION_MODE,
2834 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2835 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2836 } finally {
2837 Binder.restoreCallingIdentity(identity);
2838 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002839 return user;
2840 }
2841
2842 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002843 * Find the current guest user. If the Guest user is partial,
2844 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002845 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002846 private UserInfo findCurrentGuestUser() {
2847 synchronized (mUsersLock) {
2848 final int size = mUsers.size();
2849 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002850 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002851 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2852 return user;
2853 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002854 }
2855 }
2856 return null;
2857 }
2858
2859 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002860 * Mark this guest user for deletion to allow us to create another guest
2861 * and switch to that user before actually removing this guest.
2862 * @param userHandle the userid of the current guest
2863 * @return whether the user could be marked for deletion
2864 */
Amith Yamasani12747872015-12-07 14:19:49 -08002865 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002866 public boolean markGuestForDeletion(int userHandle) {
2867 checkManageUsersPermission("Only the system can remove users");
2868 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2869 UserManager.DISALLOW_REMOVE_USER, false)) {
2870 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2871 return false;
2872 }
2873
2874 long ident = Binder.clearCallingIdentity();
2875 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002876 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002877 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002878 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002879 userData = mUsers.get(userHandle);
2880 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002881 return false;
2882 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002883 }
Amith Yamasani12747872015-12-07 14:19:49 -08002884 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002885 return false;
2886 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002887 // We set this to a guest user that is to be removed. This is a temporary state
2888 // where we are allowed to add new Guest users, even if this one is still not
2889 // removed. This user will still show up in getUserInfo() calls.
2890 // If we don't get around to removing this Guest user, it will be purged on next
2891 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002892 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002893 // Mark it as disabled, so that it isn't returned any more when
2894 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002895 userData.info.flags |= UserInfo.FLAG_DISABLED;
2896 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002897 }
2898 } finally {
2899 Binder.restoreCallingIdentity(ident);
2900 }
2901 return true;
2902 }
2903
2904 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002905 * Removes a user and all data directories created for that user. This method should be called
2906 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002907 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002908 */
Amith Yamasani12747872015-12-07 14:19:49 -08002909 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002910 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002911 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002912 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002913
2914 final boolean isManagedProfile;
2915 synchronized (mUsersLock) {
2916 UserInfo userInfo = getUserInfoLU(userHandle);
2917 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2918 }
2919 String restriction = isManagedProfile
2920 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2921 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2922 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002923 return false;
2924 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002925 return removeUserUnchecked(userHandle);
2926 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002927
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002928 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002929 long ident = Binder.clearCallingIdentity();
2930 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002931 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002932 int currentUser = ActivityManager.getCurrentUser();
2933 if (currentUser == userHandle) {
jovanaka6763a32018-12-03 17:23:20 -08002934 Log.w(LOG_TAG, "Current user cannot be removed.");
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002935 return false;
2936 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002937 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002938 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002939 userData = mUsers.get(userHandle);
jovanaka6763a32018-12-03 17:23:20 -08002940 if (userHandle == UserHandle.USER_SYSTEM) {
2941 Log.e(LOG_TAG, "System user cannot be removed.");
2942 return false;
2943 }
2944
2945 if (userData == null) {
2946 Log.e(LOG_TAG, String.format(
2947 "Cannot remove user %d, invalid user id provided.", userHandle));
2948 return false;
2949 }
2950
2951 if (mRemovingUserIds.get(userHandle)) {
2952 Log.e(LOG_TAG, String.format(
2953 "User %d is already scheduled for removal.", userHandle));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002954 return false;
2955 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002956
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002957 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002958 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002959
Kenny Guyee58b4f2014-05-23 15:19:53 +01002960 // Set this to a partially created user, so that the user will be purged
2961 // on next startup, in case the runtime stops now before stopping and
2962 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002963 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002964 // Mark it as disabled, so that it isn't returned any more when
2965 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002966 userData.info.flags |= UserInfo.FLAG_DISABLED;
2967 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002968 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002969 try {
2970 mAppOpsService.removeUser(userHandle);
2971 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08002972 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user.", e);
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002973 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002974
Amith Yamasani12747872015-12-07 14:19:49 -08002975 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2976 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002977 // Send broadcast to notify system that the user removed was a
2978 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002979 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002980 }
2981
2982 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2983 int res;
2984 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002985 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002986 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002987 @Override
2988 public void userStopped(int userId) {
2989 finishRemoveUser(userId);
2990 }
2991 @Override
2992 public void userStopAborted(int userId) {
2993 }
2994 });
2995 } catch (RemoteException e) {
jovanaka6763a32018-12-03 17:23:20 -08002996 Log.w(LOG_TAG, "Failed to stop user during removal.", e);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002997 return false;
2998 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002999 return res == ActivityManager.USER_OP_SUCCESS;
3000 } finally {
3001 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003002 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003003 }
3004
Andreas Gampea36dc622018-02-05 17:19:22 -08003005 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003006 @VisibleForTesting
3007 void addRemovingUserIdLocked(int userId) {
3008 // We remember deleted user IDs to prevent them from being
3009 // reused during the current boot; they can still be reused
3010 // after a reboot or recycling of userIds.
3011 mRemovingUserIds.put(userId, true);
3012 mRecentlyRemovedIds.add(userId);
3013 // Keep LRU queue of recently removed IDs for recycling
3014 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
3015 mRecentlyRemovedIds.removeFirst();
3016 }
3017 }
3018
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003019 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07003020 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003021 // Let other services shutdown any activity and clean up their state before completely
3022 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003023 long ident = Binder.clearCallingIdentity();
3024 try {
3025 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
3026 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003027 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
3028 android.Manifest.permission.MANAGE_USERS,
3029
3030 new BroadcastReceiver() {
3031 @Override
3032 public void onReceive(Context context, Intent intent) {
3033 if (DBG) {
3034 Slog.i(LOG_TAG,
3035 "USER_REMOVED broadcast sent, cleaning up user data "
3036 + userHandle);
3037 }
3038 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08003039 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003040 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003041 // Clean up any ActivityTaskManager state
3042 LocalServices.getService(ActivityTaskManagerInternal.class)
3043 .onUserStopped(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003044 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07003045 }
3046 }.start();
3047 }
3048 },
3049
3050 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003051 } finally {
3052 Binder.restoreCallingIdentity(ident);
3053 }
Amith Yamasani2a003292012-08-14 18:25:45 -07003054 }
3055
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003056 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07003057 try {
3058 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
3059 } catch (IllegalStateException e) {
3060 // This may be simply because the user was partially created.
3061 Slog.i(LOG_TAG,
3062 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
3063 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003064
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003065 // Cleanup gatekeeper secure user id
3066 try {
3067 final IGateKeeperService gk = GateKeeper.getService();
3068 if (gk != null) {
3069 gk.clearSecureUserId(userHandle);
3070 }
3071 } catch (Exception ex) {
3072 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3073 }
3074
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003075 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003076 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003077
3078 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003079 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003080 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3081
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003082 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003083 synchronized (mUsersLock) {
3084 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003085 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003086 }
3087 synchronized (mUserStates) {
3088 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003089 }
3090 synchronized (mRestrictionsLock) {
3091 mBaseUserRestrictions.remove(userHandle);
3092 mAppliedUserRestrictions.remove(userHandle);
3093 mCachedEffectiveUserRestrictions.remove(userHandle);
3094 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003095 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3096 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3097 applyUserRestrictionsForAllUsersLR();
3098 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003099 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003100 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003101 synchronized (mPackagesLock) {
3102 writeUserListLP();
3103 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003104 // Remove user file
3105 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3106 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003107 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003108 if (RELEASE_DELETED_USER_ID) {
3109 synchronized (mUsers) {
3110 mRemovingUserIds.delete(userHandle);
3111 }
3112 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003113 }
3114
Kenny Guyf8d3a232014-05-15 16:09:52 +01003115 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003116 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003117 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3118 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003119 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003120 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003121 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003122 }
3123
Amith Yamasani2a003292012-08-14 18:25:45 -07003124 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003125 public Bundle getApplicationRestrictions(String packageName) {
3126 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3127 }
3128
3129 @Override
3130 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003131 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003132 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003133 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003134 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003135 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003136 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003137 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003138 }
3139 }
3140
3141 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003142 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003143 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003144 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003145 if (restrictions != null) {
3146 restrictions.setDefusable(true);
3147 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003148 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003149 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003150 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003151 } else {
3152 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003153 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003154 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003155 }
Robin Lee66e5d962014-04-09 16:44:21 +01003156
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003157 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3158 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3159 changeIntent.setPackage(packageName);
3160 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3161 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003162 }
3163
3164 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003165 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003166 try {
3167 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003168 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003169 } catch (NameNotFoundException nnfe) {
3170 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003171 } finally {
3172 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003173 }
3174 }
3175
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003176 @GuardedBy("mAppRestrictionsLock")
3177 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003178 AtomicFile restrictionsFile =
3179 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3180 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003181 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003182 }
3183
3184 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003185 @GuardedBy("mAppRestrictionsLock")
3186 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003187 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003188 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003189 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003190 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003191 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003192
3193 FileInputStream fis = null;
3194 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003195 fis = restrictionsFile.openRead();
3196 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003197 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003198 XmlUtils.nextElement(parser);
3199 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003200 Slog.e(LOG_TAG, "Unable to read restrictions file "
3201 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003202 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003203 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003204 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3205 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003206 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003207 } catch (IOException|XmlPullParserException e) {
3208 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003209 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003210 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003211 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003212 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003213 }
3214
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003215 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3216 XmlPullParser parser) throws XmlPullParserException, IOException {
3217 int type = parser.getEventType();
3218 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3219 String key = parser.getAttributeValue(null, ATTR_KEY);
3220 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3221 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3222 if (multiple != null) {
3223 values.clear();
3224 int count = Integer.parseInt(multiple);
3225 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3226 if (type == XmlPullParser.START_TAG
3227 && parser.getName().equals(TAG_VALUE)) {
3228 values.add(parser.nextText().trim());
3229 count--;
3230 }
3231 }
3232 String [] valueStrings = new String[values.size()];
3233 values.toArray(valueStrings);
3234 restrictions.putStringArray(key, valueStrings);
3235 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3236 restrictions.putBundle(key, readBundleEntry(parser, values));
3237 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3238 final int outerDepth = parser.getDepth();
3239 ArrayList<Bundle> bundleList = new ArrayList<>();
3240 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3241 Bundle childBundle = readBundleEntry(parser, values);
3242 bundleList.add(childBundle);
3243 }
3244 restrictions.putParcelableArray(key,
3245 bundleList.toArray(new Bundle[bundleList.size()]));
3246 } else {
3247 String value = parser.nextText().trim();
3248 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3249 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3250 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3251 restrictions.putInt(key, Integer.parseInt(value));
3252 } else {
3253 restrictions.putString(key, value);
3254 }
3255 }
3256 }
3257 }
3258
3259 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3260 throws IOException, XmlPullParserException {
3261 Bundle childBundle = new Bundle();
3262 final int outerDepth = parser.getDepth();
3263 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3264 readEntry(childBundle, values, parser);
3265 }
3266 return childBundle;
3267 }
3268
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003269 @GuardedBy("mAppRestrictionsLock")
3270 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003271 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003272 AtomicFile restrictionsFile = new AtomicFile(
3273 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003274 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003275 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003276 }
3277
3278 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003279 @GuardedBy("mAppRestrictionsLock")
3280 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003281 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003282 try {
3283 fos = restrictionsFile.startWrite();
3284 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3285
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003286 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003287 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003288 serializer.startDocument(null, true);
3289 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3290
3291 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003292 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003293 serializer.endTag(null, TAG_RESTRICTIONS);
3294
3295 serializer.endDocument();
3296 restrictionsFile.finishWrite(fos);
3297 } catch (Exception e) {
3298 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003299 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3300 }
3301 }
3302
3303 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3304 throws IOException {
3305 for (String key : restrictions.keySet()) {
3306 Object value = restrictions.get(key);
3307 serializer.startTag(null, TAG_ENTRY);
3308 serializer.attribute(null, ATTR_KEY, key);
3309
3310 if (value instanceof Boolean) {
3311 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3312 serializer.text(value.toString());
3313 } else if (value instanceof Integer) {
3314 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3315 serializer.text(value.toString());
3316 } else if (value == null || value instanceof String) {
3317 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3318 serializer.text(value != null ? (String) value : "");
3319 } else if (value instanceof Bundle) {
3320 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3321 writeBundle((Bundle) value, serializer);
3322 } else if (value instanceof Parcelable[]) {
3323 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3324 Parcelable[] array = (Parcelable[]) value;
3325 for (Parcelable parcelable : array) {
3326 if (!(parcelable instanceof Bundle)) {
3327 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3328 }
3329 serializer.startTag(null, TAG_ENTRY);
3330 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3331 writeBundle((Bundle) parcelable, serializer);
3332 serializer.endTag(null, TAG_ENTRY);
3333 }
3334 } else {
3335 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3336 String[] values = (String[]) value;
3337 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3338 for (String choice : values) {
3339 serializer.startTag(null, TAG_VALUE);
3340 serializer.text(choice != null ? choice : "");
3341 serializer.endTag(null, TAG_VALUE);
3342 }
3343 }
3344 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003345 }
3346 }
3347
3348 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003349 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003350 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003351 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003352 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003353 }
3354 }
3355
3356 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003357 public boolean isUserNameSet(int userHandle) {
3358 synchronized (mUsersLock) {
3359 UserInfo userInfo = getUserInfoLU(userHandle);
3360 return userInfo != null && userInfo.name != null;
3361 }
3362 }
3363
3364 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003365 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003366 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003367 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003368 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003369 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003370 }
3371 // Not found
3372 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003373 }
3374 }
3375
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003376 @Override
3377 public long getUserCreationTime(int userHandle) {
3378 int callingUserId = UserHandle.getCallingUserId();
3379 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003380 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003381 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003382 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003383 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003384 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003385 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003386 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003387 }
3388 }
3389 }
3390 if (userInfo == null) {
3391 throw new SecurityException("userHandle can only be the calling user or a managed "
3392 + "profile associated with this user");
3393 }
3394 return userInfo.creationTime;
3395 }
3396
Amith Yamasani0b285492011-04-14 17:35:23 -07003397 /**
3398 * Caches the list of user ids in an array, adjusting the array size when necessary.
3399 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003400 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003401 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003402 synchronized (mUsersLock) {
3403 final int userSize = mUsers.size();
3404 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003405 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003406 num++;
3407 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003408 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003409 final int[] newUsers = new int[num];
3410 int n = 0;
3411 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003412 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003413 newUsers[n++] = mUsers.keyAt(i);
3414 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003415 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003416 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003417 }
3418 }
3419
3420 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003421 * Called right before a user is started. This gives us a chance to prepare
3422 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003423 */
3424 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003425 UserInfo userInfo = getUserInfo(userId);
3426 if (userInfo == null) {
3427 return;
3428 }
3429 final int userSerial = userInfo.serialNumber;
3430 // Migrate only if build fingerprints mismatch
3431 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003432 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003433 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003434
3435 if (userId != UserHandle.USER_SYSTEM) {
3436 synchronized (mRestrictionsLock) {
3437 applyUserRestrictionsLR(userId);
3438 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003439 }
3440 }
3441
3442 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003443 * Called right before a user is unlocked. This gives us a chance to prepare
3444 * app storage.
3445 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003446 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003447 UserInfo userInfo = getUserInfo(userId);
3448 if (userInfo == null) {
3449 return;
3450 }
3451 final int userSerial = userInfo.serialNumber;
3452 // Migrate only if build fingerprints mismatch
3453 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003454 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003455 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003456 }
3457
3458 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003459 * Examine all users present on given mounted volume, and destroy data
3460 * belonging to users that are no longer valid, or whose user ID has been
3461 * recycled.
3462 */
3463 void reconcileUsers(String volumeUuid) {
3464 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3465 }
3466
3467 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003468 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003469 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003470 * @param userId the user that was just foregrounded
3471 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003472 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003473 UserData userData = getUserDataNoChecks(userId);
3474 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003475 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3476 return;
3477 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003478
3479 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003480 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003481 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003482 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003483 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3484 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003485 }
3486
3487 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003488 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003489 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003490 @VisibleForTesting
3491 int getNextAvailableId() {
3492 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003493 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003494 nextId = scanNextAvailableIdLocked();
3495 if (nextId >= 0) {
3496 return nextId;
3497 }
3498 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3499 // except most recently removed
3500 if (mRemovingUserIds.size() > 0) {
3501 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3502 mRemovingUserIds.clear();
3503 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3504 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003505 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003506 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003507 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003508 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003509 if (nextId < 0) {
3510 throw new IllegalStateException("No user id available!");
3511 }
3512 return nextId;
3513 }
3514
Andreas Gampea36dc622018-02-05 17:19:22 -08003515 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003516 private int scanNextAvailableIdLocked() {
3517 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3518 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3519 return i;
3520 }
3521 }
3522 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003523 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003524
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003525 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003526 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3527 }
3528
Amith Yamasani920ace02012-09-20 22:15:37 -07003529 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003530 public void setSeedAccountData(int userId, String accountName, String accountType,
3531 PersistableBundle accountOptions, boolean persist) {
3532 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3533 synchronized (mPackagesLock) {
3534 final UserData userData;
3535 synchronized (mUsersLock) {
3536 userData = getUserDataLU(userId);
3537 if (userData == null) {
3538 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3539 return;
3540 }
3541 userData.seedAccountName = accountName;
3542 userData.seedAccountType = accountType;
3543 userData.seedAccountOptions = accountOptions;
3544 userData.persistSeedData = persist;
3545 }
3546 if (persist) {
3547 writeUserLP(userData);
3548 }
3549 }
3550 }
3551
3552 @Override
3553 public String getSeedAccountName() throws RemoteException {
3554 checkManageUsersPermission("Cannot get seed account information");
3555 synchronized (mUsersLock) {
3556 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3557 return userData.seedAccountName;
3558 }
3559 }
3560
3561 @Override
3562 public String getSeedAccountType() throws RemoteException {
3563 checkManageUsersPermission("Cannot get seed account information");
3564 synchronized (mUsersLock) {
3565 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3566 return userData.seedAccountType;
3567 }
3568 }
3569
3570 @Override
3571 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3572 checkManageUsersPermission("Cannot get seed account information");
3573 synchronized (mUsersLock) {
3574 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3575 return userData.seedAccountOptions;
3576 }
3577 }
3578
3579 @Override
3580 public void clearSeedAccountData() throws RemoteException {
3581 checkManageUsersPermission("Cannot clear seed account information");
3582 synchronized (mPackagesLock) {
3583 UserData userData;
3584 synchronized (mUsersLock) {
3585 userData = getUserDataLU(UserHandle.getCallingUserId());
3586 if (userData == null) return;
3587 userData.clearSeedAccountData();
3588 }
3589 writeUserLP(userData);
3590 }
3591 }
3592
3593 @Override
3594 public boolean someUserHasSeedAccount(String accountName, String accountType)
3595 throws RemoteException {
3596 checkManageUsersPermission("Cannot check seed account information");
3597 synchronized (mUsersLock) {
3598 final int userSize = mUsers.size();
3599 for (int i = 0; i < userSize; i++) {
3600 final UserData data = mUsers.valueAt(i);
3601 if (data.info.isInitialized()) continue;
3602 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3603 continue;
3604 }
3605 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3606 continue;
3607 }
3608 return true;
3609 }
3610 }
3611 return false;
3612 }
3613
3614 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003615 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003616 FileDescriptor err, String[] args, ShellCallback callback,
3617 ResultReceiver resultReceiver) {
3618 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003619 }
3620
3621 int onShellCommand(Shell shell, String cmd) {
3622 if (cmd == null) {
3623 return shell.handleDefaultCommands(cmd);
3624 }
3625
3626 final PrintWriter pw = shell.getOutPrintWriter();
3627 try {
3628 switch(cmd) {
3629 case "list":
3630 return runList(pw);
Hui Yu8ba65972018-04-16 18:45:48 -07003631 default:
3632 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003633 }
3634 } catch (RemoteException e) {
3635 pw.println("Remote exception: " + e);
3636 }
3637 return -1;
3638 }
3639
3640 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003641 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003642 final List<UserInfo> users = getUsers(false);
3643 if (users == null) {
3644 pw.println("Error: couldn't get users");
3645 return 1;
3646 } else {
3647 pw.println("Users:");
3648 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003649 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003650 pw.println("\t" + users.get(i).toString() + running);
3651 }
3652 return 0;
3653 }
3654 }
3655
3656 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003657 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003658 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003659
3660 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003661 final long nowRealtime = SystemClock.elapsedRealtime();
Amith Yamasani920ace02012-09-20 22:15:37 -07003662 StringBuilder sb = new StringBuilder();
3663 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003664 synchronized (mUsersLock) {
3665 pw.println("Users:");
3666 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003667 UserData userData = mUsers.valueAt(i);
3668 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003669 continue;
3670 }
Amith Yamasani12747872015-12-07 14:19:49 -08003671 UserInfo userInfo = userData.info;
3672 final int userId = userInfo.id;
3673 pw.print(" "); pw.print(userInfo);
3674 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003675 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003676 pw.print(" <removing> ");
3677 }
Amith Yamasani12747872015-12-07 14:19:49 -08003678 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003679 pw.print(" <partial>");
3680 }
3681 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003682 pw.print(" State: ");
3683 final int state;
3684 synchronized (mUserStates) {
3685 state = mUserStates.get(userId, -1);
3686 }
3687 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003688 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003689 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3690
Fyodor Kupolov82402752015-10-28 14:54:51 -07003691 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003692 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3693
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003694 pw.print(" Last logged in fingerprint: ");
3695 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003696
3697 pw.print(" Start time: ");
3698 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3699
3700 pw.print(" Unlock time: ");
3701 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3702
Makoto Onukie7927da2015-11-25 10:05:17 -08003703 pw.print(" Has profile owner: ");
3704 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003705 pw.println(" Restrictions:");
3706 synchronized (mRestrictionsLock) {
3707 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003708 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003709 pw.println(" Device policy global restrictions:");
3710 UserRestrictionsUtils.dumpRestrictions(
3711 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003712 pw.println(" Device policy local restrictions:");
3713 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003714 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003715 pw.println(" Effective restrictions:");
3716 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003717 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003718 }
Amith Yamasani12747872015-12-07 14:19:49 -08003719
3720 if (userData.account != null) {
3721 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003722 pw.println();
3723 }
Amith Yamasani12747872015-12-07 14:19:49 -08003724
3725 if (userData.seedAccountName != null) {
3726 pw.print(" Seed account name: " + userData.seedAccountName);
3727 pw.println();
3728 if (userData.seedAccountType != null) {
3729 pw.print(" account type: " + userData.seedAccountType);
3730 pw.println();
3731 }
3732 if (userData.seedAccountOptions != null) {
3733 pw.print(" account options exist");
3734 pw.println();
3735 }
3736 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003737 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003738 }
Amith Yamasani12747872015-12-07 14:19:49 -08003739 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003740 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003741 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003742 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003743 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003744 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003745 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003746 synchronized (mUsersLock) {
3747 pw.println();
3748 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003749 if (mRemovingUserIds.size() > 0) {
3750 pw.println();
3751 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3752 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003753 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003754 synchronized (mUserStates) {
3755 pw.println(" Started users state: " + mUserStates);
3756 }
Amith Yamasani12747872015-12-07 14:19:49 -08003757 // Dump some capabilities
3758 pw.println();
3759 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3760 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003761 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3762 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003763 }
3764 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003765
Makoto Onuki73dded22017-12-20 13:14:48 +09003766 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3767 if (time == 0) {
3768 pw.println("<unknown>");
3769 } else {
3770 sb.setLength(0);
3771 TimeUtils.formatDuration(nowTime - time, sb);
3772 sb.append(" ago");
3773 pw.println(sb);
3774 }
3775 }
3776
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003777 final class MainHandler extends Handler {
3778
3779 @Override
3780 public void handleMessage(Message msg) {
3781 switch (msg.what) {
3782 case WRITE_USER_MSG:
3783 removeMessages(WRITE_USER_MSG, msg.obj);
3784 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003785 int userId = ((UserData) msg.obj).info.id;
3786 UserData userData = getUserDataNoChecks(userId);
3787 if (userData != null) {
3788 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003789 }
3790 }
3791 }
3792 }
3793 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003794
3795 /**
3796 * @param userId
3797 * @return whether the user has been initialized yet
3798 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003799 boolean isUserInitialized(int userId) {
3800 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003801 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003802
3803 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003804 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003805 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3806 boolean isDeviceOwner, int cameraRestrictionScope) {
3807 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3808 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003809 }
3810
3811 @Override
3812 public Bundle getBaseUserRestrictions(int userId) {
3813 synchronized (mRestrictionsLock) {
3814 return mBaseUserRestrictions.get(userId);
3815 }
3816 }
3817
3818 @Override
3819 public void setBaseUserRestrictionsByDpmsForMigration(
3820 int userId, Bundle baseRestrictions) {
3821 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003822 if (updateRestrictionsIfNeededLR(
3823 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3824 invalidateEffectiveUserRestrictionsLR(userId);
3825 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003826 }
3827
Amith Yamasani12747872015-12-07 14:19:49 -08003828 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003829 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003830 if (userData != null) {
3831 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003832 } else {
3833 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3834 }
3835 }
3836 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003837
3838 @Override
3839 public boolean getUserRestriction(int userId, String key) {
3840 return getUserRestrictions(userId).getBoolean(key);
3841 }
3842
3843 @Override
3844 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3845 synchronized (mUserRestrictionsListeners) {
3846 mUserRestrictionsListeners.add(listener);
3847 }
3848 }
3849
3850 @Override
3851 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3852 synchronized (mUserRestrictionsListeners) {
3853 mUserRestrictionsListeners.remove(listener);
3854 }
3855 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003856
3857 @Override
3858 public void setDeviceManaged(boolean isManaged) {
3859 synchronized (mUsersLock) {
3860 mIsDeviceManaged = isManaged;
3861 }
3862 }
3863
3864 @Override
3865 public void setUserManaged(int userId, boolean isManaged) {
3866 synchronized (mUsersLock) {
3867 mIsUserManaged.put(userId, isManaged);
3868 }
3869 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003870
3871 @Override
3872 public void setUserIcon(int userId, Bitmap bitmap) {
3873 long ident = Binder.clearCallingIdentity();
3874 try {
3875 synchronized (mPackagesLock) {
3876 UserData userData = getUserDataNoChecks(userId);
3877 if (userData == null || userData.info.partial) {
3878 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3879 return;
3880 }
3881 writeBitmapLP(userData.info, bitmap);
3882 writeUserLP(userData);
3883 }
3884 sendUserInfoChangedBroadcast(userId);
3885 } finally {
3886 Binder.restoreCallingIdentity(ident);
3887 }
3888 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003889
3890 @Override
3891 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3892 synchronized (mUsersLock) {
3893 mForceEphemeralUsers = forceEphemeralUsers;
3894 }
3895 }
3896
3897 @Override
3898 public void removeAllUsers() {
3899 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3900 // Remove the non-system users straight away.
3901 removeNonSystemUsers();
3902 } else {
3903 // Switch to the system user first and then remove the other users.
3904 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3905 @Override
3906 public void onReceive(Context context, Intent intent) {
3907 int userId =
3908 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3909 if (userId != UserHandle.USER_SYSTEM) {
3910 return;
3911 }
3912 mContext.unregisterReceiver(this);
3913 removeNonSystemUsers();
3914 }
3915 };
3916 IntentFilter userSwitchedFilter = new IntentFilter();
3917 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3918 mContext.registerReceiver(
3919 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3920
3921 // Switch to the system user.
3922 ActivityManager am =
3923 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3924 am.switchUser(UserHandle.USER_SYSTEM);
3925 }
3926 }
phweisse9c44062016-02-10 12:57:38 +01003927
3928 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003929 public void onEphemeralUserStop(int userId) {
3930 synchronized (mUsersLock) {
3931 UserInfo userInfo = getUserInfoLU(userId);
3932 if (userInfo != null && userInfo.isEphemeral()) {
3933 // Do not allow switching back to the ephemeral user again as the user is going
3934 // to be deleted.
3935 userInfo.flags |= UserInfo.FLAG_DISABLED;
3936 if (userInfo.isGuest()) {
3937 // Indicate that the guest will be deleted after it stops.
3938 userInfo.guestToRemove = true;
3939 }
3940 }
3941 }
3942 }
3943
3944 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003945 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3946 String[] disallowedPackages) {
3947 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3948 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003949 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003950 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003951 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3952 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3953 }
3954 return user;
3955 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003956
3957 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003958 public boolean removeUserEvenWhenDisallowed(int userId) {
3959 return removeUserUnchecked(userId);
3960 }
3961
3962 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003963 public boolean isUserRunning(int userId) {
3964 synchronized (mUserStates) {
3965 return mUserStates.get(userId, -1) >= 0;
3966 }
3967 }
3968
3969 @Override
3970 public void setUserState(int userId, int userState) {
3971 synchronized (mUserStates) {
3972 mUserStates.put(userId, userState);
3973 }
3974 }
3975
3976 @Override
3977 public void removeUserState(int userId) {
3978 synchronized (mUserStates) {
3979 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003980 }
3981 }
3982
3983 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003984 public int[] getUserIds() {
3985 return UserManagerService.this.getUserIds();
3986 }
3987
3988 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003989 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003990 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003991 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003992 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003993 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003994 // Special case, in the stopping/shutdown state user key can still be unlocked
3995 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3996 return StorageManager.isUserKeyUnlocked(userId);
3997 }
3998 return (state == UserState.STATE_RUNNING_UNLOCKING)
3999 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07004000 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004001
4002 @Override
4003 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004004 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004005 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004006 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004007 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07004008 // Special case, in the stopping/shutdown state user key can still be unlocked
4009 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
4010 return StorageManager.isUserKeyUnlocked(userId);
4011 }
4012 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08004013 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07004014
4015 @Override
4016 public boolean isUserInitialized(int userId) {
4017 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
4018 }
4019
4020 @Override
4021 public boolean exists(int userId) {
4022 return getUserInfoNoChecks(userId) != null;
4023 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08004024
4025 @Override
4026 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
4027 boolean throwSecurityException) {
4028 if (targetUserId == callingUserId) {
4029 return true;
4030 }
4031 synchronized (mUsersLock) {
4032 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
4033 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
4034 if (throwSecurityException) {
4035 throw new SecurityException(
4036 debugMsg + " for another profile "
4037 + targetUserId + " from " + callingUserId);
4038 }
4039 }
4040
4041 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
4042 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
4043 // Do not throw any exception here as this could happen due to race conditions
4044 // between the system updating its state and the client getting notified.
4045 if (throwSecurityException) {
4046 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
4047 + targetUserId + " from " + callingUserId);
4048 }
4049 return false;
4050 }
4051
4052 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
4053 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
4054 if (throwSecurityException) {
4055 throw new SecurityException(
4056 debugMsg + " for unrelated profile " + targetUserId);
4057 }
4058 return false;
4059 }
4060 }
4061 return true;
4062 }
4063
4064 @Override
4065 public int getProfileParentId(int userId) {
4066 synchronized (mUsersLock) {
4067 UserInfo profileParent = getProfileParentLU(userId);
4068 if (profileParent == null) {
4069 return userId;
4070 }
4071 return profileParent.id;
4072 }
4073 }
yuemingw1d13eae2018-01-30 17:27:54 +00004074
4075 @Override
4076 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4077 String value, int callingUid) {
4078 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4079 value, callingUid);
4080 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004081 }
4082
4083 /* Remove all the users except of the system one. */
4084 private void removeNonSystemUsers() {
4085 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4086 synchronized (mUsersLock) {
4087 final int userSize = mUsers.size();
4088 for (int i = 0; i < userSize; i++) {
4089 UserInfo ui = mUsers.valueAt(i).info;
4090 if (ui.id != UserHandle.USER_SYSTEM) {
4091 usersToRemove.add(ui);
4092 }
4093 }
4094 }
4095 for (UserInfo ui: usersToRemove) {
4096 removeUser(ui.id);
4097 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004098 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004099
4100 private class Shell extends ShellCommand {
4101 @Override
4102 public int onCommand(String cmd) {
4103 return onShellCommand(this, cmd);
4104 }
4105
4106 @Override
4107 public void onHelp() {
4108 final PrintWriter pw = getOutPrintWriter();
4109 pw.println("User manager (user) commands:");
4110 pw.println(" help");
4111 pw.println(" Print this help text.");
4112 pw.println("");
4113 pw.println(" list");
4114 pw.println(" Prints all users on the system.");
4115 }
4116 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004117
4118 private static void debug(String message) {
4119 Log.d(LOG_TAG, message +
4120 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4121 }
Kenny Guy02c89902016-11-15 19:36:38 +00004122
4123 @VisibleForTesting
4124 static int getMaxManagedProfiles() {
4125 // Allow overriding max managed profiles on debuggable builds for testing
4126 // of multiple profiles.
4127 if (!Build.IS_DEBUGGABLE) {
4128 return MAX_MANAGED_PROFILES;
4129 } else {
4130 return SystemProperties.getInt("persist.sys.max_profiles",
4131 MAX_MANAGED_PROFILES);
4132 }
4133 }
4134
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004135 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004136 @VisibleForTesting
4137 int getFreeProfileBadgeLU(int parentUserId) {
4138 int maxManagedProfiles = getMaxManagedProfiles();
4139 boolean[] usedBadges = new boolean[maxManagedProfiles];
4140 final int userSize = mUsers.size();
4141 for (int i = 0; i < userSize; i++) {
4142 UserInfo ui = mUsers.valueAt(i).info;
4143 // Check which badge indexes are already used by this profile group.
4144 if (ui.isManagedProfile()
4145 && ui.profileGroupId == parentUserId
4146 && !mRemovingUserIds.get(ui.id)
4147 && ui.profileBadge < maxManagedProfiles) {
4148 usedBadges[ui.profileBadge] = true;
4149 }
4150 }
4151 for (int i = 0; i < maxManagedProfiles; i++) {
4152 if (!usedBadges[i]) {
4153 return i;
4154 }
4155 }
4156 return 0;
4157 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004158
4159 /**
4160 * Checks if the given user has a managed profile associated with it.
4161 * @param userId The parent user
4162 * @return
4163 */
4164 boolean hasManagedProfile(int userId) {
4165 synchronized (mUsersLock) {
4166 UserInfo userInfo = getUserInfoLU(userId);
4167 final int userSize = mUsers.size();
4168 for (int i = 0; i < userSize; i++) {
4169 UserInfo profile = mUsers.valueAt(i).info;
4170 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4171 return true;
4172 }
4173 }
4174 return false;
4175 }
4176 }
Tony Makd390ae92017-12-28 13:23:10 +00004177
4178 /**
4179 * Check if the calling package name matches with the calling UID, throw
4180 * {@link SecurityException} if not.
4181 */
4182 private void verifyCallingPackage(String callingPackage, int callingUid) {
4183 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4184 if (packageUid != callingUid) {
4185 throw new SecurityException("Specified package " + callingPackage
4186 + " does not match the calling uid " + callingUid);
4187 }
4188 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004189}