blob: a0577b15736beea36d2a8b7cf7f1ccdbc0d81078 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.content.Context;
36import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010037import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010038import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070039import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080040import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000041import android.content.pm.ShortcutServiceInternal;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000053import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080055import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010056import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080058import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070060import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010062import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090066import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000067import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070069import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010070import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070071import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080072import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010073import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070074import android.security.GateKeeper;
75import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani2a003292012-08-14 18:25:45 -070076import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070077import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070078import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import android.util.Slog;
80import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080081import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000082import android.util.SparseIntArray;
Makoto Onuki73dded22017-12-20 13:14:48 +090083import android.util.SparseLongArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070084import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import android.util.Xml;
86
Makoto Onuki068c54a2015-10-13 14:34:03 -070087import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070088import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040089import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080090import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080091import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060092import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080093import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070094import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070095import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000096import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070097import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060098import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070099import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000100import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700101import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100102
Jeff Sharkey47f71082016-02-01 17:03:54 -0700103import libcore.io.IoUtils;
104import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800105
106import org.xmlpull.v1.XmlPullParser;
107import org.xmlpull.v1.XmlPullParserException;
108import org.xmlpull.v1.XmlSerializer;
109
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110import java.io.BufferedOutputStream;
111import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700112import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700114import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000116import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000117import java.io.InputStream;
118import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700119import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100120import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100122import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700123import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124import java.util.List;
125
Makoto Onuki068c54a2015-10-13 14:34:03 -0700126/**
127 * Service for {@link UserManager}.
128 *
129 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700130 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700131 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800132 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700133 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
134 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
135 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700136 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700137public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700138
Amith Yamasani2a003292012-08-14 18:25:45 -0700139 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800140 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800141 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700142 // Can be used for manual testing of id recycling
143 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700144
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800146 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700148 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700150 private static final String ATTR_CREATION_TIME = "created";
151 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600152 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700153 private static final String ATTR_SERIAL_NO = "serialNumber";
154 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700155 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700156 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700157 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100158 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000159 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700160 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800161 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
162 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530163 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700165 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800166 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800167 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100168 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
169 "device_policy_global_restrictions";
170 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100171 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100172 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800173 private static final String TAG_ENTRY = "entry";
174 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800175 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700177 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700180 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
181 private static final String ATTR_TYPE_STRING = "s";
182 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700183 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700184 private static final String ATTR_TYPE_BUNDLE = "B";
185 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700186
Amith Yamasani0b285492011-04-14 17:35:23 -0700187 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700189 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100190 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800192 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700193 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800194
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700195 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
196 UserInfo.FLAG_MANAGED_PROFILE
197 | UserInfo.FLAG_EPHEMERAL
198 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700199 | UserInfo.FLAG_GUEST
200 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700201
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700202 @VisibleForTesting
203 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700204 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700205 @VisibleForTesting
206 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
207
208 // Max size of the queue of recently removed users
209 @VisibleForTesting
210 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700211
Pavel Grafov6a40f092016-10-25 15:46:51 +0100212 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700213
Amith Yamasani920ace02012-09-20 22:15:37 -0700214 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
215
Nicolas Prevotb8186812015-08-06 15:00:03 +0100216 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700217 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000218 @VisibleForTesting
219 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700220
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800221 static final int WRITE_USER_MSG = 1;
222 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530223
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800224 // Tron counters
225 private static final String TRON_GUEST_CREATED = "users_guest_created";
226 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700227 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800228
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229 private final Context mContext;
230 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700231 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800232 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700233 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600234 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700235 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700236 // Used for serializing access to app restriction files
237 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700238
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800239 private final Handler mHandler;
240
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700241 private final File mUsersDir;
242 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700243
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800244 private static final IBinder mUserRestriconToken = new Binder();
245
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900247 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800248 */
Kenny Guy02c89902016-11-15 19:36:38 +0000249 @VisibleForTesting
250 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800251 // Basic user information and properties
252 UserInfo info;
253 // Account name used when there is a strong association between a user and an account
254 String account;
255 // Account information for seeding into a newly created user. This could also be
256 // used for login validation for an existing user, for updating their credentials.
257 // In the latter case, data may not need to be persisted as it is only valid for the
258 // current login session.
259 String seedAccountName;
260 String seedAccountType;
261 PersistableBundle seedAccountOptions;
262 // Whether to perist the seed account information to be available after a boot
263 boolean persistSeedData;
264
Makoto Onuki73dded22017-12-20 13:14:48 +0900265 /** Elapsed realtime since boot when the user started. */
266 long startRealtime;
267
268 /** Elapsed realtime since boot when the user was unlocked. */
269 long unlockRealtime;
270
Amith Yamasani12747872015-12-07 14:19:49 -0800271 void clearSeedAccountData() {
272 seedAccountName = null;
273 seedAccountType = null;
274 seedAccountOptions = null;
275 persistSeedData = false;
276 }
277 }
278
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800279 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800280 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800281
282 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700283 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100284 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700285 *
286 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
287 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
288 * maybe shared between {@link #mBaseUserRestrictions} and
289 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
290 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700291 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700292 */
293 @GuardedBy("mRestrictionsLock")
294 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
295
296 /**
297 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
298 * with device / profile owner restrictions. We'll initialize it lazily; use
299 * {@link #getEffectiveUserRestrictions} to access it.
300 *
301 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
302 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
303 * maybe shared between {@link #mBaseUserRestrictions} and
304 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
305 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700306 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700307 */
308 @GuardedBy("mRestrictionsLock")
309 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
310
Makoto Onuki4f160732015-10-27 17:15:38 -0700311 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800312 * User restrictions that have already been applied in
313 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
314 * that have changed since the last
315 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700316 */
317 @GuardedBy("mRestrictionsLock")
318 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
319
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800320 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800321 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100322 * that should be applied to all users, including guests. Only non-empty restriction bundles are
323 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800324 */
325 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100326 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800327
328 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100329 * Id of the user that set global restrictions.
330 */
331 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100332 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100333
334 /**
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 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800337 */
338 @GuardedBy("mRestrictionsLock")
339 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
340
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800341 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530342 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800343
344 /**
345 * Set of user IDs being actively removed. Removed IDs linger in this set
346 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700347 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800348 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700349 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800350 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700351
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700352 /**
353 * Queue of recently removed userIds. Used for recycling of userIds
354 */
355 @GuardedBy("mUsersLock")
356 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
357
Fyodor Kupolov82402752015-10-28 14:54:51 -0700358 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700359 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800360 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700361 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700362 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700363
Jason Monk62062992014-05-06 09:55:28 -0400364 private IAppOpsService mAppOpsService;
365
Makoto Onuki068c54a2015-10-13 14:34:03 -0700366 private final LocalService mLocalService;
367
Makoto Onukie7927da2015-11-25 10:05:17 -0800368 @GuardedBy("mUsersLock")
369 private boolean mIsDeviceManaged;
370
371 @GuardedBy("mUsersLock")
372 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
373
Makoto Onukid45a4a22015-11-02 17:17:38 -0800374 @GuardedBy("mUserRestrictionsListeners")
375 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
376 new ArrayList<>();
377
Clara Bayarria1771112015-12-18 16:29:18 +0000378 private final LockPatternUtils mLockPatternUtils;
379
Ricky Waib1dd80b2016-06-07 18:00:55 +0100380 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
381 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
382
383 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
384 @Override
385 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000386 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
387 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100388 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000389 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
390 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800391 // Call setQuietModeEnabled on bg thread to avoid ANR
392 BackgroundThread.getHandler()
393 .post(() -> setQuietModeEnabled(userHandle, false, target));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100394 }
395 };
396
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100397 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000398 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
399 *
Tony Makbece85d2018-01-12 12:10:17 +0000400 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000401 */
402 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
403 private final IntentSender mTarget;
404
405 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
406 Preconditions.checkNotNull(target);
407 mTarget = target;
408 }
409
410 @Override
411 public void onStarted(int id, Bundle extras) {}
412
413 @Override
414 public void onProgress(int id, int progress, Bundle extras) {}
415
416 @Override
417 public void onFinished(int id, Bundle extras) {
418 try {
419 mContext.startIntentSender(mTarget, null, 0, 0, 0);
420 } catch (IntentSender.SendIntentException e) {
421 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
422 }
423 }
424 }
425
426 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100427 * Whether all users should be created ephemeral.
428 */
429 @GuardedBy("mUsersLock")
430 private boolean mForceEphemeralUsers;
431
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000432 @GuardedBy("mUserStates")
433 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700434
Amith Yamasani258848d2012-08-10 17:06:33 -0700435 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700436
Dianne Hackborn4428e172012-08-24 17:43:05 -0700437 public static UserManagerService getInstance() {
438 synchronized (UserManagerService.class) {
439 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700440 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700441 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700442
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700443 public static class LifeCycle extends SystemService {
444
445 private UserManagerService mUms;
446
447 /**
448 * @param context
449 */
450 public LifeCycle(Context context) {
451 super(context);
452 }
453
454 @Override
455 public void onStart() {
456 mUms = UserManagerService.getInstance();
457 publishBinderService(Context.USER_SERVICE, mUms);
458 }
459
460 @Override
461 public void onBootPhase(int phase) {
462 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
463 mUms.cleanupPartialUsers();
464 }
465 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900466
467 @Override
468 public void onStartUser(int userHandle) {
469 synchronized (mUms.mUsersLock) {
470 final UserData user = mUms.getUserDataLU(userHandle);
471 if (user != null) {
472 user.startRealtime = SystemClock.elapsedRealtime();
473 }
474 }
475 }
476
477 @Override
478 public void onUnlockUser(int userHandle) {
479 synchronized (mUms.mUsersLock) {
480 final UserData user = mUms.getUserDataLU(userHandle);
481 if (user != null) {
482 user.unlockRealtime = SystemClock.elapsedRealtime();
483 }
484 }
485 }
486
487 @Override
488 public void onStopUser(int userHandle) {
489 synchronized (mUms.mUsersLock) {
490 final UserData user = mUms.getUserDataLU(userHandle);
491 if (user != null) {
492 user.startRealtime = 0;
493 user.unlockRealtime = 0;
494 }
495 }
496 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700497 }
498
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700499 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800500 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700501 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800502 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700503 }
504
Dianne Hackborn4428e172012-08-24 17:43:05 -0700505 /**
506 * Called by package manager to create the service. This is closely
507 * associated with the package manager, and the given lock is the
508 * package manager's own lock.
509 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800510 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
511 Object packagesLock) {
512 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700513 }
514
Dianne Hackborn4428e172012-08-24 17:43:05 -0700515 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800516 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700517 mContext = context;
518 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700519 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800520 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800521 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800522 synchronized (mPackagesLock) {
523 mUsersDir = new File(dataDir, USER_INFO_DIR);
524 mUsersDir.mkdirs();
525 // Make zeroth user directory, for services to migrate their files to that location
526 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
527 userZeroDir.mkdirs();
528 FileUtils.setPermissions(mUsersDir.toString(),
529 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
530 -1, -1);
531 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
532 initDefaultGuestRestrictions();
533 readUserListLP();
534 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700535 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700536 mLocalService = new LocalService();
537 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000538 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000539 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700540 }
541
542 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400543 mAppOpsService = IAppOpsService.Stub.asInterface(
544 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800545
546 synchronized (mRestrictionsLock) {
547 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400548 }
Samuel Tand9453b82016-03-14 15:57:02 -0700549
550 UserInfo currentGuestUser = findCurrentGuestUser();
551 if (currentGuestUser != null && !hasUserRestriction(
552 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
553 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
554 // to it, in case this guest was created in a previous version where this
555 // user restriction was not a default guest restriction.
556 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
557 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700558
Ricky Waib1dd80b2016-06-07 18:00:55 +0100559 mContext.registerReceiver(mDisableQuietModeCallback,
560 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
561 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700562 }
563
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700564 void cleanupPartialUsers() {
565 // Prune out any partially created, partially removed and ephemeral users.
566 ArrayList<UserInfo> partials = new ArrayList<>();
567 synchronized (mUsersLock) {
568 final int userSize = mUsers.size();
569 for (int i = 0; i < userSize; i++) {
570 UserInfo ui = mUsers.valueAt(i).info;
571 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
572 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700573 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700574 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700575 }
576 }
577 }
578 final int partialsSize = partials.size();
579 for (int i = 0; i < partialsSize; i++) {
580 UserInfo ui = partials.get(i);
581 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
582 + " (name=" + ui.name + ")");
583 removeUserState(ui.id);
584 }
585 }
586
Amith Yamasani258848d2012-08-10 17:06:33 -0700587 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800588 public String getUserAccount(int userId) {
589 checkManageUserAndAcrossUsersFullPermission("get user account");
590 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800591 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800592 }
593 }
594
595 @Override
596 public void setUserAccount(int userId, String accountName) {
597 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800598 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800599 synchronized (mPackagesLock) {
600 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800601 final UserData userData = mUsers.get(userId);
602 if (userData == null) {
603 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
604 return;
605 }
606 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800607 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800608 userData.account = accountName;
609 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800610 }
611 }
612
613 if (userToUpdate != null) {
614 writeUserLP(userToUpdate);
615 }
616 }
617 }
618
619 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700620 public UserInfo getPrimaryUser() {
621 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700622 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700623 final int userSize = mUsers.size();
624 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800625 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800626 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700627 return ui;
628 }
629 }
630 }
631 return null;
632 }
633
634 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700635 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700636 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700637 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700638 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700639 final int userSize = mUsers.size();
640 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800641 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700642 if (ui.partial) {
643 continue;
644 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800645 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700646 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700647 }
Amith Yamasani13593602012-03-22 16:16:17 -0700648 }
649 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700650 }
Amith Yamasani13593602012-03-22 16:16:17 -0700651 }
652
Amith Yamasani258848d2012-08-10 17:06:33 -0700653 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100654 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700655 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800656 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700657 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700658 } else {
659 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800660 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700661 final long ident = Binder.clearCallingIdentity();
662 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700663 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700664 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100665 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700666 } finally {
667 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000668 }
669 }
670
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700671 @Override
672 public int[] getProfileIds(int userId, boolean enabledOnly) {
673 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700674 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700675 }
676 final long ident = Binder.clearCallingIdentity();
677 try {
678 synchronized (mUsersLock) {
679 return getProfileIdsLU(userId, enabledOnly).toArray();
680 }
681 } finally {
682 Binder.restoreCallingIdentity(ident);
683 }
684 }
685
Amith Yamasanibe465322014-04-24 13:45:17 -0700686 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700687 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700688 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
689 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
690 for (int i = 0; i < profileIds.size(); i++) {
691 int profileId = profileIds.get(i);
692 UserInfo userInfo = mUsers.get(profileId).info;
693 // If full info is not required - clear PII data to prevent 3P apps from reading it
694 if (!fullInfo) {
695 userInfo = new UserInfo(userInfo);
696 userInfo.name = null;
697 userInfo.iconPath = null;
698 } else {
699 userInfo = userWithName(userInfo);
700 }
701 users.add(userInfo);
702 }
703 return users;
704 }
705
706 /**
707 * Assume permissions already checked and caller's identity cleared
708 */
709 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700710 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700711 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700712 if (user == null) {
713 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700714 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700715 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700716 final int userSize = mUsers.size();
717 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800718 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700719 if (!isProfileOf(user, profile)) {
720 continue;
721 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100722 if (enabledOnly && !profile.isEnabled()) {
723 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700724 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700725 if (mRemovingUserIds.get(profile.id)) {
726 continue;
727 }
Tony Mak80189cd2016-04-05 17:21:42 +0100728 if (profile.partial) {
729 continue;
730 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700731 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700732 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700733 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700734 }
735
Jessica Hummelbe81c802014-04-22 15:49:22 +0100736 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700737 public int getCredentialOwnerProfile(int userHandle) {
738 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000739 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700740 synchronized (mUsersLock) {
741 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700742 if (profileParent != null) {
743 return profileParent.id;
744 }
745 }
746 }
747
748 return userHandle;
749 }
750
751 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700752 public boolean isSameProfileGroup(int userId, int otherUserId) {
753 if (userId == otherUserId) return true;
754 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700755 return isSameProfileGroupNoChecks(userId, otherUserId);
756 }
757
758 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700759 synchronized (mUsersLock) {
760 UserInfo userInfo = getUserInfoLU(userId);
761 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
762 return false;
763 }
764 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
765 if (otherUserInfo == null
766 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
767 return false;
768 }
769 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700770 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700771 }
772
773 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100774 public UserInfo getProfileParent(int userHandle) {
775 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700776 synchronized (mUsersLock) {
777 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700778 }
779 }
780
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800781 @Override
782 public int getProfileParentId(int userHandle) {
783 checkManageUsersPermission("get the profile parent");
784 synchronized (mUsersLock) {
785 UserInfo profileParent = getProfileParentLU(userHandle);
786 if (profileParent == null) {
787 return userHandle;
788 }
789
790 return profileParent.id;
791 }
792 }
793
Fyodor Kupolov82402752015-10-28 14:54:51 -0700794 private UserInfo getProfileParentLU(int userHandle) {
795 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700796 if (profile == null) {
797 return null;
798 }
799 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800800 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700801 return null;
802 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700803 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100804 }
805 }
806
Fyodor Kupolov82402752015-10-28 14:54:51 -0700807 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100808 return user.id == profile.id ||
809 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
810 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000811 }
812
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000813 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000814 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100815 Intent intent = new Intent();
816 if (inQuietMode) {
817 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
818 } else {
819 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
820 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000821 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
822 intent.putExtra(Intent.EXTRA_USER, profileHandle);
823 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000824 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000825 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000826 }
827
828 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000829 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000830 int userHandle, @Nullable IntentSender target) {
831 Preconditions.checkNotNull(callingPackage);
832
Tony Makb7e6fd42017-12-05 19:40:28 +0000833 if (enableQuietMode && target != null) {
834 throw new IllegalArgumentException(
835 "target should only be specified when we are disabling quiet mode.");
836 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000837
Tony Makd390ae92017-12-28 13:23:10 +0000838 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000839 final long identity = Binder.clearCallingIdentity();
840 try {
841 if (enableQuietMode) {
842 setQuietModeEnabled(userHandle, true /* enableQuietMode */, target);
843 return true;
844 } else {
845 boolean needToShowConfirmCredential =
846 mLockPatternUtils.isSecure(userHandle)
847 && !StorageManager.isUserKeyUnlocked(userHandle);
848 if (needToShowConfirmCredential) {
849 showConfirmCredentialToDisableQuietMode(userHandle, target);
850 return false;
851 } else {
852 setQuietModeEnabled(userHandle, false /* enableQuietMode */, target);
853 return true;
854 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000855 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000856 } finally {
857 Binder.restoreCallingIdentity(identity);
858 }
859 }
860
Tony Make3d1f652017-12-12 11:00:37 +0000861 /**
Tony Makd390ae92017-12-28 13:23:10 +0000862 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000863 * <ul>
864 * <li>Has system UID or root UID</li>
865 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
866 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
867 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000868 * <p>
869 * If caller wants to start an intent after disabling the quiet mode, it must has
870 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000871 */
Tony Makd390ae92017-12-28 13:23:10 +0000872 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
873 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000874 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000875 return;
Tony Make3d1f652017-12-12 11:00:37 +0000876 }
Tony Makd390ae92017-12-28 13:23:10 +0000877 if (startIntent) {
878 throw new SecurityException("MANAGE_USERS permission is required to start intent "
879 + "after disabling quiet mode.");
880 }
Tony Make3d1f652017-12-12 11:00:37 +0000881 final boolean hasModifyQuietModePermission = ActivityManager.checkComponentPermission(
882 Manifest.permission.MODIFY_QUIET_MODE,
883 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
884 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000885 return;
Tony Make3d1f652017-12-12 11:00:37 +0000886 }
887
Tony Makd390ae92017-12-28 13:23:10 +0000888 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000889 final ShortcutServiceInternal shortcutInternal =
890 LocalServices.getService(ShortcutServiceInternal.class);
891 if (shortcutInternal != null) {
892 boolean isForegroundLauncher =
893 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
894 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000895 return;
Tony Make3d1f652017-12-12 11:00:37 +0000896 }
897 }
Tony Makd390ae92017-12-28 13:23:10 +0000898 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
899 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000900 }
901
Tony Makb7e6fd42017-12-05 19:40:28 +0000902 private void setQuietModeEnabled(
903 int userHandle, boolean enableQuietMode, IntentSender target) {
904 final UserInfo profile, parent;
905 final UserData profileUserData;
906 synchronized (mUsersLock) {
907 profile = getUserInfoLU(userHandle);
908 parent = getProfileParentLU(userHandle);
909
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000910 if (profile == null || !profile.isManagedProfile()) {
911 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
912 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000913 if (profile.isQuietModeEnabled() == enableQuietMode) {
914 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
915 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000916 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000917 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
918 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000919 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000920 synchronized (mPackagesLock) {
921 writeUserLP(profileUserData);
922 }
923 try {
924 if (enableQuietMode) {
925 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
926 LocalServices.getService(ActivityManagerInternal.class)
927 .killForegroundAppsForUser(userHandle);
928 } else {
929 IProgressListener callback = target != null
930 ? new DisableQuietModeUserUnlockedCallback(target)
931 : null;
932 ActivityManager.getService().startUserInBackgroundWithListener(
933 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000934 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000935 } catch (RemoteException e) {
936 // Should not happen, same process.
937 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000938 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000939 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
940 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000941 }
942
943 @Override
944 public boolean isQuietModeEnabled(int userHandle) {
945 synchronized (mPackagesLock) {
946 UserInfo info;
947 synchronized (mUsersLock) {
948 info = getUserInfoLU(userHandle);
949 }
950 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000951 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000952 }
953 return info.isQuietModeEnabled();
954 }
955 }
956
Tony Makb7e6fd42017-12-05 19:40:28 +0000957 /**
958 * Show confirm credential screen to unlock user in order to turn off quiet mode.
959 */
960 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000961 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000962 // otherwise, we show a profile challenge to trigger decryption of the user
963 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
964 Context.KEYGUARD_SERVICE);
965 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
966 // lock, confirm screenlock page will know and show personal challenge, and unlock
967 // work profile when personal challenge is correct
968 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
969 userHandle);
970 if (unlockIntent == null) {
971 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +0100972 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000973 final Intent callBackIntent = new Intent(
974 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
975 if (target != null) {
976 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100977 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000978 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
979 callBackIntent.setPackage(mContext.getPackageName());
980 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
981 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
982 mContext,
983 0,
984 callBackIntent,
985 PendingIntent.FLAG_CANCEL_CURRENT |
986 PendingIntent.FLAG_ONE_SHOT |
987 PendingIntent.FLAG_IMMUTABLE);
988 // After unlocking the challenge, it will disable quiet mode and run the original
989 // intentSender
990 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
991 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
992 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100993 }
994
995 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100996 public void setUserEnabled(int userId) {
997 checkManageUsersPermission("enable user");
998 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700999 UserInfo info;
1000 synchronized (mUsersLock) {
1001 info = getUserInfoLU(userId);
1002 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001003 if (info != null && !info.isEnabled()) {
1004 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001005 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001006 }
1007 }
1008 }
1009
Andrew Scull85a63bc2016-10-24 13:47:47 +01001010 /**
1011 * Evicts a user's CE key by stopping and restarting the user.
1012 *
1013 * The key is evicted automatically by the user controller when the user has stopped.
1014 */
1015 @Override
1016 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1017 checkManageUsersPermission("evict CE key");
1018 final IActivityManager am = ActivityManagerNative.getDefault();
1019 final long identity = Binder.clearCallingIdentity();
1020 try {
1021 am.restartUserInBackground(userId);
1022 } catch (RemoteException re) {
1023 throw re.rethrowAsRuntimeException();
1024 } finally {
1025 Binder.restoreCallingIdentity(identity);
1026 }
1027 }
1028
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001029 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001030 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001031 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001032 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001033 return userWithName(getUserInfoLU(userId));
1034 }
1035 }
1036
1037 /**
1038 * Returns a UserInfo object with the name filled in, for Owner, or the original
1039 * if the name is already set.
1040 */
1041 private UserInfo userWithName(UserInfo orig) {
1042 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1043 UserInfo withName = new UserInfo(orig);
1044 withName.name = getOwnerName();
1045 return withName;
1046 } else {
1047 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001048 }
1049 }
1050
1051 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001052 public int getManagedProfileBadge(@UserIdInt int userId) {
1053 int callingUserId = UserHandle.getCallingUserId();
1054 if (callingUserId != userId && !hasManageUsersPermission()) {
1055 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
1056 throw new SecurityException(
1057 "You need MANAGE_USERS permission to: check if specified user a " +
1058 "managed profile outside your profile group");
1059 }
1060 }
1061 synchronized (mUsersLock) {
1062 UserInfo userInfo = getUserInfoLU(userId);
1063 return userInfo != null ? userInfo.profileBadge : 0;
1064 }
1065 }
1066
1067 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001068 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +00001069 int callingUserId = UserHandle.getCallingUserId();
1070 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -07001071 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001072 throw new SecurityException(
1073 "You need MANAGE_USERS permission to: check if specified user a " +
1074 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +00001075 }
Tony Mak4dc008c2016-03-16 10:46:49 +00001076 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001077 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001078 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001079 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001080 }
1081 }
1082
Amith Yamasani71e6c692013-03-24 17:39:28 -07001083 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001084 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001085 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001086 return mLocalService.isUserUnlockingOrUnlocked(userId);
1087 }
1088
1089 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001090 public boolean isUserUnlocked(int userId) {
1091 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001092 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001093 }
1094
1095 @Override
1096 public boolean isUserRunning(int userId) {
1097 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1098 return mLocalService.isUserRunning(userId);
1099 }
1100
Makoto Onuki73dded22017-12-20 13:14:48 +09001101 @Override
1102 public long getUserStartRealtime() {
1103 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1104 synchronized (mUsersLock) {
1105 final UserData user = getUserDataLU(userId);
1106 if (user != null) {
1107 return user.startRealtime;
1108 }
1109 return 0;
1110 }
1111 }
1112
1113 @Override
1114 public long getUserUnlockRealtime() {
1115 synchronized (mUsersLock) {
1116 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1117 if (user != null) {
1118 return user.unlockRealtime;
1119 }
1120 return 0;
1121 }
1122 }
1123
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001124 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1125 int callingUserId = UserHandle.getCallingUserId();
1126 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1127 hasManageUsersPermission()) {
1128 return;
1129 }
1130 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
1131 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
1132 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1133 + "to: check " + name);
1134 }
1135 }
1136
1137 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001138 public boolean isDemoUser(int userId) {
1139 int callingUserId = UserHandle.getCallingUserId();
1140 if (callingUserId != userId && !hasManageUsersPermission()) {
1141 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1142 + " is a demo user");
1143 }
1144 synchronized (mUsersLock) {
1145 UserInfo userInfo = getUserInfoLU(userId);
1146 return userInfo != null && userInfo.isDemo();
1147 }
1148 }
1149
1150 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001151 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001152 synchronized (mUsersLock) {
1153 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001154 }
1155 }
1156
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001157 @Override
1158 public boolean canHaveRestrictedProfile(int userId) {
1159 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001160 synchronized (mUsersLock) {
1161 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001162 if (userInfo == null || !userInfo.canHaveProfile()) {
1163 return false;
1164 }
1165 if (!userInfo.isAdmin()) {
1166 return false;
1167 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001168 // restricted profile can be created if there is no DO set and the admin user has no PO;
1169 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001170 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001171 }
1172
Fyodor Kupolovca177562017-11-09 17:43:01 -08001173 @Override
1174 public boolean hasRestrictedProfiles() {
1175 checkManageUsersPermission("hasRestrictedProfiles");
1176 final int callingUserId = UserHandle.getCallingUserId();
1177 synchronized (mUsersLock) {
1178 final int userSize = mUsers.size();
1179 for (int i = 0; i < userSize; i++) {
1180 UserInfo profile = mUsers.valueAt(i).info;
1181 if (callingUserId != profile.id
1182 && profile.restrictedProfileParentId == callingUserId) {
1183 return true;
1184 }
1185 }
1186 return false;
1187 }
1188 }
1189
Amith Yamasani195263742012-08-21 15:40:12 -07001190 /*
1191 * Should be locked on mUsers before calling this.
1192 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001193 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001194 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001195 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001196 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001197 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1198 return null;
1199 }
Amith Yamasani12747872015-12-07 14:19:49 -08001200 return userData != null ? userData.info : null;
1201 }
1202
1203 private UserData getUserDataLU(int userId) {
1204 final UserData userData = mUsers.get(userId);
1205 // If it is partial and not in the process of being removed, return as unknown user.
1206 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1207 return null;
1208 }
1209 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001210 }
1211
Fyodor Kupolov82402752015-10-28 14:54:51 -07001212 /**
1213 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1214 * <p>No permissions checking or any addition checks are made</p>
1215 */
1216 private UserInfo getUserInfoNoChecks(int userId) {
1217 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001218 final UserData userData = mUsers.get(userId);
1219 return userData != null ? userData.info : null;
1220 }
1221 }
1222
1223 /**
1224 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1225 * <p>No permissions checking or any addition checks are made</p>
1226 */
1227 private UserData getUserDataNoChecks(int userId) {
1228 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001229 return mUsers.get(userId);
1230 }
1231 }
1232
Amith Yamasani236b2b52015-08-18 14:32:14 -07001233 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001234 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001235 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001236 }
1237
Amith Yamasani258848d2012-08-10 17:06:33 -07001238 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001239 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001240 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001241 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001242 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001243 UserData userData = getUserDataNoChecks(userId);
1244 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001245 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1246 return;
1247 }
Amith Yamasani12747872015-12-07 14:19:49 -08001248 if (name != null && !name.equals(userData.info.name)) {
1249 userData.info.name = name;
1250 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001251 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001252 }
1253 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001254 if (changed) {
1255 sendUserInfoChangedBroadcast(userId);
1256 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001257 }
1258
Amith Yamasani258848d2012-08-10 17:06:33 -07001259 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001260 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001261 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001262 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1263 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1264 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001265 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001266 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001267 }
1268
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001269
1270
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001271 private void sendUserInfoChangedBroadcast(int userId) {
1272 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1273 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1274 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001275 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001276 }
1277
Amith Yamasani258848d2012-08-10 17:06:33 -07001278 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001279 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001280 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001281 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001282 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1283 if (targetUserInfo == null || targetUserInfo.partial) {
1284 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001285 return null;
1286 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001287
1288 final int callingUserId = UserHandle.getCallingUserId();
1289 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1290 final int targetGroupId = targetUserInfo.profileGroupId;
1291 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1292 && callingGroupId == targetGroupId);
1293 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001294 checkManageUsersPermission("get the icon of a user who is not related");
1295 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001296
1297 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001298 return null;
1299 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001300 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001301 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001302
1303 try {
1304 return ParcelFileDescriptor.open(
1305 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1306 } catch (FileNotFoundException e) {
1307 Log.e(LOG_TAG, "Couldn't find icon file", e);
1308 }
1309 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001310 }
1311
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001312 public void makeInitialized(int userId) {
1313 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001314 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001315 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001316 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001317 userData = mUsers.get(userId);
1318 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001319 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001320 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001321 }
Amith Yamasani12747872015-12-07 14:19:49 -08001322 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1323 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001324 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001325 }
1326 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001327 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001328 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001329 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001330 }
1331
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001332 /**
1333 * If default guest restrictions haven't been initialized yet, add the basic
1334 * restrictions.
1335 */
1336 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001337 synchronized (mGuestRestrictions) {
1338 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001339 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001340 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001341 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1342 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1343 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001344 }
1345 }
1346
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001347 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301348 public Bundle getDefaultGuestRestrictions() {
1349 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001350 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301351 return new Bundle(mGuestRestrictions);
1352 }
1353 }
1354
1355 @Override
1356 public void setDefaultGuestRestrictions(Bundle restrictions) {
1357 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001358 synchronized (mGuestRestrictions) {
1359 mGuestRestrictions.clear();
1360 mGuestRestrictions.putAll(restrictions);
1361 }
1362 synchronized (mPackagesLock) {
1363 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301364 }
1365 }
1366
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001367 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001368 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001369 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001370 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1371 boolean isDeviceOwner, int cameraRestrictionScope) {
1372 final Bundle global = new Bundle();
1373 final Bundle local = new Bundle();
1374
1375 // Sort restrictions into local and global ensuring they don't overlap.
1376 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1377 cameraRestrictionScope, global, local);
1378
1379 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001380 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001381 // Update global and local restrictions if they were changed.
1382 globalChanged = updateRestrictionsIfNeededLR(
1383 userId, global, mDevicePolicyGlobalUserRestrictions);
1384 localChanged = updateRestrictionsIfNeededLR(
1385 userId, local, mDevicePolicyLocalUserRestrictions);
1386
1387 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001388 // Remember the global restriction owner userId to be able to make a distinction
1389 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001390 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001391 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001392 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001393 // When profile owner sets restrictions it passes null global bundle and we
1394 // reset global restriction owner userId.
1395 // This means this user used to have DO, but now the DO is gone and the user
1396 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001397 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001398 }
1399 }
1400 }
1401 if (DBG) {
1402 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1403 + " global=" + global + (globalChanged ? " (changed)" : "")
1404 + " local=" + local + (localChanged ? " (changed)" : "")
1405 );
1406 }
1407 // Don't call them within the mRestrictionsLock.
1408 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001409 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001410 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001411 }
1412 }
1413
1414 synchronized (mRestrictionsLock) {
1415 if (globalChanged) {
1416 applyUserRestrictionsForAllUsersLR();
1417 } else if (localChanged) {
1418 applyUserRestrictionsLR(userId);
1419 }
1420 }
1421 }
1422
Pavel Grafov6a40f092016-10-25 15:46:51 +01001423 /**
1424 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1425 * empty, record is removed from the array.
1426 * @return whether restrictions bundle is different from the old one.
1427 */
1428 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1429 SparseArray<Bundle> restrictionsArray) {
1430 final boolean changed =
1431 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1432 if (changed) {
1433 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1434 restrictionsArray.put(userId, restrictions);
1435 } else {
1436 restrictionsArray.delete(userId);
1437 }
1438 }
1439 return changed;
1440 }
1441
Makoto Onuki068c54a2015-10-13 14:34:03 -07001442 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001443 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001444 final Bundle baseRestrictions =
1445 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001446 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001447 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001448
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1450 // Common case first.
1451 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001452 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001453 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1454 UserRestrictionsUtils.merge(effective, global);
1455 UserRestrictionsUtils.merge(effective, local);
1456
Makoto Onuki068c54a2015-10-13 14:34:03 -07001457 return effective;
1458 }
1459
1460 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001461 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001462 if (DBG) {
1463 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1464 }
1465 mCachedEffectiveUserRestrictions.remove(userId);
1466 }
1467
1468 private Bundle getEffectiveUserRestrictions(int userId) {
1469 synchronized (mRestrictionsLock) {
1470 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1471 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001472 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001473 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1474 }
1475 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001476 }
1477 }
1478
Makoto Onuki068c54a2015-10-13 14:34:03 -07001479 /** @return a specific user restriction that's in effect currently. */
1480 @Override
1481 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001482 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1483 return false;
1484 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001485 Bundle restrictions = getEffectiveUserRestrictions(userId);
1486 return restrictions != null && restrictions.getBoolean(restrictionKey);
1487 }
1488
1489 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001490 * @hide
1491 *
1492 * Returns who set a user restriction on a user.
1493 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1494 * @param restrictionKey the string key representing the restriction
1495 * @param userId the id of the user for whom to retrieve the restrictions.
1496 * @return The source of user restriction. Any combination of
1497 * {@link UserManager#RESTRICTION_NOT_SET},
1498 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1499 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1500 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1501 */
1502 @Override
1503 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001504 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1505 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001506 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001507 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1508 result |= enforcingUsers.get(i).getUserRestrictionSource();
1509 }
1510 return result;
1511 }
1512
1513 @Override
1514 public List<EnforcingUser> getUserRestrictionSources(
1515 String restrictionKey, @UserIdInt int userId) {
1516 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001517
1518 // Shortcut for the most common case
1519 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001520 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001521 }
1522
Pavel Grafov6a40f092016-10-25 15:46:51 +01001523 final List<EnforcingUser> result = new ArrayList<>();
1524
1525 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001526 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001527 result.add(new EnforcingUser(
1528 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001529 }
1530
Pavel Grafov6a40f092016-10-25 15:46:51 +01001531 synchronized (mRestrictionsLock) {
1532 // Check if it is set by profile owner.
1533 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1534 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1535 result.add(getEnforcingUserLocked(userId));
1536 }
1537
1538 // Iterate over all users who enforce global restrictions.
1539 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1540 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1541 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1542 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1543 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001544 }
1545 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001546 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001547 return result;
1548 }
1549
Andreas Gampea36dc622018-02-05 17:19:22 -08001550 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001551 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1552 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1553 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1554 return new EnforcingUser(userId, source);
1555 }
1556
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001557 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001558 * @return UserRestrictions that are in effect currently. This always returns a new
1559 * {@link Bundle}.
1560 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001561 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001562 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001563 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001564 }
1565
1566 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001567 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1568 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001569 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1570 return false;
1571 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001572 synchronized (mRestrictionsLock) {
1573 Bundle bundle = mBaseUserRestrictions.get(userId);
1574 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1575 }
1576 }
1577
1578 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001579 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001580 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001581 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1582 return;
1583 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001584 synchronized (mRestrictionsLock) {
1585 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1586 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001587 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1588 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001589 newRestrictions.putBoolean(key, value);
1590
Fyodor Kupolov82402752015-10-28 14:54:51 -07001591 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001592 }
1593 }
1594
Makoto Onuki068c54a2015-10-13 14:34:03 -07001595 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001596 * Optionally updating user restrictions, calculate the effective user restrictions and also
1597 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001598 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001599 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001600 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001601 * @param userId target user ID.
1602 */
1603 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001604 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001605 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001606 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1607 mAppliedUserRestrictions.get(userId));
1608
1609 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001610 if (newBaseRestrictions != null) {
1611 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001612 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1613
Pavel Grafov6a40f092016-10-25 15:46:51 +01001614 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001615 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001616 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001617
Pavel Grafov6a40f092016-10-25 15:46:51 +01001618 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001619 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001620 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001621 }
1622
Fyodor Kupolov82402752015-10-28 14:54:51 -07001623 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001624
Makoto Onuki759a7632015-10-28 16:43:10 -07001625 mCachedEffectiveUserRestrictions.put(userId, effective);
1626
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001627 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001628 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001629 debug("Applying user restrictions: userId=" + userId
1630 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001631 }
1632
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001634 mHandler.post(new Runnable() {
1635 @Override
1636 public void run() {
1637 try {
1638 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1639 } catch (RemoteException e) {
1640 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1641 }
1642 }
1643 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001644 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001645
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001647
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001648 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001649 }
1650
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001651 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001652 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1654 // actually, but we still need some kind of synchronization otherwise we might end up
1655 // calling listeners out-of-order, thus "LR".
1656
1657 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1658 return;
1659 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001660
1661 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1662 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1663
1664 mHandler.post(new Runnable() {
1665 @Override
1666 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001667 UserRestrictionsUtils.applyUserRestrictions(
1668 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001669
Makoto Onukid45a4a22015-11-02 17:17:38 -08001670 final UserRestrictionsListener[] listeners;
1671 synchronized (mUserRestrictionsListeners) {
1672 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1673 mUserRestrictionsListeners.toArray(listeners);
1674 }
1675 for (int i = 0; i < listeners.length; i++) {
1676 listeners[i].onUserRestrictionsChanged(userId,
1677 newRestrictionsFinal, prevRestrictionsFinal);
1678 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001679
1680 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1681 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1682 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001683 }
1684 });
1685 }
1686
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687 // Package private for the inner class.
1688 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001689 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001690 }
1691
1692 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693 // Package private for the inner class.
1694 void applyUserRestrictionsForAllUsersLR() {
1695 if (DBG) {
1696 debug("applyUserRestrictionsForAllUsersLR");
1697 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001698 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001699 mCachedEffectiveUserRestrictions.clear();
1700
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001701 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001702 // it on a handler.
1703 final Runnable r = new Runnable() {
1704 @Override
1705 public void run() {
1706 // Then get the list of running users.
1707 final int[] runningUsers;
1708 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001709 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001710 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001711 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001712 return;
1713 }
1714 // Then re-calculate the effective restrictions and apply, only for running users.
1715 // It's okay if a new user has started after the getRunningUserIds() call,
1716 // because we'll do the same thing (re-calculate the restrictions and apply)
1717 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001718 synchronized (mRestrictionsLock) {
1719 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001721 }
1722 }
1723 }
1724 };
1725 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001726 }
1727
Amith Yamasani258848d2012-08-10 17:06:33 -07001728 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001729 * Check if we've hit the limit of how many users can be created.
1730 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001731 private boolean isUserLimitReached() {
1732 int count;
1733 synchronized (mUsersLock) {
1734 count = getAliveUsersExcludingGuestsCountLU();
1735 }
1736 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001737 }
1738
1739 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001740 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001741 checkManageUsersPermission("check if more managed profiles can be added.");
1742 if (ActivityManager.isLowRamDeviceStatic()) {
1743 return false;
1744 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001745 if (!mContext.getPackageManager().hasSystemFeature(
1746 PackageManager.FEATURE_MANAGED_USERS)) {
1747 return false;
1748 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001749 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001750 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001751 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001752 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001753 return false;
1754 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001755 synchronized(mUsersLock) {
1756 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001757 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001758 return false;
1759 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001760 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1761 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001762 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001763 return usersCountAfterRemoving == 1
1764 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001765 }
1766 }
1767
Fyodor Kupolov82402752015-10-28 14:54:51 -07001768 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001769 int aliveUserCount = 0;
1770 final int totalUserCount = mUsers.size();
1771 // Skip over users being removed
1772 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001773 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001774 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001775 aliveUserCount++;
1776 }
1777 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001778 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001779 }
1780
1781 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001782 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001783 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1784 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1785 * permissions can make certain calls to the UserManager.
1786 *
1787 * @param message used as message if SecurityException is thrown
1788 * @throws SecurityException if the caller does not have enough privilege.
1789 */
1790 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1791 final int uid = Binder.getCallingUid();
1792 if (uid != Process.SYSTEM_UID && uid != 0
1793 && ActivityManager.checkComponentPermission(
1794 Manifest.permission.MANAGE_USERS,
1795 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1796 && ActivityManager.checkComponentPermission(
1797 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1798 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1799 throw new SecurityException(
1800 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1801 + message);
1802 }
1803 }
1804
1805 /**
1806 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001807 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001808 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001809 *
1810 * @param message used as message if SecurityException is thrown
1811 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001812 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001813 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001814 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001815 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001816 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1817 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001818 }
1819
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001820 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001821 * Enforces that only the system UID or root's UID or apps that have the
1822 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1823 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1824 * can make certain calls to the UserManager.
1825 *
1826 * @param message used as message if SecurityException is thrown
1827 * @throws SecurityException if the caller is not system or root
1828 * @see #hasManageOrCreateUsersPermission()
1829 */
1830 private static final void checkManageOrCreateUsersPermission(String message) {
1831 if (!hasManageOrCreateUsersPermission()) {
1832 throw new SecurityException(
1833 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1834 }
1835 }
1836
1837 /**
1838 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1839 * to create user/profiles other than what is allowed for
1840 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1841 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1842 */
1843 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1844 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1845 if (!hasManageOrCreateUsersPermission()) {
1846 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1847 + "permission to create an user with flags: " + creationFlags);
1848 }
1849 } else if (!hasManageUsersPermission()) {
1850 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1851 + " with flags: " + creationFlags);
1852 }
1853 }
1854
1855 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001856 * @return whether the calling UID is system UID or root's UID or the calling app has the
1857 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1858 */
1859 private static final boolean hasManageUsersPermission() {
1860 final int callingUid = Binder.getCallingUid();
1861 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1862 || callingUid == Process.ROOT_UID
1863 || ActivityManager.checkComponentPermission(
1864 android.Manifest.permission.MANAGE_USERS,
1865 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1866 }
1867
1868 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001869 * @return whether the calling UID is system UID or root's UID or the calling app has the
1870 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1871 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1872 */
1873 private static final boolean hasManageOrCreateUsersPermission() {
1874 final int callingUid = Binder.getCallingUid();
1875 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1876 || callingUid == Process.ROOT_UID
1877 || ActivityManager.checkComponentPermission(
1878 android.Manifest.permission.MANAGE_USERS,
1879 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1880 || ActivityManager.checkComponentPermission(
1881 android.Manifest.permission.CREATE_USERS,
1882 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1883 }
1884
1885 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001886 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1887 * UserManager.
1888 *
1889 * @param message used as message if SecurityException is thrown
1890 * @throws SecurityException if the caller is not system or root
1891 */
1892 private static void checkSystemOrRoot(String message) {
1893 final int uid = Binder.getCallingUid();
1894 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1895 throw new SecurityException("Only system may: " + message);
1896 }
1897 }
1898
Fyodor Kupolov82402752015-10-28 14:54:51 -07001899 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001900 try {
1901 File dir = new File(mUsersDir, Integer.toString(info.id));
1902 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001903 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001904 if (!dir.exists()) {
1905 dir.mkdir();
1906 FileUtils.setPermissions(
1907 dir.getPath(),
1908 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1909 -1, -1);
1910 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001911 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001912 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001913 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001914 info.iconPath = file.getAbsolutePath();
1915 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001916 try {
1917 os.close();
1918 } catch (IOException ioe) {
1919 // What the ... !
1920 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001921 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001922 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001923 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001924 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001925 }
1926
Amith Yamasani0b285492011-04-14 17:35:23 -07001927 /**
1928 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1929 * cache it elsewhere.
1930 * @return the array of user ids.
1931 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001932 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001933 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001934 return mUserIds;
1935 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001936 }
1937
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001938 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001939 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001940 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001941 return;
1942 }
1943 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001944 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001945 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001946 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001947 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001948 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001949 int type;
1950 while ((type = parser.next()) != XmlPullParser.START_TAG
1951 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001952 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001953 }
1954
1955 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001956 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001957 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001958 return;
1959 }
1960
Amith Yamasani2a003292012-08-14 18:25:45 -07001961 mNextSerialNumber = -1;
1962 if (parser.getName().equals(TAG_USERS)) {
1963 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1964 if (lastSerialNumber != null) {
1965 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1966 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001967 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1968 if (versionNumber != null) {
1969 mUserVersion = Integer.parseInt(versionNumber);
1970 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001971 }
1972
Pavel Grafov6a40f092016-10-25 15:46:51 +01001973 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1974 // currently), take care of it in case of upgrade.
1975 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001976
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001977 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301978 if (type == XmlPullParser.START_TAG) {
1979 final String name = parser.getName();
1980 if (name.equals(TAG_USER)) {
1981 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001982
Amith Yamasani12747872015-12-07 14:19:49 -08001983 UserData userData = readUserLP(Integer.parseInt(id));
1984
1985 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001986 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001987 mUsers.put(userData.info.id, userData);
1988 if (mNextSerialNumber < 0
1989 || mNextSerialNumber <= userData.info.id) {
1990 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001991 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301992 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001993 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301994 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001995 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1996 && type != XmlPullParser.END_TAG) {
1997 if (type == XmlPullParser.START_TAG) {
1998 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001999 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002000 UserRestrictionsUtils
2001 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002002 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002003 }
2004 break;
2005 }
2006 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002007 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2008 // Legacy name, should only be encountered when upgrading from pre-O.
2009 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002010 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2011 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002012 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002013 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002014 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2015 // Should only happen when upgrading from pre-O (version < 7).
2016 oldDevicePolicyGlobalUserRestrictions =
2017 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002018 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002019 }
2020 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002021
Fyodor Kupolov82402752015-10-28 14:54:51 -07002022 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002023 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002024 } catch (IOException | XmlPullParserException e) {
2025 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002026 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002027 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002028 }
2029 }
2030
Amith Yamasani6f34b412012-10-22 18:19:27 -07002031 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002032 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002033 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002034 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01002035 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002036 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002037 int userVersion = mUserVersion;
2038 if (userVersion < 1) {
2039 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002040 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2041 if ("Primary".equals(userData.info.name)) {
2042 userData.info.name =
2043 mContext.getResources().getString(com.android.internal.R.string.owner_name);
2044 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002045 }
2046 userVersion = 1;
2047 }
2048
Amith Yamasanibc9625052012-11-15 14:39:18 -08002049 if (userVersion < 2) {
2050 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002051 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2052 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2053 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2054 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002055 }
2056 userVersion = 2;
2057 }
2058
Amith Yamasani350962c2013-08-06 11:18:53 -07002059
Amith Yamasani5e486f52013-08-07 11:06:44 -07002060 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002061 userVersion = 4;
2062 }
2063
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002064 if (userVersion < 5) {
2065 initDefaultGuestRestrictions();
2066 userVersion = 5;
2067 }
2068
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002069 if (userVersion < 6) {
2070 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002071 synchronized (mUsersLock) {
2072 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002073 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002074 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002075 if (!splitSystemUser && userData.info.isRestricted()
2076 && (userData.info.restrictedProfileParentId
2077 == UserInfo.NO_PROFILE_GROUP_ID)) {
2078 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2079 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002080 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002081 }
2082 }
2083 userVersion = 6;
2084 }
2085
Pavel Grafov6a40f092016-10-25 15:46:51 +01002086 if (userVersion < 7) {
2087 // Previously only one user could enforce global restrictions, now it is per-user.
2088 synchronized (mRestrictionsLock) {
2089 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2090 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2091 mDevicePolicyGlobalUserRestrictions.put(
2092 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2093 }
2094 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2095 // it from local to global bundle for all users who set it.
2096 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2097 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2098 );
2099 }
2100 userVersion = 7;
2101 }
2102
Amith Yamasani6f34b412012-10-22 18:19:27 -07002103 if (userVersion < USER_VERSION) {
2104 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2105 + USER_VERSION);
2106 } else {
2107 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002108
2109 if (originalVersion < mUserVersion) {
2110 writeUserListLP();
2111 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002112 }
2113 }
2114
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002115 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002116 int flags = UserInfo.FLAG_INITIALIZED;
2117 // In split system user mode, the admin and primary flags are assigned to the first human
2118 // user.
2119 if (!UserManager.isSplitSystemUser()) {
2120 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2121 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002122 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002123 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002124 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002125 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002126 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002127
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002128 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002129 try {
2130 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2131 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2132 for (String userRestriction : defaultFirstUserRestrictions) {
2133 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2134 restrictions.putBoolean(userRestriction, true);
2135 }
2136 }
2137 } catch (Resources.NotFoundException e) {
2138 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2139 }
2140
Pavel Grafov6a40f092016-10-25 15:46:51 +01002141 if (!restrictions.isEmpty()) {
2142 synchronized (mRestrictionsLock) {
2143 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2144 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002145 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002146
Fyodor Kupolov82402752015-10-28 14:54:51 -07002147 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002148 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002149
Amith Yamasani12747872015-12-07 14:19:49 -08002150 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002151 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002152 }
2153
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002154 private String getOwnerName() {
2155 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2156 }
2157
Amith Yamasani12747872015-12-07 14:19:49 -08002158 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002159 if (DBG) {
2160 debug("scheduleWriteUser");
2161 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002162 // No need to wrap it within a lock -- worst case, we'll just post the same message
2163 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002164 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2165 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002166 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2167 }
2168 }
2169
Amith Yamasani12747872015-12-07 14:19:49 -08002170 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002171 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002172 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002173 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002174 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002175 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002176 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002177 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002178 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002179 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002180 userFile.finishWrite(fos);
2181 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002182 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002183 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002184 }
2185 }
2186
2187 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002188 * Writes the user file in this format:
2189 *
2190 * <user flags="20039023" id="0">
2191 * <name>Primary</name>
2192 * </user>
2193 */
2194 @VisibleForTesting
2195 void writeUserLP(UserData userData, OutputStream os)
2196 throws IOException, XmlPullParserException {
2197 // XmlSerializer serializer = XmlUtils.serializerInstance();
2198 final XmlSerializer serializer = new FastXmlSerializer();
2199 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2200 serializer.startDocument(null, true);
2201 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2202
2203 final UserInfo userInfo = userData.info;
2204 serializer.startTag(null, TAG_USER);
2205 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2206 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2207 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2208 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2209 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2210 Long.toString(userInfo.lastLoggedInTime));
2211 if (userInfo.lastLoggedInFingerprint != null) {
2212 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2213 userInfo.lastLoggedInFingerprint);
2214 }
2215 if (userInfo.iconPath != null) {
2216 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2217 }
2218 if (userInfo.partial) {
2219 serializer.attribute(null, ATTR_PARTIAL, "true");
2220 }
2221 if (userInfo.guestToRemove) {
2222 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2223 }
2224 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2225 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2226 Integer.toString(userInfo.profileGroupId));
2227 }
2228 serializer.attribute(null, ATTR_PROFILE_BADGE,
2229 Integer.toString(userInfo.profileBadge));
2230 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2231 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2232 Integer.toString(userInfo.restrictedProfileParentId));
2233 }
2234 // Write seed data
2235 if (userData.persistSeedData) {
2236 if (userData.seedAccountName != null) {
2237 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2238 }
2239 if (userData.seedAccountType != null) {
2240 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2241 }
2242 }
2243 if (userInfo.name != null) {
2244 serializer.startTag(null, TAG_NAME);
2245 serializer.text(userInfo.name);
2246 serializer.endTag(null, TAG_NAME);
2247 }
2248 synchronized (mRestrictionsLock) {
2249 UserRestrictionsUtils.writeRestrictions(serializer,
2250 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2251 UserRestrictionsUtils.writeRestrictions(serializer,
2252 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2253 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002254 UserRestrictionsUtils.writeRestrictions(serializer,
2255 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2256 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002257 }
2258
2259 if (userData.account != null) {
2260 serializer.startTag(null, TAG_ACCOUNT);
2261 serializer.text(userData.account);
2262 serializer.endTag(null, TAG_ACCOUNT);
2263 }
2264
2265 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2266 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2267 userData.seedAccountOptions.saveToXml(serializer);
2268 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2269 }
2270
2271 serializer.endTag(null, TAG_USER);
2272
2273 serializer.endDocument();
2274 }
2275
2276 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002277 * Writes the user list file in this format:
2278 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002279 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002280 * <user id="0"></user>
2281 * <user id="2"></user>
2282 * </users>
2283 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002284 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002285 if (DBG) {
2286 debug("writeUserList");
2287 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002288 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002289 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002290 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002291 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002292 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2293
2294 // XmlSerializer serializer = XmlUtils.serializerInstance();
2295 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002296 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002297 serializer.startDocument(null, true);
2298 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2299
2300 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002301 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002302 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002303
Adam Lesinskieddeb492014-09-08 17:50:03 -07002304 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002305 synchronized (mGuestRestrictions) {
2306 UserRestrictionsUtils
2307 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2308 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302309 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002310 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2311 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2312 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002313 int[] userIdsToWrite;
2314 synchronized (mUsersLock) {
2315 userIdsToWrite = new int[mUsers.size()];
2316 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002317 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002318 userIdsToWrite[i] = user.id;
2319 }
2320 }
2321 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002322 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002323 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002324 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002325 }
2326
2327 serializer.endTag(null, TAG_USERS);
2328
2329 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002330 userListFile.finishWrite(fos);
2331 } catch (Exception e) {
2332 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002333 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002334 }
2335 }
2336
Amith Yamasani12747872015-12-07 14:19:49 -08002337 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002338 FileInputStream fis = null;
2339 try {
2340 AtomicFile userFile =
2341 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2342 fis = userFile.openRead();
2343 return readUserLP(id, fis);
2344 } catch (IOException ioe) {
2345 Slog.e(LOG_TAG, "Error reading user list");
2346 } catch (XmlPullParserException pe) {
2347 Slog.e(LOG_TAG, "Error reading user list");
2348 } finally {
2349 IoUtils.closeQuietly(fis);
2350 }
2351 return null;
2352 }
2353
2354 @VisibleForTesting
2355 UserData readUserLP(int id, InputStream is) throws IOException,
2356 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002357 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002358 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002359 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002360 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002361 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002362 long creationTime = 0L;
2363 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002364 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002365 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002366 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002367 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002368 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002369 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002370 boolean persistSeedData = false;
2371 String seedAccountName = null;
2372 String seedAccountType = null;
2373 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002374 Bundle baseRestrictions = null;
2375 Bundle localRestrictions = null;
2376 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002377
Kenny Guy02c89902016-11-15 19:36:38 +00002378 XmlPullParser parser = Xml.newPullParser();
2379 parser.setInput(is, StandardCharsets.UTF_8.name());
2380 int type;
2381 while ((type = parser.next()) != XmlPullParser.START_TAG
2382 && type != XmlPullParser.END_DOCUMENT) {
2383 // Skip
2384 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002385
Kenny Guy02c89902016-11-15 19:36:38 +00002386 if (type != XmlPullParser.START_TAG) {
2387 Slog.e(LOG_TAG, "Unable to read user " + id);
2388 return null;
2389 }
2390
2391 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2392 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2393 if (storedId != id) {
2394 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002395 return null;
2396 }
Kenny Guy02c89902016-11-15 19:36:38 +00002397 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2398 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2399 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2400 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2401 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2402 lastLoggedInFingerprint = parser.getAttributeValue(null,
2403 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2404 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2405 UserInfo.NO_PROFILE_GROUP_ID);
2406 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2407 restrictedProfileParentId = readIntAttribute(parser,
2408 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2409 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2410 if ("true".equals(valueString)) {
2411 partial = true;
2412 }
2413 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2414 if ("true".equals(valueString)) {
2415 guestToRemove = true;
2416 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002417
Kenny Guy02c89902016-11-15 19:36:38 +00002418 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2419 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2420 if (seedAccountName != null || seedAccountType != null) {
2421 persistSeedData = true;
2422 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002423
Kenny Guy02c89902016-11-15 19:36:38 +00002424 int outerDepth = parser.getDepth();
2425 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2426 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2427 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2428 continue;
2429 }
2430 String tag = parser.getName();
2431 if (TAG_NAME.equals(tag)) {
2432 type = parser.next();
2433 if (type == XmlPullParser.TEXT) {
2434 name = parser.getText();
2435 }
2436 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002437 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002438 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002439 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2440 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2441 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002442 } else if (TAG_ACCOUNT.equals(tag)) {
2443 type = parser.next();
2444 if (type == XmlPullParser.TEXT) {
2445 account = parser.getText();
2446 }
2447 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2448 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002449 persistSeedData = true;
2450 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002451 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002452 }
Kenny Guy02c89902016-11-15 19:36:38 +00002453
2454 // Create the UserInfo object that gets passed around
2455 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2456 userInfo.serialNumber = serialNumber;
2457 userInfo.creationTime = creationTime;
2458 userInfo.lastLoggedInTime = lastLoggedInTime;
2459 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2460 userInfo.partial = partial;
2461 userInfo.guestToRemove = guestToRemove;
2462 userInfo.profileGroupId = profileGroupId;
2463 userInfo.profileBadge = profileBadge;
2464 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2465
2466 // Create the UserData object that's internal to this class
2467 UserData userData = new UserData();
2468 userData.info = userInfo;
2469 userData.account = account;
2470 userData.seedAccountName = seedAccountName;
2471 userData.seedAccountType = seedAccountType;
2472 userData.persistSeedData = persistSeedData;
2473 userData.seedAccountOptions = seedAccountOptions;
2474
2475 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002476 if (baseRestrictions != null) {
2477 mBaseUserRestrictions.put(id, baseRestrictions);
2478 }
2479 if (localRestrictions != null) {
2480 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2481 }
2482 if (globalRestrictions != null) {
2483 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2484 }
Kenny Guy02c89902016-11-15 19:36:38 +00002485 }
2486 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002487 }
2488
Amith Yamasani920ace02012-09-20 22:15:37 -07002489 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2490 String valueString = parser.getAttributeValue(null, attr);
2491 if (valueString == null) return defaultValue;
2492 try {
2493 return Integer.parseInt(valueString);
2494 } catch (NumberFormatException nfe) {
2495 return defaultValue;
2496 }
2497 }
2498
2499 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2500 String valueString = parser.getAttributeValue(null, attr);
2501 if (valueString == null) return defaultValue;
2502 try {
2503 return Long.parseLong(valueString);
2504 } catch (NumberFormatException nfe) {
2505 return defaultValue;
2506 }
2507 }
2508
Amith Yamasanib82add22013-07-09 11:24:44 -07002509 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002510 * Removes the app restrictions file for a specific package and user id, if it exists.
2511 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002512 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2513 File dir = Environment.getUserSystemDirectory(userId);
2514 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2515 if (resFile.exists()) {
2516 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002517 }
2518 }
2519
Kenny Guya52dc3e2014-02-11 15:33:14 +00002520 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002521 public UserInfo createProfileForUser(String name, int flags, int userId,
2522 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002523 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002524 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002525 }
2526
Amith Yamasani258848d2012-08-10 17:06:33 -07002527 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002528 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2529 String[] disallowedPackages) {
2530 checkManageOrCreateUsersPermission(flags);
2531 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2532 }
2533
2534 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002535 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2536 checkManageOrCreateUsersPermission("Only the system can remove users");
2537 return removeUserUnchecked(userHandle);
2538 }
2539
2540 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002541 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002542 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002543 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002544 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002545
Jessica Hummelbe81c802014-04-22 15:49:22 +01002546 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002547 return createUserInternal(name, flags, parentId, null);
2548 }
2549
2550 private UserInfo createUserInternal(String name, int flags, int parentId,
2551 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002552 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2553 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2554 : UserManager.DISALLOW_ADD_USER;
2555 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2556 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002557 return null;
2558 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002559 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2560 }
2561
2562 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2563 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002564 DeviceStorageMonitorInternal dsm = LocalServices
2565 .getService(DeviceStorageMonitorInternal.class);
2566 if (dsm.isMemoryLow()) {
2567 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2568 return null;
2569 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002570 if (ActivityManager.isLowRamDeviceStatic()) {
2571 return null;
2572 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002573 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002574 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002575 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002576 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002577 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002578 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002579 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002580 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002581 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002582 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002583 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002584 if (parentId != UserHandle.USER_NULL) {
2585 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002586 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002587 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002588 if (parent == null) return null;
2589 }
2590 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2591 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2592 return null;
2593 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002594 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2595 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002596 // been reached, cannot add a user.
2597 return null;
2598 }
2599 // If we're adding a guest and there already exists one, bail.
2600 if (isGuest && findCurrentGuestUser() != null) {
2601 return null;
2602 }
2603 // In legacy mode, restricted profile's parent can only be the owner user
2604 if (isRestricted && !UserManager.isSplitSystemUser()
2605 && (parentId != UserHandle.USER_SYSTEM)) {
2606 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2607 return null;
2608 }
2609 if (isRestricted && UserManager.isSplitSystemUser()) {
2610 if (parent == null) {
2611 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2612 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002613 return null;
2614 }
Amith Yamasani12747872015-12-07 14:19:49 -08002615 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002616 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2617 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002618 return null;
2619 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002620 }
2621 // In split system user mode, we assign the first human user the primary flag.
2622 // And if there is no device owner, we also assign the admin flag to primary user.
2623 if (UserManager.isSplitSystemUser()
2624 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2625 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002626 synchronized (mUsersLock) {
2627 if (!mIsDeviceManaged) {
2628 flags |= UserInfo.FLAG_ADMIN;
2629 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002630 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002631 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002632
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002633 userId = getNextAvailableId();
2634 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002635 boolean ephemeralGuests = Resources.getSystem()
2636 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002637
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002638 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002639 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2640 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2641 || (parent != null && parent.info.isEphemeral())) {
2642 flags |= UserInfo.FLAG_EPHEMERAL;
2643 }
2644
2645 userInfo = new UserInfo(userId, name, null, flags);
2646 userInfo.serialNumber = mNextSerialNumber++;
2647 long now = System.currentTimeMillis();
2648 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2649 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002650 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002651 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2652 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2653 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002654 userData = new UserData();
2655 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002656 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002657 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002658 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002659 writeUserListLP();
2660 if (parent != null) {
2661 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002662 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2663 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002664 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002665 }
Amith Yamasani12747872015-12-07 14:19:49 -08002666 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002667 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002668 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2669 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002670 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002671 }
Amith Yamasani12747872015-12-07 14:19:49 -08002672 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002673 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002674 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002675 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002676 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002677 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002678 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002679 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002680 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002681 userInfo.partial = false;
2682 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002683 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002684 }
2685 updateUserIds();
2686 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002687 if (isGuest) {
2688 synchronized (mGuestRestrictions) {
2689 restrictions.putAll(mGuestRestrictions);
2690 }
2691 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002692 synchronized (mRestrictionsLock) {
2693 mBaseUserRestrictions.append(userId, restrictions);
2694 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002695 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002696 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2697 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2698 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2699 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002700 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2701 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002702 } finally {
2703 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002704 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002705 return userInfo;
2706 }
2707
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002708 @VisibleForTesting
2709 UserData putUserInfo(UserInfo userInfo) {
2710 final UserData userData = new UserData();
2711 userData.info = userInfo;
2712 synchronized (mUsers) {
2713 mUsers.put(userInfo.id, userData);
2714 }
2715 return userData;
2716 }
2717
2718 @VisibleForTesting
2719 void removeUserInfo(int userId) {
2720 synchronized (mUsers) {
2721 mUsers.remove(userId);
2722 }
2723 }
2724
Amith Yamasani0b285492011-04-14 17:35:23 -07002725 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002726 * @hide
2727 */
Amith Yamasani12747872015-12-07 14:19:49 -08002728 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002729 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002730 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002731 final UserInfo user = createProfileForUser(
2732 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002733 if (user == null) {
2734 return null;
2735 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002736 long identity = Binder.clearCallingIdentity();
2737 try {
2738 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2739 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2740 // the putIntForUser() will fail.
2741 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2742 android.provider.Settings.Secure.LOCATION_MODE,
2743 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2744 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2745 } finally {
2746 Binder.restoreCallingIdentity(identity);
2747 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002748 return user;
2749 }
2750
2751 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002752 * Find the current guest user. If the Guest user is partial,
2753 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002754 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002755 private UserInfo findCurrentGuestUser() {
2756 synchronized (mUsersLock) {
2757 final int size = mUsers.size();
2758 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002759 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002760 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2761 return user;
2762 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002763 }
2764 }
2765 return null;
2766 }
2767
2768 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002769 * Mark this guest user for deletion to allow us to create another guest
2770 * and switch to that user before actually removing this guest.
2771 * @param userHandle the userid of the current guest
2772 * @return whether the user could be marked for deletion
2773 */
Amith Yamasani12747872015-12-07 14:19:49 -08002774 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002775 public boolean markGuestForDeletion(int userHandle) {
2776 checkManageUsersPermission("Only the system can remove users");
2777 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2778 UserManager.DISALLOW_REMOVE_USER, false)) {
2779 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2780 return false;
2781 }
2782
2783 long ident = Binder.clearCallingIdentity();
2784 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002785 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002786 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002787 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002788 userData = mUsers.get(userHandle);
2789 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002790 return false;
2791 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002792 }
Amith Yamasani12747872015-12-07 14:19:49 -08002793 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002794 return false;
2795 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002796 // We set this to a guest user that is to be removed. This is a temporary state
2797 // where we are allowed to add new Guest users, even if this one is still not
2798 // removed. This user will still show up in getUserInfo() calls.
2799 // If we don't get around to removing this Guest user, it will be purged on next
2800 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002801 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002802 // Mark it as disabled, so that it isn't returned any more when
2803 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002804 userData.info.flags |= UserInfo.FLAG_DISABLED;
2805 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002806 }
2807 } finally {
2808 Binder.restoreCallingIdentity(ident);
2809 }
2810 return true;
2811 }
2812
2813 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002814 * Removes a user and all data directories created for that user. This method should be called
2815 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002816 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002817 */
Amith Yamasani12747872015-12-07 14:19:49 -08002818 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002819 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002820 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002821 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002822
2823 final boolean isManagedProfile;
2824 synchronized (mUsersLock) {
2825 UserInfo userInfo = getUserInfoLU(userHandle);
2826 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2827 }
2828 String restriction = isManagedProfile
2829 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2830 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2831 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002832 return false;
2833 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002834 return removeUserUnchecked(userHandle);
2835 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002836
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002837 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002838 long ident = Binder.clearCallingIdentity();
2839 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002840 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002841 int currentUser = ActivityManager.getCurrentUser();
2842 if (currentUser == userHandle) {
2843 Log.w(LOG_TAG, "Current user cannot be removed");
2844 return false;
2845 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002846 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002847 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002848 userData = mUsers.get(userHandle);
2849 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002850 return false;
2851 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002852
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002853 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002854 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002855
Kenny Guyee58b4f2014-05-23 15:19:53 +01002856 // Set this to a partially created user, so that the user will be purged
2857 // on next startup, in case the runtime stops now before stopping and
2858 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002859 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002860 // Mark it as disabled, so that it isn't returned any more when
2861 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002862 userData.info.flags |= UserInfo.FLAG_DISABLED;
2863 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002864 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002865 try {
2866 mAppOpsService.removeUser(userHandle);
2867 } catch (RemoteException e) {
2868 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2869 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002870
Amith Yamasani12747872015-12-07 14:19:49 -08002871 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2872 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002873 // Send broadcast to notify system that the user removed was a
2874 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002875 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002876 }
2877
2878 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2879 int res;
2880 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002881 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002882 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002883 @Override
2884 public void userStopped(int userId) {
2885 finishRemoveUser(userId);
2886 }
2887 @Override
2888 public void userStopAborted(int userId) {
2889 }
2890 });
2891 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002892 return false;
2893 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002894 return res == ActivityManager.USER_OP_SUCCESS;
2895 } finally {
2896 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002897 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002898 }
2899
Andreas Gampea36dc622018-02-05 17:19:22 -08002900 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002901 @VisibleForTesting
2902 void addRemovingUserIdLocked(int userId) {
2903 // We remember deleted user IDs to prevent them from being
2904 // reused during the current boot; they can still be reused
2905 // after a reboot or recycling of userIds.
2906 mRemovingUserIds.put(userId, true);
2907 mRecentlyRemovedIds.add(userId);
2908 // Keep LRU queue of recently removed IDs for recycling
2909 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2910 mRecentlyRemovedIds.removeFirst();
2911 }
2912 }
2913
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002914 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002915 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002916 // Let other services shutdown any activity and clean up their state before completely
2917 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002918 long ident = Binder.clearCallingIdentity();
2919 try {
2920 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2921 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002922 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2923 android.Manifest.permission.MANAGE_USERS,
2924
2925 new BroadcastReceiver() {
2926 @Override
2927 public void onReceive(Context context, Intent intent) {
2928 if (DBG) {
2929 Slog.i(LOG_TAG,
2930 "USER_REMOVED broadcast sent, cleaning up user data "
2931 + userHandle);
2932 }
2933 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002934 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002935 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002936 // Clean up any ActivityManager state
2937 LocalServices.getService(ActivityManagerInternal.class)
2938 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002939 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002940 }
2941 }.start();
2942 }
2943 },
2944
2945 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002946 } finally {
2947 Binder.restoreCallingIdentity(ident);
2948 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002949 }
2950
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002951 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002952 try {
2953 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2954 } catch (IllegalStateException e) {
2955 // This may be simply because the user was partially created.
2956 Slog.i(LOG_TAG,
2957 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2958 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002959
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002960 // Cleanup gatekeeper secure user id
2961 try {
2962 final IGateKeeperService gk = GateKeeper.getService();
2963 if (gk != null) {
2964 gk.clearSecureUserId(userHandle);
2965 }
2966 } catch (Exception ex) {
2967 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2968 }
2969
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002970 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002971 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002972
2973 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002974 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002975 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2976
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002977 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002978 synchronized (mUsersLock) {
2979 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002980 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002981 }
2982 synchronized (mUserStates) {
2983 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002984 }
2985 synchronized (mRestrictionsLock) {
2986 mBaseUserRestrictions.remove(userHandle);
2987 mAppliedUserRestrictions.remove(userHandle);
2988 mCachedEffectiveUserRestrictions.remove(userHandle);
2989 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002990 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2991 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2992 applyUserRestrictionsForAllUsersLR();
2993 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002994 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002995 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002996 synchronized (mPackagesLock) {
2997 writeUserListLP();
2998 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002999 // Remove user file
3000 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3001 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003002 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003003 if (RELEASE_DELETED_USER_ID) {
3004 synchronized (mUsers) {
3005 mRemovingUserIds.delete(userHandle);
3006 }
3007 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003008 }
3009
Kenny Guyf8d3a232014-05-15 16:09:52 +01003010 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003011 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003012 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3013 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003014 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003015 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003016 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003017 }
3018
Amith Yamasani2a003292012-08-14 18:25:45 -07003019 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003020 public Bundle getApplicationRestrictions(String packageName) {
3021 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3022 }
3023
3024 @Override
3025 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003026 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003027 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003028 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003029 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003030 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003031 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003032 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003033 }
3034 }
3035
3036 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003037 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003038 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003039 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003040 if (restrictions != null) {
3041 restrictions.setDefusable(true);
3042 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003043 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003044 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003045 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003046 } else {
3047 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003048 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003049 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003050 }
Robin Lee66e5d962014-04-09 16:44:21 +01003051
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003052 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3053 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3054 changeIntent.setPackage(packageName);
3055 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3056 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003057 }
3058
3059 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003060 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003061 try {
3062 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003063 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003064 } catch (NameNotFoundException nnfe) {
3065 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003066 } finally {
3067 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003068 }
3069 }
3070
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003071 @GuardedBy("mAppRestrictionsLock")
3072 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003073 AtomicFile restrictionsFile =
3074 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3075 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003076 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003077 }
3078
3079 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003080 @GuardedBy("mAppRestrictionsLock")
3081 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003082 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003083 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003084 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003085 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003086 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003087
3088 FileInputStream fis = null;
3089 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003090 fis = restrictionsFile.openRead();
3091 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003092 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003093 XmlUtils.nextElement(parser);
3094 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003095 Slog.e(LOG_TAG, "Unable to read restrictions file "
3096 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003097 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003098 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003099 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3100 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003101 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003102 } catch (IOException|XmlPullParserException e) {
3103 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003104 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003105 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003106 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003107 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003108 }
3109
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003110 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3111 XmlPullParser parser) throws XmlPullParserException, IOException {
3112 int type = parser.getEventType();
3113 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3114 String key = parser.getAttributeValue(null, ATTR_KEY);
3115 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3116 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3117 if (multiple != null) {
3118 values.clear();
3119 int count = Integer.parseInt(multiple);
3120 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3121 if (type == XmlPullParser.START_TAG
3122 && parser.getName().equals(TAG_VALUE)) {
3123 values.add(parser.nextText().trim());
3124 count--;
3125 }
3126 }
3127 String [] valueStrings = new String[values.size()];
3128 values.toArray(valueStrings);
3129 restrictions.putStringArray(key, valueStrings);
3130 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3131 restrictions.putBundle(key, readBundleEntry(parser, values));
3132 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3133 final int outerDepth = parser.getDepth();
3134 ArrayList<Bundle> bundleList = new ArrayList<>();
3135 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3136 Bundle childBundle = readBundleEntry(parser, values);
3137 bundleList.add(childBundle);
3138 }
3139 restrictions.putParcelableArray(key,
3140 bundleList.toArray(new Bundle[bundleList.size()]));
3141 } else {
3142 String value = parser.nextText().trim();
3143 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3144 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3145 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3146 restrictions.putInt(key, Integer.parseInt(value));
3147 } else {
3148 restrictions.putString(key, value);
3149 }
3150 }
3151 }
3152 }
3153
3154 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3155 throws IOException, XmlPullParserException {
3156 Bundle childBundle = new Bundle();
3157 final int outerDepth = parser.getDepth();
3158 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3159 readEntry(childBundle, values, parser);
3160 }
3161 return childBundle;
3162 }
3163
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003164 @GuardedBy("mAppRestrictionsLock")
3165 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003166 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003167 AtomicFile restrictionsFile = new AtomicFile(
3168 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003169 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003170 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003171 }
3172
3173 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003174 @GuardedBy("mAppRestrictionsLock")
3175 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003176 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003177 try {
3178 fos = restrictionsFile.startWrite();
3179 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3180
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003181 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003182 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003183 serializer.startDocument(null, true);
3184 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3185
3186 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003187 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003188 serializer.endTag(null, TAG_RESTRICTIONS);
3189
3190 serializer.endDocument();
3191 restrictionsFile.finishWrite(fos);
3192 } catch (Exception e) {
3193 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003194 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3195 }
3196 }
3197
3198 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3199 throws IOException {
3200 for (String key : restrictions.keySet()) {
3201 Object value = restrictions.get(key);
3202 serializer.startTag(null, TAG_ENTRY);
3203 serializer.attribute(null, ATTR_KEY, key);
3204
3205 if (value instanceof Boolean) {
3206 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3207 serializer.text(value.toString());
3208 } else if (value instanceof Integer) {
3209 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3210 serializer.text(value.toString());
3211 } else if (value == null || value instanceof String) {
3212 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3213 serializer.text(value != null ? (String) value : "");
3214 } else if (value instanceof Bundle) {
3215 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3216 writeBundle((Bundle) value, serializer);
3217 } else if (value instanceof Parcelable[]) {
3218 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3219 Parcelable[] array = (Parcelable[]) value;
3220 for (Parcelable parcelable : array) {
3221 if (!(parcelable instanceof Bundle)) {
3222 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3223 }
3224 serializer.startTag(null, TAG_ENTRY);
3225 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3226 writeBundle((Bundle) parcelable, serializer);
3227 serializer.endTag(null, TAG_ENTRY);
3228 }
3229 } else {
3230 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3231 String[] values = (String[]) value;
3232 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3233 for (String choice : values) {
3234 serializer.startTag(null, TAG_VALUE);
3235 serializer.text(choice != null ? choice : "");
3236 serializer.endTag(null, TAG_VALUE);
3237 }
3238 }
3239 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003240 }
3241 }
3242
3243 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003244 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003245 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003246 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003247 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003248 }
3249 }
3250
3251 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003252 public boolean isUserNameSet(int userHandle) {
3253 synchronized (mUsersLock) {
3254 UserInfo userInfo = getUserInfoLU(userHandle);
3255 return userInfo != null && userInfo.name != null;
3256 }
3257 }
3258
3259 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003260 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003261 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003262 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003263 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003264 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003265 }
3266 // Not found
3267 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003268 }
3269 }
3270
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003271 @Override
3272 public long getUserCreationTime(int userHandle) {
3273 int callingUserId = UserHandle.getCallingUserId();
3274 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003275 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003276 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003277 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003278 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003279 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003280 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003281 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003282 }
3283 }
3284 }
3285 if (userInfo == null) {
3286 throw new SecurityException("userHandle can only be the calling user or a managed "
3287 + "profile associated with this user");
3288 }
3289 return userInfo.creationTime;
3290 }
3291
Amith Yamasani0b285492011-04-14 17:35:23 -07003292 /**
3293 * Caches the list of user ids in an array, adjusting the array size when necessary.
3294 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003295 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003296 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003297 synchronized (mUsersLock) {
3298 final int userSize = mUsers.size();
3299 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003300 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003301 num++;
3302 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003303 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003304 final int[] newUsers = new int[num];
3305 int n = 0;
3306 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003307 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003308 newUsers[n++] = mUsers.keyAt(i);
3309 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003310 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003311 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003312 }
3313 }
3314
3315 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003316 * Called right before a user is started. This gives us a chance to prepare
3317 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003318 */
3319 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003320 UserInfo userInfo = getUserInfo(userId);
3321 if (userInfo == null) {
3322 return;
3323 }
3324 final int userSerial = userInfo.serialNumber;
3325 // Migrate only if build fingerprints mismatch
3326 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003327 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003328 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003329
3330 if (userId != UserHandle.USER_SYSTEM) {
3331 synchronized (mRestrictionsLock) {
3332 applyUserRestrictionsLR(userId);
3333 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003334 }
3335 }
3336
3337 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003338 * Called right before a user is unlocked. This gives us a chance to prepare
3339 * app storage.
3340 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003341 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003342 UserInfo userInfo = getUserInfo(userId);
3343 if (userInfo == null) {
3344 return;
3345 }
3346 final int userSerial = userInfo.serialNumber;
3347 // Migrate only if build fingerprints mismatch
3348 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003349 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003350 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003351 }
3352
3353 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003354 * Examine all users present on given mounted volume, and destroy data
3355 * belonging to users that are no longer valid, or whose user ID has been
3356 * recycled.
3357 */
3358 void reconcileUsers(String volumeUuid) {
3359 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3360 }
3361
3362 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003363 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003364 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003365 * @param userId the user that was just foregrounded
3366 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003367 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003368 UserData userData = getUserDataNoChecks(userId);
3369 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003370 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3371 return;
3372 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003373
3374 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003375 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003376 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003377 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003378 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3379 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003380 }
3381
3382 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003383 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003384 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003385 @VisibleForTesting
3386 int getNextAvailableId() {
3387 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003388 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003389 nextId = scanNextAvailableIdLocked();
3390 if (nextId >= 0) {
3391 return nextId;
3392 }
3393 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3394 // except most recently removed
3395 if (mRemovingUserIds.size() > 0) {
3396 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3397 mRemovingUserIds.clear();
3398 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3399 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003400 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003401 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003402 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003403 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003404 if (nextId < 0) {
3405 throw new IllegalStateException("No user id available!");
3406 }
3407 return nextId;
3408 }
3409
Andreas Gampea36dc622018-02-05 17:19:22 -08003410 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003411 private int scanNextAvailableIdLocked() {
3412 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3413 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3414 return i;
3415 }
3416 }
3417 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003418 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003419
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003420 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003421 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3422 }
3423
Amith Yamasani920ace02012-09-20 22:15:37 -07003424 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003425 public void setSeedAccountData(int userId, String accountName, String accountType,
3426 PersistableBundle accountOptions, boolean persist) {
3427 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3428 synchronized (mPackagesLock) {
3429 final UserData userData;
3430 synchronized (mUsersLock) {
3431 userData = getUserDataLU(userId);
3432 if (userData == null) {
3433 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3434 return;
3435 }
3436 userData.seedAccountName = accountName;
3437 userData.seedAccountType = accountType;
3438 userData.seedAccountOptions = accountOptions;
3439 userData.persistSeedData = persist;
3440 }
3441 if (persist) {
3442 writeUserLP(userData);
3443 }
3444 }
3445 }
3446
3447 @Override
3448 public String getSeedAccountName() throws RemoteException {
3449 checkManageUsersPermission("Cannot get seed account information");
3450 synchronized (mUsersLock) {
3451 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3452 return userData.seedAccountName;
3453 }
3454 }
3455
3456 @Override
3457 public String getSeedAccountType() throws RemoteException {
3458 checkManageUsersPermission("Cannot get seed account information");
3459 synchronized (mUsersLock) {
3460 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3461 return userData.seedAccountType;
3462 }
3463 }
3464
3465 @Override
3466 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3467 checkManageUsersPermission("Cannot get seed account information");
3468 synchronized (mUsersLock) {
3469 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3470 return userData.seedAccountOptions;
3471 }
3472 }
3473
3474 @Override
3475 public void clearSeedAccountData() throws RemoteException {
3476 checkManageUsersPermission("Cannot clear seed account information");
3477 synchronized (mPackagesLock) {
3478 UserData userData;
3479 synchronized (mUsersLock) {
3480 userData = getUserDataLU(UserHandle.getCallingUserId());
3481 if (userData == null) return;
3482 userData.clearSeedAccountData();
3483 }
3484 writeUserLP(userData);
3485 }
3486 }
3487
3488 @Override
3489 public boolean someUserHasSeedAccount(String accountName, String accountType)
3490 throws RemoteException {
3491 checkManageUsersPermission("Cannot check seed account information");
3492 synchronized (mUsersLock) {
3493 final int userSize = mUsers.size();
3494 for (int i = 0; i < userSize; i++) {
3495 final UserData data = mUsers.valueAt(i);
3496 if (data.info.isInitialized()) continue;
3497 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3498 continue;
3499 }
3500 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3501 continue;
3502 }
3503 return true;
3504 }
3505 }
3506 return false;
3507 }
3508
3509 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003510 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003511 FileDescriptor err, String[] args, ShellCallback callback,
3512 ResultReceiver resultReceiver) {
3513 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003514 }
3515
3516 int onShellCommand(Shell shell, String cmd) {
3517 if (cmd == null) {
3518 return shell.handleDefaultCommands(cmd);
3519 }
3520
3521 final PrintWriter pw = shell.getOutPrintWriter();
3522 try {
3523 switch(cmd) {
3524 case "list":
3525 return runList(pw);
3526 }
3527 } catch (RemoteException e) {
3528 pw.println("Remote exception: " + e);
3529 }
3530 return -1;
3531 }
3532
3533 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003534 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003535 final List<UserInfo> users = getUsers(false);
3536 if (users == null) {
3537 pw.println("Error: couldn't get users");
3538 return 1;
3539 } else {
3540 pw.println("Users:");
3541 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003542 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003543 pw.println("\t" + users.get(i).toString() + running);
3544 }
3545 return 0;
3546 }
3547 }
3548
3549 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003550 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003551 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003552
3553 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003554 final long nowRealtime = SystemClock.elapsedRealtime();
Amith Yamasani920ace02012-09-20 22:15:37 -07003555 StringBuilder sb = new StringBuilder();
3556 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003557 synchronized (mUsersLock) {
3558 pw.println("Users:");
3559 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003560 UserData userData = mUsers.valueAt(i);
3561 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003562 continue;
3563 }
Amith Yamasani12747872015-12-07 14:19:49 -08003564 UserInfo userInfo = userData.info;
3565 final int userId = userInfo.id;
3566 pw.print(" "); pw.print(userInfo);
3567 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003568 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003569 pw.print(" <removing> ");
3570 }
Amith Yamasani12747872015-12-07 14:19:49 -08003571 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003572 pw.print(" <partial>");
3573 }
3574 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003575 pw.print(" State: ");
3576 final int state;
3577 synchronized (mUserStates) {
3578 state = mUserStates.get(userId, -1);
3579 }
3580 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003581 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003582 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3583
Fyodor Kupolov82402752015-10-28 14:54:51 -07003584 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003585 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3586
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003587 pw.print(" Last logged in fingerprint: ");
3588 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003589
3590 pw.print(" Start time: ");
3591 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3592
3593 pw.print(" Unlock time: ");
3594 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3595
Makoto Onukie7927da2015-11-25 10:05:17 -08003596 pw.print(" Has profile owner: ");
3597 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003598 pw.println(" Restrictions:");
3599 synchronized (mRestrictionsLock) {
3600 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003601 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003602 pw.println(" Device policy global restrictions:");
3603 UserRestrictionsUtils.dumpRestrictions(
3604 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003605 pw.println(" Device policy local restrictions:");
3606 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003607 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003608 pw.println(" Effective restrictions:");
3609 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003610 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003611 }
Amith Yamasani12747872015-12-07 14:19:49 -08003612
3613 if (userData.account != null) {
3614 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003615 pw.println();
3616 }
Amith Yamasani12747872015-12-07 14:19:49 -08003617
3618 if (userData.seedAccountName != null) {
3619 pw.print(" Seed account name: " + userData.seedAccountName);
3620 pw.println();
3621 if (userData.seedAccountType != null) {
3622 pw.print(" account type: " + userData.seedAccountType);
3623 pw.println();
3624 }
3625 if (userData.seedAccountOptions != null) {
3626 pw.print(" account options exist");
3627 pw.println();
3628 }
3629 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003630 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003631 }
Amith Yamasani12747872015-12-07 14:19:49 -08003632 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003633 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003634 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003635 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003636 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003637 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003638 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003639 synchronized (mUsersLock) {
3640 pw.println();
3641 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003642 if (mRemovingUserIds.size() > 0) {
3643 pw.println();
3644 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3645 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003646 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003647 synchronized (mUserStates) {
3648 pw.println(" Started users state: " + mUserStates);
3649 }
Amith Yamasani12747872015-12-07 14:19:49 -08003650 // Dump some capabilities
3651 pw.println();
3652 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3653 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003654 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3655 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003656 }
3657 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003658
Makoto Onuki73dded22017-12-20 13:14:48 +09003659 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3660 if (time == 0) {
3661 pw.println("<unknown>");
3662 } else {
3663 sb.setLength(0);
3664 TimeUtils.formatDuration(nowTime - time, sb);
3665 sb.append(" ago");
3666 pw.println(sb);
3667 }
3668 }
3669
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003670 final class MainHandler extends Handler {
3671
3672 @Override
3673 public void handleMessage(Message msg) {
3674 switch (msg.what) {
3675 case WRITE_USER_MSG:
3676 removeMessages(WRITE_USER_MSG, msg.obj);
3677 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003678 int userId = ((UserData) msg.obj).info.id;
3679 UserData userData = getUserDataNoChecks(userId);
3680 if (userData != null) {
3681 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003682 }
3683 }
3684 }
3685 }
3686 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003687
3688 /**
3689 * @param userId
3690 * @return whether the user has been initialized yet
3691 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003692 boolean isUserInitialized(int userId) {
3693 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003694 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003695
3696 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003697 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003698 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3699 boolean isDeviceOwner, int cameraRestrictionScope) {
3700 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3701 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003702 }
3703
3704 @Override
3705 public Bundle getBaseUserRestrictions(int userId) {
3706 synchronized (mRestrictionsLock) {
3707 return mBaseUserRestrictions.get(userId);
3708 }
3709 }
3710
3711 @Override
3712 public void setBaseUserRestrictionsByDpmsForMigration(
3713 int userId, Bundle baseRestrictions) {
3714 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003715 if (updateRestrictionsIfNeededLR(
3716 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3717 invalidateEffectiveUserRestrictionsLR(userId);
3718 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003719 }
3720
Amith Yamasani12747872015-12-07 14:19:49 -08003721 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003722 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003723 if (userData != null) {
3724 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003725 } else {
3726 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3727 }
3728 }
3729 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003730
3731 @Override
3732 public boolean getUserRestriction(int userId, String key) {
3733 return getUserRestrictions(userId).getBoolean(key);
3734 }
3735
3736 @Override
3737 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3738 synchronized (mUserRestrictionsListeners) {
3739 mUserRestrictionsListeners.add(listener);
3740 }
3741 }
3742
3743 @Override
3744 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3745 synchronized (mUserRestrictionsListeners) {
3746 mUserRestrictionsListeners.remove(listener);
3747 }
3748 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003749
3750 @Override
3751 public void setDeviceManaged(boolean isManaged) {
3752 synchronized (mUsersLock) {
3753 mIsDeviceManaged = isManaged;
3754 }
3755 }
3756
3757 @Override
3758 public void setUserManaged(int userId, boolean isManaged) {
3759 synchronized (mUsersLock) {
3760 mIsUserManaged.put(userId, isManaged);
3761 }
3762 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003763
3764 @Override
3765 public void setUserIcon(int userId, Bitmap bitmap) {
3766 long ident = Binder.clearCallingIdentity();
3767 try {
3768 synchronized (mPackagesLock) {
3769 UserData userData = getUserDataNoChecks(userId);
3770 if (userData == null || userData.info.partial) {
3771 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3772 return;
3773 }
3774 writeBitmapLP(userData.info, bitmap);
3775 writeUserLP(userData);
3776 }
3777 sendUserInfoChangedBroadcast(userId);
3778 } finally {
3779 Binder.restoreCallingIdentity(ident);
3780 }
3781 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003782
3783 @Override
3784 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3785 synchronized (mUsersLock) {
3786 mForceEphemeralUsers = forceEphemeralUsers;
3787 }
3788 }
3789
3790 @Override
3791 public void removeAllUsers() {
3792 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3793 // Remove the non-system users straight away.
3794 removeNonSystemUsers();
3795 } else {
3796 // Switch to the system user first and then remove the other users.
3797 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3798 @Override
3799 public void onReceive(Context context, Intent intent) {
3800 int userId =
3801 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3802 if (userId != UserHandle.USER_SYSTEM) {
3803 return;
3804 }
3805 mContext.unregisterReceiver(this);
3806 removeNonSystemUsers();
3807 }
3808 };
3809 IntentFilter userSwitchedFilter = new IntentFilter();
3810 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3811 mContext.registerReceiver(
3812 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3813
3814 // Switch to the system user.
3815 ActivityManager am =
3816 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3817 am.switchUser(UserHandle.USER_SYSTEM);
3818 }
3819 }
phweisse9c44062016-02-10 12:57:38 +01003820
3821 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003822 public void onEphemeralUserStop(int userId) {
3823 synchronized (mUsersLock) {
3824 UserInfo userInfo = getUserInfoLU(userId);
3825 if (userInfo != null && userInfo.isEphemeral()) {
3826 // Do not allow switching back to the ephemeral user again as the user is going
3827 // to be deleted.
3828 userInfo.flags |= UserInfo.FLAG_DISABLED;
3829 if (userInfo.isGuest()) {
3830 // Indicate that the guest will be deleted after it stops.
3831 userInfo.guestToRemove = true;
3832 }
3833 }
3834 }
3835 }
3836
3837 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003838 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3839 String[] disallowedPackages) {
3840 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3841 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003842 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003843 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003844 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3845 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3846 }
3847 return user;
3848 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003849
3850 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003851 public boolean removeUserEvenWhenDisallowed(int userId) {
3852 return removeUserUnchecked(userId);
3853 }
3854
3855 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003856 public boolean isUserRunning(int userId) {
3857 synchronized (mUserStates) {
3858 return mUserStates.get(userId, -1) >= 0;
3859 }
3860 }
3861
3862 @Override
3863 public void setUserState(int userId, int userState) {
3864 synchronized (mUserStates) {
3865 mUserStates.put(userId, userState);
3866 }
3867 }
3868
3869 @Override
3870 public void removeUserState(int userId) {
3871 synchronized (mUserStates) {
3872 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003873 }
3874 }
3875
3876 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003877 public int[] getUserIds() {
3878 return UserManagerService.this.getUserIds();
3879 }
3880
3881 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003882 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003883 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003884 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003885 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003886 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003887 // Special case, in the stopping/shutdown state user key can still be unlocked
3888 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3889 return StorageManager.isUserKeyUnlocked(userId);
3890 }
3891 return (state == UserState.STATE_RUNNING_UNLOCKING)
3892 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003893 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003894
3895 @Override
3896 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003897 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003898 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003899 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003900 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003901 // Special case, in the stopping/shutdown state user key can still be unlocked
3902 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3903 return StorageManager.isUserKeyUnlocked(userId);
3904 }
3905 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003906 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003907
3908 @Override
3909 public boolean isUserInitialized(int userId) {
3910 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3911 }
3912
3913 @Override
3914 public boolean exists(int userId) {
3915 return getUserInfoNoChecks(userId) != null;
3916 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003917 }
3918
3919 /* Remove all the users except of the system one. */
3920 private void removeNonSystemUsers() {
3921 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3922 synchronized (mUsersLock) {
3923 final int userSize = mUsers.size();
3924 for (int i = 0; i < userSize; i++) {
3925 UserInfo ui = mUsers.valueAt(i).info;
3926 if (ui.id != UserHandle.USER_SYSTEM) {
3927 usersToRemove.add(ui);
3928 }
3929 }
3930 }
3931 for (UserInfo ui: usersToRemove) {
3932 removeUser(ui.id);
3933 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003934 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003935
3936 private class Shell extends ShellCommand {
3937 @Override
3938 public int onCommand(String cmd) {
3939 return onShellCommand(this, cmd);
3940 }
3941
3942 @Override
3943 public void onHelp() {
3944 final PrintWriter pw = getOutPrintWriter();
3945 pw.println("User manager (user) commands:");
3946 pw.println(" help");
3947 pw.println(" Print this help text.");
3948 pw.println("");
3949 pw.println(" list");
3950 pw.println(" Prints all users on the system.");
3951 }
3952 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003953
3954 private static void debug(String message) {
3955 Log.d(LOG_TAG, message +
3956 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3957 }
Kenny Guy02c89902016-11-15 19:36:38 +00003958
3959 @VisibleForTesting
3960 static int getMaxManagedProfiles() {
3961 // Allow overriding max managed profiles on debuggable builds for testing
3962 // of multiple profiles.
3963 if (!Build.IS_DEBUGGABLE) {
3964 return MAX_MANAGED_PROFILES;
3965 } else {
3966 return SystemProperties.getInt("persist.sys.max_profiles",
3967 MAX_MANAGED_PROFILES);
3968 }
3969 }
3970
3971 @VisibleForTesting
3972 int getFreeProfileBadgeLU(int parentUserId) {
3973 int maxManagedProfiles = getMaxManagedProfiles();
3974 boolean[] usedBadges = new boolean[maxManagedProfiles];
3975 final int userSize = mUsers.size();
3976 for (int i = 0; i < userSize; i++) {
3977 UserInfo ui = mUsers.valueAt(i).info;
3978 // Check which badge indexes are already used by this profile group.
3979 if (ui.isManagedProfile()
3980 && ui.profileGroupId == parentUserId
3981 && !mRemovingUserIds.get(ui.id)
3982 && ui.profileBadge < maxManagedProfiles) {
3983 usedBadges[ui.profileBadge] = true;
3984 }
3985 }
3986 for (int i = 0; i < maxManagedProfiles; i++) {
3987 if (!usedBadges[i]) {
3988 return i;
3989 }
3990 }
3991 return 0;
3992 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003993
3994 /**
3995 * Checks if the given user has a managed profile associated with it.
3996 * @param userId The parent user
3997 * @return
3998 */
3999 boolean hasManagedProfile(int userId) {
4000 synchronized (mUsersLock) {
4001 UserInfo userInfo = getUserInfoLU(userId);
4002 final int userSize = mUsers.size();
4003 for (int i = 0; i < userSize; i++) {
4004 UserInfo profile = mUsers.valueAt(i).info;
4005 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4006 return true;
4007 }
4008 }
4009 return false;
4010 }
4011 }
Tony Makd390ae92017-12-28 13:23:10 +00004012
4013 /**
4014 * Check if the calling package name matches with the calling UID, throw
4015 * {@link SecurityException} if not.
4016 */
4017 private void verifyCallingPackage(String callingPackage, int callingUid) {
4018 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4019 if (packageUid != callingUid) {
4020 throw new SecurityException("Specified package " + callingPackage
4021 + " does not match the calling uid " + callingUid);
4022 }
4023 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004024}