blob: dc481ca11c7b31d7b0a5b879684521e5ad3d2399 [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;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010042import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070043import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060045import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080046import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080047import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.os.Environment;
49import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080051import android.os.IBinder;
Tony Mak64fd8c02017-12-01 19:11:59 +000052import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070053import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080054import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010055import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070056import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080057import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070058import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070059import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070060import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010061import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040062import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070063import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070064import android.os.ShellCommand;
Kenny Guy02c89902016-11-15 19:36:38 +000065import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070067import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010068import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080070import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010071import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070072import android.security.GateKeeper;
73import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani2a003292012-08-14 18:25:45 -070074import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070075import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070076import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import android.util.Slog;
78import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080079import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000080import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070081import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import android.util.Xml;
83
Makoto Onuki068c54a2015-10-13 14:34:03 -070084import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070085import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040086import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080087import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060088import com.android.internal.util.DumpUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080089import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070090import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070091import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000092import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070093import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060094import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070095import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000096import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070097import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +010098
Jeff Sharkey47f71082016-02-01 17:03:54 -070099import libcore.io.IoUtils;
100import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800101
102import org.xmlpull.v1.XmlPullParser;
103import org.xmlpull.v1.XmlPullParserException;
104import org.xmlpull.v1.XmlSerializer;
105
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106import java.io.BufferedOutputStream;
107import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700108import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700110import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000112import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000113import java.io.InputStream;
114import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700115import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100116import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100118import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700119import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120import java.util.List;
121
Makoto Onuki068c54a2015-10-13 14:34:03 -0700122/**
123 * Service for {@link UserManager}.
124 *
125 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700126 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700127 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800128 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700129 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
130 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
131 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700132 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700133public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700134
Amith Yamasani2a003292012-08-14 18:25:45 -0700135 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800136 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800137 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700138 // Can be used for manual testing of id recycling
139 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700140
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800142 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700144 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700146 private static final String ATTR_CREATION_TIME = "created";
147 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600148 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700149 private static final String ATTR_SERIAL_NO = "serialNumber";
150 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700151 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700152 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700153 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100154 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000155 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700156 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800157 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
158 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530159 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700160 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800162 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800163 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100164 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
165 "device_policy_global_restrictions";
166 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100167 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100168 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800169 private static final String TAG_ENTRY = "entry";
170 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800171 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800172 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700173 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800174 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700176 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
177 private static final String ATTR_TYPE_STRING = "s";
178 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700179 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700180 private static final String ATTR_TYPE_BUNDLE = "B";
181 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700182
Amith Yamasani0b285492011-04-14 17:35:23 -0700183 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700184 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700185 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100186 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800188 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700189 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800190
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700191 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
192 UserInfo.FLAG_MANAGED_PROFILE
193 | UserInfo.FLAG_EPHEMERAL
194 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700195 | UserInfo.FLAG_GUEST
196 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700197
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700198 @VisibleForTesting
199 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700200 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700201 @VisibleForTesting
202 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
203
204 // Max size of the queue of recently removed users
205 @VisibleForTesting
206 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700207
Pavel Grafov6a40f092016-10-25 15:46:51 +0100208 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700209
Amith Yamasani920ace02012-09-20 22:15:37 -0700210 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
211
Nicolas Prevotb8186812015-08-06 15:00:03 +0100212 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700213 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000214 @VisibleForTesting
215 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700216
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800217 static final int WRITE_USER_MSG = 1;
218 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530219
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800220 // Tron counters
221 private static final String TRON_GUEST_CREATED = "users_guest_created";
222 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700223 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800224
Dianne Hackborn4428e172012-08-24 17:43:05 -0700225 private final Context mContext;
226 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700227 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800228 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700229 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600230 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700231 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700232 // Used for serializing access to app restriction files
233 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700234
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800235 private final Handler mHandler;
236
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700237 private final File mUsersDir;
238 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700239
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800240 private static final IBinder mUserRestriconToken = new Binder();
241
Makoto Onuki068c54a2015-10-13 14:34:03 -0700242 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800243 * User-related information that is used for persisting to flash. Only UserInfo is
244 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800245 */
Kenny Guy02c89902016-11-15 19:36:38 +0000246 @VisibleForTesting
247 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800248 // Basic user information and properties
249 UserInfo info;
250 // Account name used when there is a strong association between a user and an account
251 String account;
252 // Account information for seeding into a newly created user. This could also be
253 // used for login validation for an existing user, for updating their credentials.
254 // In the latter case, data may not need to be persisted as it is only valid for the
255 // current login session.
256 String seedAccountName;
257 String seedAccountType;
258 PersistableBundle seedAccountOptions;
259 // Whether to perist the seed account information to be available after a boot
260 boolean persistSeedData;
261
262 void clearSeedAccountData() {
263 seedAccountName = null;
264 seedAccountType = null;
265 seedAccountOptions = null;
266 persistSeedData = false;
267 }
268 }
269
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800270 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800271 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800272
273 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700274 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100275 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700276 *
277 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
278 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
279 * maybe shared between {@link #mBaseUserRestrictions} and
280 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
281 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700282 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700283 */
284 @GuardedBy("mRestrictionsLock")
285 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
286
287 /**
288 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
289 * with device / profile owner restrictions. We'll initialize it lazily; use
290 * {@link #getEffectiveUserRestrictions} to access it.
291 *
292 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
293 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
294 * maybe shared between {@link #mBaseUserRestrictions} and
295 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
296 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700297 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700298 */
299 @GuardedBy("mRestrictionsLock")
300 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
301
Makoto Onuki4f160732015-10-27 17:15:38 -0700302 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800303 * User restrictions that have already been applied in
304 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
305 * that have changed since the last
306 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700307 */
308 @GuardedBy("mRestrictionsLock")
309 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
310
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800311 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800312 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100313 * that should be applied to all users, including guests. Only non-empty restriction bundles are
314 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800315 */
316 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100317 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800318
319 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100320 * Id of the user that set global restrictions.
321 */
322 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100323 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100324
325 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800326 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100327 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800328 */
329 @GuardedBy("mRestrictionsLock")
330 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
331
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800332 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530333 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800334
335 /**
336 * Set of user IDs being actively removed. Removed IDs linger in this set
337 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700338 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800339 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700340 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800341 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700342
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700343 /**
344 * Queue of recently removed userIds. Used for recycling of userIds
345 */
346 @GuardedBy("mUsersLock")
347 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
348
Fyodor Kupolov82402752015-10-28 14:54:51 -0700349 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700350 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800351 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700352 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700353 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700354
Jason Monk62062992014-05-06 09:55:28 -0400355 private IAppOpsService mAppOpsService;
356
Makoto Onuki068c54a2015-10-13 14:34:03 -0700357 private final LocalService mLocalService;
358
Makoto Onukie7927da2015-11-25 10:05:17 -0800359 @GuardedBy("mUsersLock")
360 private boolean mIsDeviceManaged;
361
362 @GuardedBy("mUsersLock")
363 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
364
Makoto Onukid45a4a22015-11-02 17:17:38 -0800365 @GuardedBy("mUserRestrictionsListeners")
366 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
367 new ArrayList<>();
368
Clara Bayarria1771112015-12-18 16:29:18 +0000369 private final LockPatternUtils mLockPatternUtils;
370
Ricky Waib1dd80b2016-06-07 18:00:55 +0100371 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
372 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
373
374 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
375 @Override
376 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000377 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
378 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100379 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000380 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
381 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
382 setQuietModeEnabled(userHandle, false, target);
Ricky Waib1dd80b2016-06-07 18:00:55 +0100383 }
384 };
385
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100386 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000387 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
388 *
389 * @see {@link #trySetQuietModeDisabled(int, IntentSender)}
390 */
391 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
392 private final IntentSender mTarget;
393
394 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
395 Preconditions.checkNotNull(target);
396 mTarget = target;
397 }
398
399 @Override
400 public void onStarted(int id, Bundle extras) {}
401
402 @Override
403 public void onProgress(int id, int progress, Bundle extras) {}
404
405 @Override
406 public void onFinished(int id, Bundle extras) {
407 try {
408 mContext.startIntentSender(mTarget, null, 0, 0, 0);
409 } catch (IntentSender.SendIntentException e) {
410 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
411 }
412 }
413 }
414
415 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100416 * Whether all users should be created ephemeral.
417 */
418 @GuardedBy("mUsersLock")
419 private boolean mForceEphemeralUsers;
420
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000421 @GuardedBy("mUserStates")
422 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700423
Amith Yamasani258848d2012-08-10 17:06:33 -0700424 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700425
Dianne Hackborn4428e172012-08-24 17:43:05 -0700426 public static UserManagerService getInstance() {
427 synchronized (UserManagerService.class) {
428 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700429 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700430 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700431
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700432 public static class LifeCycle extends SystemService {
433
434 private UserManagerService mUms;
435
436 /**
437 * @param context
438 */
439 public LifeCycle(Context context) {
440 super(context);
441 }
442
443 @Override
444 public void onStart() {
445 mUms = UserManagerService.getInstance();
446 publishBinderService(Context.USER_SERVICE, mUms);
447 }
448
449 @Override
450 public void onBootPhase(int phase) {
451 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
452 mUms.cleanupPartialUsers();
453 }
454 }
455 }
456
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700457 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800458 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700459 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800460 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700461 }
462
Dianne Hackborn4428e172012-08-24 17:43:05 -0700463 /**
464 * Called by package manager to create the service. This is closely
465 * associated with the package manager, and the given lock is the
466 * package manager's own lock.
467 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800468 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
469 Object packagesLock) {
470 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700471 }
472
Dianne Hackborn4428e172012-08-24 17:43:05 -0700473 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800474 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700475 mContext = context;
476 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700477 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800478 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800479 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800480 synchronized (mPackagesLock) {
481 mUsersDir = new File(dataDir, USER_INFO_DIR);
482 mUsersDir.mkdirs();
483 // Make zeroth user directory, for services to migrate their files to that location
484 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
485 userZeroDir.mkdirs();
486 FileUtils.setPermissions(mUsersDir.toString(),
487 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
488 -1, -1);
489 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
490 initDefaultGuestRestrictions();
491 readUserListLP();
492 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700493 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700494 mLocalService = new LocalService();
495 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000496 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000497 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700498 }
499
500 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400501 mAppOpsService = IAppOpsService.Stub.asInterface(
502 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800503
504 synchronized (mRestrictionsLock) {
505 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400506 }
Samuel Tand9453b82016-03-14 15:57:02 -0700507
508 UserInfo currentGuestUser = findCurrentGuestUser();
509 if (currentGuestUser != null && !hasUserRestriction(
510 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
511 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
512 // to it, in case this guest was created in a previous version where this
513 // user restriction was not a default guest restriction.
514 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
515 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700516
Ricky Waib1dd80b2016-06-07 18:00:55 +0100517 mContext.registerReceiver(mDisableQuietModeCallback,
518 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
519 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700520 }
521
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700522 void cleanupPartialUsers() {
523 // Prune out any partially created, partially removed and ephemeral users.
524 ArrayList<UserInfo> partials = new ArrayList<>();
525 synchronized (mUsersLock) {
526 final int userSize = mUsers.size();
527 for (int i = 0; i < userSize; i++) {
528 UserInfo ui = mUsers.valueAt(i).info;
529 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
530 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700531 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700532 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700533 }
534 }
535 }
536 final int partialsSize = partials.size();
537 for (int i = 0; i < partialsSize; i++) {
538 UserInfo ui = partials.get(i);
539 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
540 + " (name=" + ui.name + ")");
541 removeUserState(ui.id);
542 }
543 }
544
Amith Yamasani258848d2012-08-10 17:06:33 -0700545 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800546 public String getUserAccount(int userId) {
547 checkManageUserAndAcrossUsersFullPermission("get user account");
548 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800549 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800550 }
551 }
552
553 @Override
554 public void setUserAccount(int userId, String accountName) {
555 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800556 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800557 synchronized (mPackagesLock) {
558 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800559 final UserData userData = mUsers.get(userId);
560 if (userData == null) {
561 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
562 return;
563 }
564 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800565 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800566 userData.account = accountName;
567 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800568 }
569 }
570
571 if (userToUpdate != null) {
572 writeUserLP(userToUpdate);
573 }
574 }
575 }
576
577 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700578 public UserInfo getPrimaryUser() {
579 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700580 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700581 final int userSize = mUsers.size();
582 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800583 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800584 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700585 return ui;
586 }
587 }
588 }
589 return null;
590 }
591
592 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700593 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700594 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700595 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700596 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700597 final int userSize = mUsers.size();
598 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800599 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700600 if (ui.partial) {
601 continue;
602 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800603 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700604 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700605 }
Amith Yamasani13593602012-03-22 16:16:17 -0700606 }
607 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700608 }
Amith Yamasani13593602012-03-22 16:16:17 -0700609 }
610
Amith Yamasani258848d2012-08-10 17:06:33 -0700611 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100612 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700613 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800614 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700615 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700616 } else {
617 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800618 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700619 final long ident = Binder.clearCallingIdentity();
620 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700621 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700622 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100623 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700624 } finally {
625 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000626 }
627 }
628
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700629 @Override
630 public int[] getProfileIds(int userId, boolean enabledOnly) {
631 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700632 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700633 }
634 final long ident = Binder.clearCallingIdentity();
635 try {
636 synchronized (mUsersLock) {
637 return getProfileIdsLU(userId, enabledOnly).toArray();
638 }
639 } finally {
640 Binder.restoreCallingIdentity(ident);
641 }
642 }
643
Amith Yamasanibe465322014-04-24 13:45:17 -0700644 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700645 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700646 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
647 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
648 for (int i = 0; i < profileIds.size(); i++) {
649 int profileId = profileIds.get(i);
650 UserInfo userInfo = mUsers.get(profileId).info;
651 // If full info is not required - clear PII data to prevent 3P apps from reading it
652 if (!fullInfo) {
653 userInfo = new UserInfo(userInfo);
654 userInfo.name = null;
655 userInfo.iconPath = null;
656 } else {
657 userInfo = userWithName(userInfo);
658 }
659 users.add(userInfo);
660 }
661 return users;
662 }
663
664 /**
665 * Assume permissions already checked and caller's identity cleared
666 */
667 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700668 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700669 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700670 if (user == null) {
671 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700672 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700673 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700674 final int userSize = mUsers.size();
675 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800676 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700677 if (!isProfileOf(user, profile)) {
678 continue;
679 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100680 if (enabledOnly && !profile.isEnabled()) {
681 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700682 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700683 if (mRemovingUserIds.get(profile.id)) {
684 continue;
685 }
Tony Mak80189cd2016-04-05 17:21:42 +0100686 if (profile.partial) {
687 continue;
688 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700689 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700690 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700691 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700692 }
693
Jessica Hummelbe81c802014-04-22 15:49:22 +0100694 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700695 public int getCredentialOwnerProfile(int userHandle) {
696 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000697 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 synchronized (mUsersLock) {
699 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700700 if (profileParent != null) {
701 return profileParent.id;
702 }
703 }
704 }
705
706 return userHandle;
707 }
708
709 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700710 public boolean isSameProfileGroup(int userId, int otherUserId) {
711 if (userId == otherUserId) return true;
712 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700713 return isSameProfileGroupNoChecks(userId, otherUserId);
714 }
715
716 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700717 synchronized (mUsersLock) {
718 UserInfo userInfo = getUserInfoLU(userId);
719 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
720 return false;
721 }
722 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
723 if (otherUserInfo == null
724 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
725 return false;
726 }
727 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700728 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700729 }
730
731 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100732 public UserInfo getProfileParent(int userHandle) {
733 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700734 synchronized (mUsersLock) {
735 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700736 }
737 }
738
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800739 @Override
740 public int getProfileParentId(int userHandle) {
741 checkManageUsersPermission("get the profile parent");
742 synchronized (mUsersLock) {
743 UserInfo profileParent = getProfileParentLU(userHandle);
744 if (profileParent == null) {
745 return userHandle;
746 }
747
748 return profileParent.id;
749 }
750 }
751
Fyodor Kupolov82402752015-10-28 14:54:51 -0700752 private UserInfo getProfileParentLU(int userHandle) {
753 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700754 if (profile == null) {
755 return null;
756 }
757 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800758 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700759 return null;
760 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700761 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100762 }
763 }
764
Fyodor Kupolov82402752015-10-28 14:54:51 -0700765 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100766 return user.id == profile.id ||
767 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
768 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000769 }
770
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000771 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000772 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100773 Intent intent = new Intent();
774 if (inQuietMode) {
775 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
776 } else {
777 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
778 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000779 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
780 intent.putExtra(Intent.EXTRA_USER, profileHandle);
781 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000782 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000783 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000784 }
785
786 @Override
Tony Mak64fd8c02017-12-01 19:11:59 +0000787 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode, IntentSender target) {
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000788 checkManageUsersPermission("silence profile");
789 boolean changed = false;
790 UserInfo profile, parent;
791 synchronized (mPackagesLock) {
792 synchronized (mUsersLock) {
793 profile = getUserInfoLU(userHandle);
794 parent = getProfileParentLU(userHandle);
795
796 }
797 if (profile == null || !profile.isManagedProfile()) {
798 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
799 }
800 if (profile.isQuietModeEnabled() != enableQuietMode) {
801 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800802 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000803 changed = true;
804 }
805 }
806 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000807 long identity = Binder.clearCallingIdentity();
808 try {
809 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800810 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100811 LocalServices.getService(ActivityManagerInternal.class)
812 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000813 } else {
Tony Mak64fd8c02017-12-01 19:11:59 +0000814 IProgressListener callback = target != null
815 ? new DisableQuietModeUserUnlockedCallback(target)
816 : null;
817 ActivityManager.getService().startUserInBackgroundWithListener(
818 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000819 }
820 } catch (RemoteException e) {
821 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
822 } finally {
823 Binder.restoreCallingIdentity(identity);
824 }
825
826 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
827 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000828 }
829 }
830
831 @Override
832 public boolean isQuietModeEnabled(int userHandle) {
833 synchronized (mPackagesLock) {
834 UserInfo info;
835 synchronized (mUsersLock) {
836 info = getUserInfoLU(userHandle);
837 }
838 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000839 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000840 }
841 return info.isQuietModeEnabled();
842 }
843 }
844
Kenny Guya52dc3e2014-02-11 15:33:14 +0000845 @Override
Tony Mak64fd8c02017-12-01 19:11:59 +0000846 public boolean trySetQuietModeDisabled(
847 @UserIdInt int userHandle, @Nullable IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100848 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600849 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100850 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100851 // if the user is already unlocked, no need to show a profile challenge
Tony Mak64fd8c02017-12-01 19:11:59 +0000852 setQuietModeEnabled(userHandle, false, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100853 return true;
854 }
855
856 long identity = Binder.clearCallingIdentity();
857 try {
858 // otherwise, we show a profile challenge to trigger decryption of the user
859 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
860 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100861 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
862 // lock, confirm screenlock page will know and show personal challenge, and unlock
863 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100864 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
865 userHandle);
866 if (unlockIntent == null) {
867 return false;
868 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100869 final Intent callBackIntent = new Intent(
870 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100871 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100872 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100873 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100874 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
875 callBackIntent.setPackage(mContext.getPackageName());
876 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
877 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
878 mContext,
879 0,
880 callBackIntent,
881 PendingIntent.FLAG_CANCEL_CURRENT |
882 PendingIntent.FLAG_ONE_SHOT |
883 PendingIntent.FLAG_IMMUTABLE);
884 // After unlocking the challenge, it will disable quiet mode and run the original
885 // intentSender
886 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100887 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
888 mContext.startActivity(unlockIntent);
889 } finally {
890 Binder.restoreCallingIdentity(identity);
891 }
892 return false;
893 }
894
895 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100896 public void setUserEnabled(int userId) {
897 checkManageUsersPermission("enable user");
898 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700899 UserInfo info;
900 synchronized (mUsersLock) {
901 info = getUserInfoLU(userId);
902 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100903 if (info != null && !info.isEnabled()) {
904 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800905 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100906 }
907 }
908 }
909
Andrew Scull85a63bc2016-10-24 13:47:47 +0100910 /**
911 * Evicts a user's CE key by stopping and restarting the user.
912 *
913 * The key is evicted automatically by the user controller when the user has stopped.
914 */
915 @Override
916 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
917 checkManageUsersPermission("evict CE key");
918 final IActivityManager am = ActivityManagerNative.getDefault();
919 final long identity = Binder.clearCallingIdentity();
920 try {
921 am.restartUserInBackground(userId);
922 } catch (RemoteException re) {
923 throw re.rethrowAsRuntimeException();
924 } finally {
925 Binder.restoreCallingIdentity(identity);
926 }
927 }
928
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100929 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700930 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700931 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000932 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700933 return userWithName(getUserInfoLU(userId));
934 }
935 }
936
937 /**
938 * Returns a UserInfo object with the name filled in, for Owner, or the original
939 * if the name is already set.
940 */
941 private UserInfo userWithName(UserInfo orig) {
942 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
943 UserInfo withName = new UserInfo(orig);
944 withName.name = getOwnerName();
945 return withName;
946 } else {
947 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000948 }
949 }
950
951 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000952 public int getManagedProfileBadge(@UserIdInt int userId) {
953 int callingUserId = UserHandle.getCallingUserId();
954 if (callingUserId != userId && !hasManageUsersPermission()) {
955 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
956 throw new SecurityException(
957 "You need MANAGE_USERS permission to: check if specified user a " +
958 "managed profile outside your profile group");
959 }
960 }
961 synchronized (mUsersLock) {
962 UserInfo userInfo = getUserInfoLU(userId);
963 return userInfo != null ? userInfo.profileBadge : 0;
964 }
965 }
966
967 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000968 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000969 int callingUserId = UserHandle.getCallingUserId();
970 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700971 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700972 throw new SecurityException(
973 "You need MANAGE_USERS permission to: check if specified user a " +
974 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000975 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000976 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700977 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700978 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000979 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700980 }
981 }
982
Amith Yamasani71e6c692013-03-24 17:39:28 -0700983 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700984 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800985 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700986 return mLocalService.isUserUnlockingOrUnlocked(userId);
987 }
988
989 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800990 public boolean isUserUnlocked(int userId) {
991 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -0700992 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800993 }
994
995 @Override
996 public boolean isUserRunning(int userId) {
997 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
998 return mLocalService.isUserRunning(userId);
999 }
1000
1001 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1002 int callingUserId = UserHandle.getCallingUserId();
1003 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1004 hasManageUsersPermission()) {
1005 return;
1006 }
1007 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
1008 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
1009 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1010 + "to: check " + name);
1011 }
1012 }
1013
1014 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001015 public boolean isDemoUser(int userId) {
1016 int callingUserId = UserHandle.getCallingUserId();
1017 if (callingUserId != userId && !hasManageUsersPermission()) {
1018 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1019 + " is a demo user");
1020 }
1021 synchronized (mUsersLock) {
1022 UserInfo userInfo = getUserInfoLU(userId);
1023 return userInfo != null && userInfo.isDemo();
1024 }
1025 }
1026
1027 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001028 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001029 synchronized (mUsersLock) {
1030 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001031 }
1032 }
1033
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001034 @Override
1035 public boolean canHaveRestrictedProfile(int userId) {
1036 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001037 synchronized (mUsersLock) {
1038 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001039 if (userInfo == null || !userInfo.canHaveProfile()) {
1040 return false;
1041 }
1042 if (!userInfo.isAdmin()) {
1043 return false;
1044 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001045 // restricted profile can be created if there is no DO set and the admin user has no PO;
1046 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001047 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001048 }
1049
Fyodor Kupolovca177562017-11-09 17:43:01 -08001050 @Override
1051 public boolean hasRestrictedProfiles() {
1052 checkManageUsersPermission("hasRestrictedProfiles");
1053 final int callingUserId = UserHandle.getCallingUserId();
1054 synchronized (mUsersLock) {
1055 final int userSize = mUsers.size();
1056 for (int i = 0; i < userSize; i++) {
1057 UserInfo profile = mUsers.valueAt(i).info;
1058 if (callingUserId != profile.id
1059 && profile.restrictedProfileParentId == callingUserId) {
1060 return true;
1061 }
1062 }
1063 return false;
1064 }
1065 }
1066
Amith Yamasani195263742012-08-21 15:40:12 -07001067 /*
1068 * Should be locked on mUsers before calling this.
1069 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001070 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001071 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001072 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001073 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001074 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1075 return null;
1076 }
Amith Yamasani12747872015-12-07 14:19:49 -08001077 return userData != null ? userData.info : null;
1078 }
1079
1080 private UserData getUserDataLU(int userId) {
1081 final UserData userData = mUsers.get(userId);
1082 // If it is partial and not in the process of being removed, return as unknown user.
1083 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1084 return null;
1085 }
1086 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001087 }
1088
Fyodor Kupolov82402752015-10-28 14:54:51 -07001089 /**
1090 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1091 * <p>No permissions checking or any addition checks are made</p>
1092 */
1093 private UserInfo getUserInfoNoChecks(int userId) {
1094 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001095 final UserData userData = mUsers.get(userId);
1096 return userData != null ? userData.info : null;
1097 }
1098 }
1099
1100 /**
1101 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1102 * <p>No permissions checking or any addition checks are made</p>
1103 */
1104 private UserData getUserDataNoChecks(int userId) {
1105 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001106 return mUsers.get(userId);
1107 }
1108 }
1109
Amith Yamasani236b2b52015-08-18 14:32:14 -07001110 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001111 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001112 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001113 }
1114
Amith Yamasani258848d2012-08-10 17:06:33 -07001115 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001116 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001117 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001118 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001119 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001120 UserData userData = getUserDataNoChecks(userId);
1121 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001122 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1123 return;
1124 }
Amith Yamasani12747872015-12-07 14:19:49 -08001125 if (name != null && !name.equals(userData.info.name)) {
1126 userData.info.name = name;
1127 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001128 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001129 }
1130 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001131 if (changed) {
1132 sendUserInfoChangedBroadcast(userId);
1133 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001134 }
1135
Amith Yamasani258848d2012-08-10 17:06:33 -07001136 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001137 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001138 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001139 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1140 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1141 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001142 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001143 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001144 }
1145
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001146
1147
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001148 private void sendUserInfoChangedBroadcast(int userId) {
1149 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1150 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1151 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001152 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001153 }
1154
Amith Yamasani258848d2012-08-10 17:06:33 -07001155 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001156 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001157 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001158 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001159 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1160 if (targetUserInfo == null || targetUserInfo.partial) {
1161 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001162 return null;
1163 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001164
1165 final int callingUserId = UserHandle.getCallingUserId();
1166 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1167 final int targetGroupId = targetUserInfo.profileGroupId;
1168 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1169 && callingGroupId == targetGroupId);
1170 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001171 checkManageUsersPermission("get the icon of a user who is not related");
1172 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001173
1174 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001175 return null;
1176 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001177 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001178 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001179
1180 try {
1181 return ParcelFileDescriptor.open(
1182 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1183 } catch (FileNotFoundException e) {
1184 Log.e(LOG_TAG, "Couldn't find icon file", e);
1185 }
1186 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001187 }
1188
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001189 public void makeInitialized(int userId) {
1190 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001191 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001192 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001193 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001194 userData = mUsers.get(userId);
1195 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001196 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001197 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001198 }
Amith Yamasani12747872015-12-07 14:19:49 -08001199 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1200 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001201 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001202 }
1203 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001204 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001205 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001206 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001207 }
1208
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001209 /**
1210 * If default guest restrictions haven't been initialized yet, add the basic
1211 * restrictions.
1212 */
1213 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001214 synchronized (mGuestRestrictions) {
1215 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001216 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001217 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001218 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1219 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1220 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001221 }
1222 }
1223
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001224 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301225 public Bundle getDefaultGuestRestrictions() {
1226 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001227 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301228 return new Bundle(mGuestRestrictions);
1229 }
1230 }
1231
1232 @Override
1233 public void setDefaultGuestRestrictions(Bundle restrictions) {
1234 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001235 synchronized (mGuestRestrictions) {
1236 mGuestRestrictions.clear();
1237 mGuestRestrictions.putAll(restrictions);
1238 }
1239 synchronized (mPackagesLock) {
1240 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301241 }
1242 }
1243
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001244 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001245 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001246 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001247 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1248 boolean isDeviceOwner, int cameraRestrictionScope) {
1249 final Bundle global = new Bundle();
1250 final Bundle local = new Bundle();
1251
1252 // Sort restrictions into local and global ensuring they don't overlap.
1253 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1254 cameraRestrictionScope, global, local);
1255
1256 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001257 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001258 // Update global and local restrictions if they were changed.
1259 globalChanged = updateRestrictionsIfNeededLR(
1260 userId, global, mDevicePolicyGlobalUserRestrictions);
1261 localChanged = updateRestrictionsIfNeededLR(
1262 userId, local, mDevicePolicyLocalUserRestrictions);
1263
1264 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001265 // Remember the global restriction owner userId to be able to make a distinction
1266 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001267 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001268 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001269 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001270 // When profile owner sets restrictions it passes null global bundle and we
1271 // reset global restriction owner userId.
1272 // This means this user used to have DO, but now the DO is gone and the user
1273 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001274 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001275 }
1276 }
1277 }
1278 if (DBG) {
1279 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1280 + " global=" + global + (globalChanged ? " (changed)" : "")
1281 + " local=" + local + (localChanged ? " (changed)" : "")
1282 );
1283 }
1284 // Don't call them within the mRestrictionsLock.
1285 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001286 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001287 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001288 }
1289 }
1290
1291 synchronized (mRestrictionsLock) {
1292 if (globalChanged) {
1293 applyUserRestrictionsForAllUsersLR();
1294 } else if (localChanged) {
1295 applyUserRestrictionsLR(userId);
1296 }
1297 }
1298 }
1299
Pavel Grafov6a40f092016-10-25 15:46:51 +01001300 /**
1301 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1302 * empty, record is removed from the array.
1303 * @return whether restrictions bundle is different from the old one.
1304 */
1305 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1306 SparseArray<Bundle> restrictionsArray) {
1307 final boolean changed =
1308 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1309 if (changed) {
1310 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1311 restrictionsArray.put(userId, restrictions);
1312 } else {
1313 restrictionsArray.delete(userId);
1314 }
1315 }
1316 return changed;
1317 }
1318
Makoto Onuki068c54a2015-10-13 14:34:03 -07001319 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001320 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001321 final Bundle baseRestrictions =
1322 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001323 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001324 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001325
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001326 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1327 // Common case first.
1328 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001329 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001330 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1331 UserRestrictionsUtils.merge(effective, global);
1332 UserRestrictionsUtils.merge(effective, local);
1333
Makoto Onuki068c54a2015-10-13 14:34:03 -07001334 return effective;
1335 }
1336
1337 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001338 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001339 if (DBG) {
1340 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1341 }
1342 mCachedEffectiveUserRestrictions.remove(userId);
1343 }
1344
1345 private Bundle getEffectiveUserRestrictions(int userId) {
1346 synchronized (mRestrictionsLock) {
1347 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1348 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001349 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001350 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1351 }
1352 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001353 }
1354 }
1355
Makoto Onuki068c54a2015-10-13 14:34:03 -07001356 /** @return a specific user restriction that's in effect currently. */
1357 @Override
1358 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001359 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1360 return false;
1361 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001362 Bundle restrictions = getEffectiveUserRestrictions(userId);
1363 return restrictions != null && restrictions.getBoolean(restrictionKey);
1364 }
1365
1366 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001367 * @hide
1368 *
1369 * Returns who set a user restriction on a user.
1370 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1371 * @param restrictionKey the string key representing the restriction
1372 * @param userId the id of the user for whom to retrieve the restrictions.
1373 * @return The source of user restriction. Any combination of
1374 * {@link UserManager#RESTRICTION_NOT_SET},
1375 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1376 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1377 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1378 */
1379 @Override
1380 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001381 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1382 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001383 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001384 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1385 result |= enforcingUsers.get(i).getUserRestrictionSource();
1386 }
1387 return result;
1388 }
1389
1390 @Override
1391 public List<EnforcingUser> getUserRestrictionSources(
1392 String restrictionKey, @UserIdInt int userId) {
1393 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001394
1395 // Shortcut for the most common case
1396 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001397 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001398 }
1399
Pavel Grafov6a40f092016-10-25 15:46:51 +01001400 final List<EnforcingUser> result = new ArrayList<>();
1401
1402 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001403 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001404 result.add(new EnforcingUser(
1405 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001406 }
1407
Pavel Grafov6a40f092016-10-25 15:46:51 +01001408 synchronized (mRestrictionsLock) {
1409 // Check if it is set by profile owner.
1410 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1411 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1412 result.add(getEnforcingUserLocked(userId));
1413 }
1414
1415 // Iterate over all users who enforce global restrictions.
1416 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1417 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1418 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1419 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1420 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001421 }
1422 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001423 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001424 return result;
1425 }
1426
Pavel Grafov6a40f092016-10-25 15:46:51 +01001427 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1428 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1429 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1430 return new EnforcingUser(userId, source);
1431 }
1432
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001433 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001434 * @return UserRestrictions that are in effect currently. This always returns a new
1435 * {@link Bundle}.
1436 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001437 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001438 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001439 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001440 }
1441
1442 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001443 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1444 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001445 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1446 return false;
1447 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001448 synchronized (mRestrictionsLock) {
1449 Bundle bundle = mBaseUserRestrictions.get(userId);
1450 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1451 }
1452 }
1453
1454 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001455 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001456 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001457 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1458 return;
1459 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001460 synchronized (mRestrictionsLock) {
1461 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1462 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001463 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1464 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001465 newRestrictions.putBoolean(key, value);
1466
Fyodor Kupolov82402752015-10-28 14:54:51 -07001467 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001468 }
1469 }
1470
Makoto Onuki068c54a2015-10-13 14:34:03 -07001471 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001472 * Optionally updating user restrictions, calculate the effective user restrictions and also
1473 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001474 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001475 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001476 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001477 * @param userId target user ID.
1478 */
1479 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001480 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001481 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001482 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1483 mAppliedUserRestrictions.get(userId));
1484
1485 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001486 if (newBaseRestrictions != null) {
1487 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001488 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1489
Pavel Grafov6a40f092016-10-25 15:46:51 +01001490 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001491 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001492 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001493
Pavel Grafov6a40f092016-10-25 15:46:51 +01001494 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001495 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001496 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001497 }
1498
Fyodor Kupolov82402752015-10-28 14:54:51 -07001499 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001500
Makoto Onuki759a7632015-10-28 16:43:10 -07001501 mCachedEffectiveUserRestrictions.put(userId, effective);
1502
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001503 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001504 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001505 debug("Applying user restrictions: userId=" + userId
1506 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001507 }
1508
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001509 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001510 mHandler.post(new Runnable() {
1511 @Override
1512 public void run() {
1513 try {
1514 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1515 } catch (RemoteException e) {
1516 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1517 }
1518 }
1519 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001520 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001521
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001522 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001523
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001524 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001525 }
1526
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001527 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001528 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001529 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1530 // actually, but we still need some kind of synchronization otherwise we might end up
1531 // calling listeners out-of-order, thus "LR".
1532
1533 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1534 return;
1535 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001536
1537 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1538 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1539
1540 mHandler.post(new Runnable() {
1541 @Override
1542 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001543 UserRestrictionsUtils.applyUserRestrictions(
1544 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001545
Makoto Onukid45a4a22015-11-02 17:17:38 -08001546 final UserRestrictionsListener[] listeners;
1547 synchronized (mUserRestrictionsListeners) {
1548 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1549 mUserRestrictionsListeners.toArray(listeners);
1550 }
1551 for (int i = 0; i < listeners.length; i++) {
1552 listeners[i].onUserRestrictionsChanged(userId,
1553 newRestrictionsFinal, prevRestrictionsFinal);
1554 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001555
1556 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1557 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1558 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001559 }
1560 });
1561 }
1562
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001563 // Package private for the inner class.
1564 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001565 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001566 }
1567
1568 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001569 // Package private for the inner class.
1570 void applyUserRestrictionsForAllUsersLR() {
1571 if (DBG) {
1572 debug("applyUserRestrictionsForAllUsersLR");
1573 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001574 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001575 mCachedEffectiveUserRestrictions.clear();
1576
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001577 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001578 // it on a handler.
1579 final Runnable r = new Runnable() {
1580 @Override
1581 public void run() {
1582 // Then get the list of running users.
1583 final int[] runningUsers;
1584 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001585 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001586 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001587 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001588 return;
1589 }
1590 // Then re-calculate the effective restrictions and apply, only for running users.
1591 // It's okay if a new user has started after the getRunningUserIds() call,
1592 // because we'll do the same thing (re-calculate the restrictions and apply)
1593 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001594 synchronized (mRestrictionsLock) {
1595 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001596 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001597 }
1598 }
1599 }
1600 };
1601 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001602 }
1603
Amith Yamasani258848d2012-08-10 17:06:33 -07001604 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001605 * Check if we've hit the limit of how many users can be created.
1606 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001607 private boolean isUserLimitReached() {
1608 int count;
1609 synchronized (mUsersLock) {
1610 count = getAliveUsersExcludingGuestsCountLU();
1611 }
1612 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001613 }
1614
1615 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001616 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001617 checkManageUsersPermission("check if more managed profiles can be added.");
1618 if (ActivityManager.isLowRamDeviceStatic()) {
1619 return false;
1620 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001621 if (!mContext.getPackageManager().hasSystemFeature(
1622 PackageManager.FEATURE_MANAGED_USERS)) {
1623 return false;
1624 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001625 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001626 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001627 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001628 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001629 return false;
1630 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001631 synchronized(mUsersLock) {
1632 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001633 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001634 return false;
1635 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001636 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1637 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001638 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001639 return usersCountAfterRemoving == 1
1640 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001641 }
1642 }
1643
Fyodor Kupolov82402752015-10-28 14:54:51 -07001644 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001645 int aliveUserCount = 0;
1646 final int totalUserCount = mUsers.size();
1647 // Skip over users being removed
1648 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001649 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001650 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001651 aliveUserCount++;
1652 }
1653 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001654 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001655 }
1656
1657 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001658 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001659 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1660 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1661 * permissions can make certain calls to the UserManager.
1662 *
1663 * @param message used as message if SecurityException is thrown
1664 * @throws SecurityException if the caller does not have enough privilege.
1665 */
1666 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1667 final int uid = Binder.getCallingUid();
1668 if (uid != Process.SYSTEM_UID && uid != 0
1669 && ActivityManager.checkComponentPermission(
1670 Manifest.permission.MANAGE_USERS,
1671 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1672 && ActivityManager.checkComponentPermission(
1673 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1674 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1675 throw new SecurityException(
1676 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1677 + message);
1678 }
1679 }
1680
1681 /**
1682 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001683 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001684 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001685 *
1686 * @param message used as message if SecurityException is thrown
1687 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001688 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001689 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001690 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001691 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001692 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1693 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001694 }
1695
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001696 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001697 * Enforces that only the system UID or root's UID or apps that have the
1698 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1699 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1700 * can make certain calls to the UserManager.
1701 *
1702 * @param message used as message if SecurityException is thrown
1703 * @throws SecurityException if the caller is not system or root
1704 * @see #hasManageOrCreateUsersPermission()
1705 */
1706 private static final void checkManageOrCreateUsersPermission(String message) {
1707 if (!hasManageOrCreateUsersPermission()) {
1708 throw new SecurityException(
1709 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1710 }
1711 }
1712
1713 /**
1714 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1715 * to create user/profiles other than what is allowed for
1716 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1717 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1718 */
1719 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1720 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1721 if (!hasManageOrCreateUsersPermission()) {
1722 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1723 + "permission to create an user with flags: " + creationFlags);
1724 }
1725 } else if (!hasManageUsersPermission()) {
1726 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1727 + " with flags: " + creationFlags);
1728 }
1729 }
1730
1731 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001732 * @return whether the calling UID is system UID or root's UID or the calling app has the
1733 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1734 */
1735 private static final boolean hasManageUsersPermission() {
1736 final int callingUid = Binder.getCallingUid();
1737 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1738 || callingUid == Process.ROOT_UID
1739 || ActivityManager.checkComponentPermission(
1740 android.Manifest.permission.MANAGE_USERS,
1741 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1742 }
1743
1744 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001745 * @return whether the calling UID is system UID or root's UID or the calling app has the
1746 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1747 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1748 */
1749 private static final boolean hasManageOrCreateUsersPermission() {
1750 final int callingUid = Binder.getCallingUid();
1751 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1752 || callingUid == Process.ROOT_UID
1753 || ActivityManager.checkComponentPermission(
1754 android.Manifest.permission.MANAGE_USERS,
1755 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1756 || ActivityManager.checkComponentPermission(
1757 android.Manifest.permission.CREATE_USERS,
1758 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1759 }
1760
1761 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001762 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1763 * UserManager.
1764 *
1765 * @param message used as message if SecurityException is thrown
1766 * @throws SecurityException if the caller is not system or root
1767 */
1768 private static void checkSystemOrRoot(String message) {
1769 final int uid = Binder.getCallingUid();
1770 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1771 throw new SecurityException("Only system may: " + message);
1772 }
1773 }
1774
Fyodor Kupolov82402752015-10-28 14:54:51 -07001775 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001776 try {
1777 File dir = new File(mUsersDir, Integer.toString(info.id));
1778 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001779 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001780 if (!dir.exists()) {
1781 dir.mkdir();
1782 FileUtils.setPermissions(
1783 dir.getPath(),
1784 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1785 -1, -1);
1786 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001787 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001788 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001789 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001790 info.iconPath = file.getAbsolutePath();
1791 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001792 try {
1793 os.close();
1794 } catch (IOException ioe) {
1795 // What the ... !
1796 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001797 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001798 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001799 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001800 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001801 }
1802
Amith Yamasani0b285492011-04-14 17:35:23 -07001803 /**
1804 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1805 * cache it elsewhere.
1806 * @return the array of user ids.
1807 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001808 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001809 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001810 return mUserIds;
1811 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001812 }
1813
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001814 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001815 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001816 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001817 return;
1818 }
1819 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001820 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001821 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001822 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001823 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001824 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001825 int type;
1826 while ((type = parser.next()) != XmlPullParser.START_TAG
1827 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001828 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001829 }
1830
1831 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001832 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001833 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001834 return;
1835 }
1836
Amith Yamasani2a003292012-08-14 18:25:45 -07001837 mNextSerialNumber = -1;
1838 if (parser.getName().equals(TAG_USERS)) {
1839 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1840 if (lastSerialNumber != null) {
1841 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1842 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001843 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1844 if (versionNumber != null) {
1845 mUserVersion = Integer.parseInt(versionNumber);
1846 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001847 }
1848
Pavel Grafov6a40f092016-10-25 15:46:51 +01001849 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1850 // currently), take care of it in case of upgrade.
1851 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001852
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001853 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301854 if (type == XmlPullParser.START_TAG) {
1855 final String name = parser.getName();
1856 if (name.equals(TAG_USER)) {
1857 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001858
Amith Yamasani12747872015-12-07 14:19:49 -08001859 UserData userData = readUserLP(Integer.parseInt(id));
1860
1861 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001862 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001863 mUsers.put(userData.info.id, userData);
1864 if (mNextSerialNumber < 0
1865 || mNextSerialNumber <= userData.info.id) {
1866 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001867 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301868 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001869 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301870 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001871 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1872 && type != XmlPullParser.END_TAG) {
1873 if (type == XmlPullParser.START_TAG) {
1874 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001875 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001876 UserRestrictionsUtils
1877 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001878 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001879 }
1880 break;
1881 }
1882 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001883 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1884 // Legacy name, should only be encountered when upgrading from pre-O.
1885 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001886 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1887 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001888 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001889 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001890 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1891 // Should only happen when upgrading from pre-O (version < 7).
1892 oldDevicePolicyGlobalUserRestrictions =
1893 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001894 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001895 }
1896 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001897
Fyodor Kupolov82402752015-10-28 14:54:51 -07001898 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001899 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001900 } catch (IOException | XmlPullParserException e) {
1901 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001902 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001903 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001904 }
1905 }
1906
Amith Yamasani6f34b412012-10-22 18:19:27 -07001907 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001908 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001909 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001910 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001911 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001912 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001913 int userVersion = mUserVersion;
1914 if (userVersion < 1) {
1915 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001916 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1917 if ("Primary".equals(userData.info.name)) {
1918 userData.info.name =
1919 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1920 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001921 }
1922 userVersion = 1;
1923 }
1924
Amith Yamasanibc9625052012-11-15 14:39:18 -08001925 if (userVersion < 2) {
1926 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001927 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1928 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1929 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1930 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001931 }
1932 userVersion = 2;
1933 }
1934
Amith Yamasani350962c2013-08-06 11:18:53 -07001935
Amith Yamasani5e486f52013-08-07 11:06:44 -07001936 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001937 userVersion = 4;
1938 }
1939
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001940 if (userVersion < 5) {
1941 initDefaultGuestRestrictions();
1942 userVersion = 5;
1943 }
1944
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001945 if (userVersion < 6) {
1946 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001947 synchronized (mUsersLock) {
1948 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001949 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001950 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001951 if (!splitSystemUser && userData.info.isRestricted()
1952 && (userData.info.restrictedProfileParentId
1953 == UserInfo.NO_PROFILE_GROUP_ID)) {
1954 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1955 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001956 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001957 }
1958 }
1959 userVersion = 6;
1960 }
1961
Pavel Grafov6a40f092016-10-25 15:46:51 +01001962 if (userVersion < 7) {
1963 // Previously only one user could enforce global restrictions, now it is per-user.
1964 synchronized (mRestrictionsLock) {
1965 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1966 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1967 mDevicePolicyGlobalUserRestrictions.put(
1968 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1969 }
1970 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1971 // it from local to global bundle for all users who set it.
1972 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1973 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1974 );
1975 }
1976 userVersion = 7;
1977 }
1978
Amith Yamasani6f34b412012-10-22 18:19:27 -07001979 if (userVersion < USER_VERSION) {
1980 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1981 + USER_VERSION);
1982 } else {
1983 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001984
1985 if (originalVersion < mUserVersion) {
1986 writeUserListLP();
1987 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001988 }
1989 }
1990
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001991 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001992 int flags = UserInfo.FLAG_INITIALIZED;
1993 // In split system user mode, the admin and primary flags are assigned to the first human
1994 // user.
1995 if (!UserManager.isSplitSystemUser()) {
1996 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1997 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001998 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001999 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002000 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002001 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002002 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002003
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002004 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002005 try {
2006 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2007 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2008 for (String userRestriction : defaultFirstUserRestrictions) {
2009 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2010 restrictions.putBoolean(userRestriction, true);
2011 }
2012 }
2013 } catch (Resources.NotFoundException e) {
2014 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2015 }
2016
Pavel Grafov6a40f092016-10-25 15:46:51 +01002017 if (!restrictions.isEmpty()) {
2018 synchronized (mRestrictionsLock) {
2019 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2020 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002021 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002022
Fyodor Kupolov82402752015-10-28 14:54:51 -07002023 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002024 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002025
Amith Yamasani12747872015-12-07 14:19:49 -08002026 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002027 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002028 }
2029
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002030 private String getOwnerName() {
2031 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2032 }
2033
Amith Yamasani12747872015-12-07 14:19:49 -08002034 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002035 if (DBG) {
2036 debug("scheduleWriteUser");
2037 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002038 // No need to wrap it within a lock -- worst case, we'll just post the same message
2039 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002040 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2041 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002042 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2043 }
2044 }
2045
Amith Yamasani12747872015-12-07 14:19:49 -08002046 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002047 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002048 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002049 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002050 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002051 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002052 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002053 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002054 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002055 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002056 userFile.finishWrite(fos);
2057 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002058 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002059 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002060 }
2061 }
2062
2063 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002064 * Writes the user file in this format:
2065 *
2066 * <user flags="20039023" id="0">
2067 * <name>Primary</name>
2068 * </user>
2069 */
2070 @VisibleForTesting
2071 void writeUserLP(UserData userData, OutputStream os)
2072 throws IOException, XmlPullParserException {
2073 // XmlSerializer serializer = XmlUtils.serializerInstance();
2074 final XmlSerializer serializer = new FastXmlSerializer();
2075 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2076 serializer.startDocument(null, true);
2077 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2078
2079 final UserInfo userInfo = userData.info;
2080 serializer.startTag(null, TAG_USER);
2081 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2082 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2083 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2084 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2085 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2086 Long.toString(userInfo.lastLoggedInTime));
2087 if (userInfo.lastLoggedInFingerprint != null) {
2088 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2089 userInfo.lastLoggedInFingerprint);
2090 }
2091 if (userInfo.iconPath != null) {
2092 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2093 }
2094 if (userInfo.partial) {
2095 serializer.attribute(null, ATTR_PARTIAL, "true");
2096 }
2097 if (userInfo.guestToRemove) {
2098 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2099 }
2100 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2101 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2102 Integer.toString(userInfo.profileGroupId));
2103 }
2104 serializer.attribute(null, ATTR_PROFILE_BADGE,
2105 Integer.toString(userInfo.profileBadge));
2106 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2107 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2108 Integer.toString(userInfo.restrictedProfileParentId));
2109 }
2110 // Write seed data
2111 if (userData.persistSeedData) {
2112 if (userData.seedAccountName != null) {
2113 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2114 }
2115 if (userData.seedAccountType != null) {
2116 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2117 }
2118 }
2119 if (userInfo.name != null) {
2120 serializer.startTag(null, TAG_NAME);
2121 serializer.text(userInfo.name);
2122 serializer.endTag(null, TAG_NAME);
2123 }
2124 synchronized (mRestrictionsLock) {
2125 UserRestrictionsUtils.writeRestrictions(serializer,
2126 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2127 UserRestrictionsUtils.writeRestrictions(serializer,
2128 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2129 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002130 UserRestrictionsUtils.writeRestrictions(serializer,
2131 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2132 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002133 }
2134
2135 if (userData.account != null) {
2136 serializer.startTag(null, TAG_ACCOUNT);
2137 serializer.text(userData.account);
2138 serializer.endTag(null, TAG_ACCOUNT);
2139 }
2140
2141 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2142 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2143 userData.seedAccountOptions.saveToXml(serializer);
2144 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2145 }
2146
2147 serializer.endTag(null, TAG_USER);
2148
2149 serializer.endDocument();
2150 }
2151
2152 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002153 * Writes the user list file in this format:
2154 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002155 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002156 * <user id="0"></user>
2157 * <user id="2"></user>
2158 * </users>
2159 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002160 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002161 if (DBG) {
2162 debug("writeUserList");
2163 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002164 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002165 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002166 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002167 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002168 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2169
2170 // XmlSerializer serializer = XmlUtils.serializerInstance();
2171 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002172 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002173 serializer.startDocument(null, true);
2174 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2175
2176 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002177 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002178 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002179
Adam Lesinskieddeb492014-09-08 17:50:03 -07002180 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002181 synchronized (mGuestRestrictions) {
2182 UserRestrictionsUtils
2183 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2184 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302185 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002186 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2187 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2188 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002189 int[] userIdsToWrite;
2190 synchronized (mUsersLock) {
2191 userIdsToWrite = new int[mUsers.size()];
2192 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002193 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002194 userIdsToWrite[i] = user.id;
2195 }
2196 }
2197 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002198 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002199 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002200 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002201 }
2202
2203 serializer.endTag(null, TAG_USERS);
2204
2205 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002206 userListFile.finishWrite(fos);
2207 } catch (Exception e) {
2208 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002209 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002210 }
2211 }
2212
Amith Yamasani12747872015-12-07 14:19:49 -08002213 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002214 FileInputStream fis = null;
2215 try {
2216 AtomicFile userFile =
2217 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2218 fis = userFile.openRead();
2219 return readUserLP(id, fis);
2220 } catch (IOException ioe) {
2221 Slog.e(LOG_TAG, "Error reading user list");
2222 } catch (XmlPullParserException pe) {
2223 Slog.e(LOG_TAG, "Error reading user list");
2224 } finally {
2225 IoUtils.closeQuietly(fis);
2226 }
2227 return null;
2228 }
2229
2230 @VisibleForTesting
2231 UserData readUserLP(int id, InputStream is) throws IOException,
2232 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002233 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002234 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002235 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002236 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002237 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002238 long creationTime = 0L;
2239 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002240 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002241 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002242 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002243 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002244 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002245 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002246 boolean persistSeedData = false;
2247 String seedAccountName = null;
2248 String seedAccountType = null;
2249 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002250 Bundle baseRestrictions = null;
2251 Bundle localRestrictions = null;
2252 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002253
Kenny Guy02c89902016-11-15 19:36:38 +00002254 XmlPullParser parser = Xml.newPullParser();
2255 parser.setInput(is, StandardCharsets.UTF_8.name());
2256 int type;
2257 while ((type = parser.next()) != XmlPullParser.START_TAG
2258 && type != XmlPullParser.END_DOCUMENT) {
2259 // Skip
2260 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002261
Kenny Guy02c89902016-11-15 19:36:38 +00002262 if (type != XmlPullParser.START_TAG) {
2263 Slog.e(LOG_TAG, "Unable to read user " + id);
2264 return null;
2265 }
2266
2267 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2268 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2269 if (storedId != id) {
2270 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002271 return null;
2272 }
Kenny Guy02c89902016-11-15 19:36:38 +00002273 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2274 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2275 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2276 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2277 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2278 lastLoggedInFingerprint = parser.getAttributeValue(null,
2279 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2280 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2281 UserInfo.NO_PROFILE_GROUP_ID);
2282 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2283 restrictedProfileParentId = readIntAttribute(parser,
2284 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2285 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2286 if ("true".equals(valueString)) {
2287 partial = true;
2288 }
2289 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2290 if ("true".equals(valueString)) {
2291 guestToRemove = true;
2292 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002293
Kenny Guy02c89902016-11-15 19:36:38 +00002294 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2295 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2296 if (seedAccountName != null || seedAccountType != null) {
2297 persistSeedData = true;
2298 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002299
Kenny Guy02c89902016-11-15 19:36:38 +00002300 int outerDepth = parser.getDepth();
2301 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2302 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2303 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2304 continue;
2305 }
2306 String tag = parser.getName();
2307 if (TAG_NAME.equals(tag)) {
2308 type = parser.next();
2309 if (type == XmlPullParser.TEXT) {
2310 name = parser.getText();
2311 }
2312 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002313 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002314 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002315 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2316 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2317 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002318 } else if (TAG_ACCOUNT.equals(tag)) {
2319 type = parser.next();
2320 if (type == XmlPullParser.TEXT) {
2321 account = parser.getText();
2322 }
2323 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2324 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002325 persistSeedData = true;
2326 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002327 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002328 }
Kenny Guy02c89902016-11-15 19:36:38 +00002329
2330 // Create the UserInfo object that gets passed around
2331 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2332 userInfo.serialNumber = serialNumber;
2333 userInfo.creationTime = creationTime;
2334 userInfo.lastLoggedInTime = lastLoggedInTime;
2335 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2336 userInfo.partial = partial;
2337 userInfo.guestToRemove = guestToRemove;
2338 userInfo.profileGroupId = profileGroupId;
2339 userInfo.profileBadge = profileBadge;
2340 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2341
2342 // Create the UserData object that's internal to this class
2343 UserData userData = new UserData();
2344 userData.info = userInfo;
2345 userData.account = account;
2346 userData.seedAccountName = seedAccountName;
2347 userData.seedAccountType = seedAccountType;
2348 userData.persistSeedData = persistSeedData;
2349 userData.seedAccountOptions = seedAccountOptions;
2350
2351 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002352 if (baseRestrictions != null) {
2353 mBaseUserRestrictions.put(id, baseRestrictions);
2354 }
2355 if (localRestrictions != null) {
2356 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2357 }
2358 if (globalRestrictions != null) {
2359 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2360 }
Kenny Guy02c89902016-11-15 19:36:38 +00002361 }
2362 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002363 }
2364
Amith Yamasani920ace02012-09-20 22:15:37 -07002365 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2366 String valueString = parser.getAttributeValue(null, attr);
2367 if (valueString == null) return defaultValue;
2368 try {
2369 return Integer.parseInt(valueString);
2370 } catch (NumberFormatException nfe) {
2371 return defaultValue;
2372 }
2373 }
2374
2375 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2376 String valueString = parser.getAttributeValue(null, attr);
2377 if (valueString == null) return defaultValue;
2378 try {
2379 return Long.parseLong(valueString);
2380 } catch (NumberFormatException nfe) {
2381 return defaultValue;
2382 }
2383 }
2384
Amith Yamasanib82add22013-07-09 11:24:44 -07002385 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002386 * Removes the app restrictions file for a specific package and user id, if it exists.
2387 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002388 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2389 File dir = Environment.getUserSystemDirectory(userId);
2390 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2391 if (resFile.exists()) {
2392 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002393 }
2394 }
2395
Kenny Guya52dc3e2014-02-11 15:33:14 +00002396 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002397 public UserInfo createProfileForUser(String name, int flags, int userId,
2398 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002399 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002400 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002401 }
2402
Amith Yamasani258848d2012-08-10 17:06:33 -07002403 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002404 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2405 String[] disallowedPackages) {
2406 checkManageOrCreateUsersPermission(flags);
2407 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2408 }
2409
2410 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002411 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2412 checkManageOrCreateUsersPermission("Only the system can remove users");
2413 return removeUserUnchecked(userHandle);
2414 }
2415
2416 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002417 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002418 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002419 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002420 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002421
Jessica Hummelbe81c802014-04-22 15:49:22 +01002422 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002423 return createUserInternal(name, flags, parentId, null);
2424 }
2425
2426 private UserInfo createUserInternal(String name, int flags, int parentId,
2427 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002428 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2429 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2430 : UserManager.DISALLOW_ADD_USER;
2431 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2432 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002433 return null;
2434 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002435 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2436 }
2437
2438 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2439 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002440 DeviceStorageMonitorInternal dsm = LocalServices
2441 .getService(DeviceStorageMonitorInternal.class);
2442 if (dsm.isMemoryLow()) {
2443 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2444 return null;
2445 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002446 if (ActivityManager.isLowRamDeviceStatic()) {
2447 return null;
2448 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002449 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002450 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002451 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002452 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002453 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002454 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002455 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002456 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002457 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002458 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002459 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002460 if (parentId != UserHandle.USER_NULL) {
2461 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002462 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002463 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002464 if (parent == null) return null;
2465 }
2466 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2467 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2468 return null;
2469 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002470 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2471 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002472 // been reached, cannot add a user.
2473 return null;
2474 }
2475 // If we're adding a guest and there already exists one, bail.
2476 if (isGuest && findCurrentGuestUser() != null) {
2477 return null;
2478 }
2479 // In legacy mode, restricted profile's parent can only be the owner user
2480 if (isRestricted && !UserManager.isSplitSystemUser()
2481 && (parentId != UserHandle.USER_SYSTEM)) {
2482 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2483 return null;
2484 }
2485 if (isRestricted && UserManager.isSplitSystemUser()) {
2486 if (parent == null) {
2487 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2488 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002489 return null;
2490 }
Amith Yamasani12747872015-12-07 14:19:49 -08002491 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002492 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2493 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002494 return null;
2495 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002496 }
2497 // In split system user mode, we assign the first human user the primary flag.
2498 // And if there is no device owner, we also assign the admin flag to primary user.
2499 if (UserManager.isSplitSystemUser()
2500 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2501 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002502 synchronized (mUsersLock) {
2503 if (!mIsDeviceManaged) {
2504 flags |= UserInfo.FLAG_ADMIN;
2505 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002506 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002507 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002508
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002509 userId = getNextAvailableId();
2510 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002511 boolean ephemeralGuests = Resources.getSystem()
2512 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002513
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002514 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002515 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2516 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2517 || (parent != null && parent.info.isEphemeral())) {
2518 flags |= UserInfo.FLAG_EPHEMERAL;
2519 }
2520
2521 userInfo = new UserInfo(userId, name, null, flags);
2522 userInfo.serialNumber = mNextSerialNumber++;
2523 long now = System.currentTimeMillis();
2524 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2525 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002526 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002527 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2528 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2529 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002530 userData = new UserData();
2531 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002532 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002533 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002534 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002535 writeUserListLP();
2536 if (parent != null) {
2537 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002538 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2539 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002540 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002541 }
Amith Yamasani12747872015-12-07 14:19:49 -08002542 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002543 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002544 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2545 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002546 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002547 }
Amith Yamasani12747872015-12-07 14:19:49 -08002548 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002549 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002550 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002551 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002552 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002553 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002554 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002555 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002556 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002557 userInfo.partial = false;
2558 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002559 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002560 }
2561 updateUserIds();
2562 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002563 if (isGuest) {
2564 synchronized (mGuestRestrictions) {
2565 restrictions.putAll(mGuestRestrictions);
2566 }
2567 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002568 synchronized (mRestrictionsLock) {
2569 mBaseUserRestrictions.append(userId, restrictions);
2570 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002571 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002572 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2573 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2574 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2575 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002576 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2577 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002578 } finally {
2579 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002580 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002581 return userInfo;
2582 }
2583
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002584 @VisibleForTesting
2585 UserData putUserInfo(UserInfo userInfo) {
2586 final UserData userData = new UserData();
2587 userData.info = userInfo;
2588 synchronized (mUsers) {
2589 mUsers.put(userInfo.id, userData);
2590 }
2591 return userData;
2592 }
2593
2594 @VisibleForTesting
2595 void removeUserInfo(int userId) {
2596 synchronized (mUsers) {
2597 mUsers.remove(userId);
2598 }
2599 }
2600
Amith Yamasani0b285492011-04-14 17:35:23 -07002601 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002602 * @hide
2603 */
Amith Yamasani12747872015-12-07 14:19:49 -08002604 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002605 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002606 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002607 final UserInfo user = createProfileForUser(
2608 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002609 if (user == null) {
2610 return null;
2611 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002612 long identity = Binder.clearCallingIdentity();
2613 try {
2614 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2615 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2616 // the putIntForUser() will fail.
2617 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2618 android.provider.Settings.Secure.LOCATION_MODE,
2619 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2620 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2621 } finally {
2622 Binder.restoreCallingIdentity(identity);
2623 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002624 return user;
2625 }
2626
2627 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002628 * Find the current guest user. If the Guest user is partial,
2629 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002630 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002631 private UserInfo findCurrentGuestUser() {
2632 synchronized (mUsersLock) {
2633 final int size = mUsers.size();
2634 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002635 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002636 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2637 return user;
2638 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002639 }
2640 }
2641 return null;
2642 }
2643
2644 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002645 * Mark this guest user for deletion to allow us to create another guest
2646 * and switch to that user before actually removing this guest.
2647 * @param userHandle the userid of the current guest
2648 * @return whether the user could be marked for deletion
2649 */
Amith Yamasani12747872015-12-07 14:19:49 -08002650 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002651 public boolean markGuestForDeletion(int userHandle) {
2652 checkManageUsersPermission("Only the system can remove users");
2653 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2654 UserManager.DISALLOW_REMOVE_USER, false)) {
2655 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2656 return false;
2657 }
2658
2659 long ident = Binder.clearCallingIdentity();
2660 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002661 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002662 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002663 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002664 userData = mUsers.get(userHandle);
2665 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002666 return false;
2667 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002668 }
Amith Yamasani12747872015-12-07 14:19:49 -08002669 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002670 return false;
2671 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002672 // We set this to a guest user that is to be removed. This is a temporary state
2673 // where we are allowed to add new Guest users, even if this one is still not
2674 // removed. This user will still show up in getUserInfo() calls.
2675 // If we don't get around to removing this Guest user, it will be purged on next
2676 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002677 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002678 // Mark it as disabled, so that it isn't returned any more when
2679 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002680 userData.info.flags |= UserInfo.FLAG_DISABLED;
2681 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002682 }
2683 } finally {
2684 Binder.restoreCallingIdentity(ident);
2685 }
2686 return true;
2687 }
2688
2689 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002690 * Removes a user and all data directories created for that user. This method should be called
2691 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002692 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002693 */
Amith Yamasani12747872015-12-07 14:19:49 -08002694 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002695 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002696 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002697 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002698
2699 final boolean isManagedProfile;
2700 synchronized (mUsersLock) {
2701 UserInfo userInfo = getUserInfoLU(userHandle);
2702 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2703 }
2704 String restriction = isManagedProfile
2705 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2706 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2707 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002708 return false;
2709 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002710 return removeUserUnchecked(userHandle);
2711 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002712
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002713 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002714 long ident = Binder.clearCallingIdentity();
2715 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002716 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002717 int currentUser = ActivityManager.getCurrentUser();
2718 if (currentUser == userHandle) {
2719 Log.w(LOG_TAG, "Current user cannot be removed");
2720 return false;
2721 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002722 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002723 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002724 userData = mUsers.get(userHandle);
2725 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002726 return false;
2727 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002728
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002729 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002730 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002731
Kenny Guyee58b4f2014-05-23 15:19:53 +01002732 // Set this to a partially created user, so that the user will be purged
2733 // on next startup, in case the runtime stops now before stopping and
2734 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002735 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002736 // Mark it as disabled, so that it isn't returned any more when
2737 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002738 userData.info.flags |= UserInfo.FLAG_DISABLED;
2739 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002740 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002741 try {
2742 mAppOpsService.removeUser(userHandle);
2743 } catch (RemoteException e) {
2744 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2745 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002746
Amith Yamasani12747872015-12-07 14:19:49 -08002747 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2748 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002749 // Send broadcast to notify system that the user removed was a
2750 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002751 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002752 }
2753
2754 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2755 int res;
2756 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002757 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002758 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002759 @Override
2760 public void userStopped(int userId) {
2761 finishRemoveUser(userId);
2762 }
2763 @Override
2764 public void userStopAborted(int userId) {
2765 }
2766 });
2767 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002768 return false;
2769 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002770 return res == ActivityManager.USER_OP_SUCCESS;
2771 } finally {
2772 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002773 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002774 }
2775
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002776 @VisibleForTesting
2777 void addRemovingUserIdLocked(int userId) {
2778 // We remember deleted user IDs to prevent them from being
2779 // reused during the current boot; they can still be reused
2780 // after a reboot or recycling of userIds.
2781 mRemovingUserIds.put(userId, true);
2782 mRecentlyRemovedIds.add(userId);
2783 // Keep LRU queue of recently removed IDs for recycling
2784 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2785 mRecentlyRemovedIds.removeFirst();
2786 }
2787 }
2788
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002789 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002790 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002791 // Let other services shutdown any activity and clean up their state before completely
2792 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002793 long ident = Binder.clearCallingIdentity();
2794 try {
2795 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2796 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002797 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2798 android.Manifest.permission.MANAGE_USERS,
2799
2800 new BroadcastReceiver() {
2801 @Override
2802 public void onReceive(Context context, Intent intent) {
2803 if (DBG) {
2804 Slog.i(LOG_TAG,
2805 "USER_REMOVED broadcast sent, cleaning up user data "
2806 + userHandle);
2807 }
2808 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002809 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002810 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002811 // Clean up any ActivityManager state
2812 LocalServices.getService(ActivityManagerInternal.class)
2813 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002814 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002815 }
2816 }.start();
2817 }
2818 },
2819
2820 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002821 } finally {
2822 Binder.restoreCallingIdentity(ident);
2823 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002824 }
2825
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002826 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002827 try {
2828 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2829 } catch (IllegalStateException e) {
2830 // This may be simply because the user was partially created.
2831 Slog.i(LOG_TAG,
2832 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2833 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002834
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002835 // Cleanup gatekeeper secure user id
2836 try {
2837 final IGateKeeperService gk = GateKeeper.getService();
2838 if (gk != null) {
2839 gk.clearSecureUserId(userHandle);
2840 }
2841 } catch (Exception ex) {
2842 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2843 }
2844
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002845 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002846 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002847
2848 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002849 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002850 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2851
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002852 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002853 synchronized (mUsersLock) {
2854 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002855 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002856 }
2857 synchronized (mUserStates) {
2858 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002859 }
2860 synchronized (mRestrictionsLock) {
2861 mBaseUserRestrictions.remove(userHandle);
2862 mAppliedUserRestrictions.remove(userHandle);
2863 mCachedEffectiveUserRestrictions.remove(userHandle);
2864 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002865 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2866 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2867 applyUserRestrictionsForAllUsersLR();
2868 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002869 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002870 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002871 synchronized (mPackagesLock) {
2872 writeUserListLP();
2873 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002874 // Remove user file
2875 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2876 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002877 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002878 if (RELEASE_DELETED_USER_ID) {
2879 synchronized (mUsers) {
2880 mRemovingUserIds.delete(userHandle);
2881 }
2882 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002883 }
2884
Kenny Guyf8d3a232014-05-15 16:09:52 +01002885 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002886 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002887 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2888 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002889 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002890 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002891 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002892 }
2893
Amith Yamasani2a003292012-08-14 18:25:45 -07002894 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002895 public Bundle getApplicationRestrictions(String packageName) {
2896 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2897 }
2898
2899 @Override
2900 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002901 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002902 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002903 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002904 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002905 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002906 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002907 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002908 }
2909 }
2910
2911 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002912 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002913 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002914 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002915 if (restrictions != null) {
2916 restrictions.setDefusable(true);
2917 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002918 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002919 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002920 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002921 } else {
2922 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002923 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002924 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002925 }
Robin Lee66e5d962014-04-09 16:44:21 +01002926
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002927 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2928 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2929 changeIntent.setPackage(packageName);
2930 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2931 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002932 }
2933
2934 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002935 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002936 try {
2937 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002938 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002939 } catch (NameNotFoundException nnfe) {
2940 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002941 } finally {
2942 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002943 }
2944 }
2945
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002946 @GuardedBy("mAppRestrictionsLock")
2947 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002948 AtomicFile restrictionsFile =
2949 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2950 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002951 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002952 }
2953
2954 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002955 @GuardedBy("mAppRestrictionsLock")
2956 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002957 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002958 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002959 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002960 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002961 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002962
2963 FileInputStream fis = null;
2964 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002965 fis = restrictionsFile.openRead();
2966 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002967 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002968 XmlUtils.nextElement(parser);
2969 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002970 Slog.e(LOG_TAG, "Unable to read restrictions file "
2971 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002972 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002973 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002974 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2975 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002976 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002977 } catch (IOException|XmlPullParserException e) {
2978 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002979 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002980 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002981 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002982 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002983 }
2984
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002985 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2986 XmlPullParser parser) throws XmlPullParserException, IOException {
2987 int type = parser.getEventType();
2988 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2989 String key = parser.getAttributeValue(null, ATTR_KEY);
2990 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2991 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2992 if (multiple != null) {
2993 values.clear();
2994 int count = Integer.parseInt(multiple);
2995 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2996 if (type == XmlPullParser.START_TAG
2997 && parser.getName().equals(TAG_VALUE)) {
2998 values.add(parser.nextText().trim());
2999 count--;
3000 }
3001 }
3002 String [] valueStrings = new String[values.size()];
3003 values.toArray(valueStrings);
3004 restrictions.putStringArray(key, valueStrings);
3005 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3006 restrictions.putBundle(key, readBundleEntry(parser, values));
3007 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3008 final int outerDepth = parser.getDepth();
3009 ArrayList<Bundle> bundleList = new ArrayList<>();
3010 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3011 Bundle childBundle = readBundleEntry(parser, values);
3012 bundleList.add(childBundle);
3013 }
3014 restrictions.putParcelableArray(key,
3015 bundleList.toArray(new Bundle[bundleList.size()]));
3016 } else {
3017 String value = parser.nextText().trim();
3018 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3019 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3020 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3021 restrictions.putInt(key, Integer.parseInt(value));
3022 } else {
3023 restrictions.putString(key, value);
3024 }
3025 }
3026 }
3027 }
3028
3029 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3030 throws IOException, XmlPullParserException {
3031 Bundle childBundle = new Bundle();
3032 final int outerDepth = parser.getDepth();
3033 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3034 readEntry(childBundle, values, parser);
3035 }
3036 return childBundle;
3037 }
3038
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003039 @GuardedBy("mAppRestrictionsLock")
3040 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003041 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003042 AtomicFile restrictionsFile = new AtomicFile(
3043 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003044 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003045 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003046 }
3047
3048 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003049 @GuardedBy("mAppRestrictionsLock")
3050 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003051 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003052 try {
3053 fos = restrictionsFile.startWrite();
3054 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3055
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003056 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003057 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003058 serializer.startDocument(null, true);
3059 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3060
3061 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003062 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003063 serializer.endTag(null, TAG_RESTRICTIONS);
3064
3065 serializer.endDocument();
3066 restrictionsFile.finishWrite(fos);
3067 } catch (Exception e) {
3068 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003069 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3070 }
3071 }
3072
3073 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3074 throws IOException {
3075 for (String key : restrictions.keySet()) {
3076 Object value = restrictions.get(key);
3077 serializer.startTag(null, TAG_ENTRY);
3078 serializer.attribute(null, ATTR_KEY, key);
3079
3080 if (value instanceof Boolean) {
3081 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3082 serializer.text(value.toString());
3083 } else if (value instanceof Integer) {
3084 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3085 serializer.text(value.toString());
3086 } else if (value == null || value instanceof String) {
3087 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3088 serializer.text(value != null ? (String) value : "");
3089 } else if (value instanceof Bundle) {
3090 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3091 writeBundle((Bundle) value, serializer);
3092 } else if (value instanceof Parcelable[]) {
3093 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3094 Parcelable[] array = (Parcelable[]) value;
3095 for (Parcelable parcelable : array) {
3096 if (!(parcelable instanceof Bundle)) {
3097 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3098 }
3099 serializer.startTag(null, TAG_ENTRY);
3100 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3101 writeBundle((Bundle) parcelable, serializer);
3102 serializer.endTag(null, TAG_ENTRY);
3103 }
3104 } else {
3105 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3106 String[] values = (String[]) value;
3107 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3108 for (String choice : values) {
3109 serializer.startTag(null, TAG_VALUE);
3110 serializer.text(choice != null ? choice : "");
3111 serializer.endTag(null, TAG_VALUE);
3112 }
3113 }
3114 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003115 }
3116 }
3117
3118 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003119 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003120 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003121 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003122 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003123 }
3124 }
3125
3126 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003127 public boolean isUserNameSet(int userHandle) {
3128 synchronized (mUsersLock) {
3129 UserInfo userInfo = getUserInfoLU(userHandle);
3130 return userInfo != null && userInfo.name != null;
3131 }
3132 }
3133
3134 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003135 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003136 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003137 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003138 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003139 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003140 }
3141 // Not found
3142 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003143 }
3144 }
3145
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003146 @Override
3147 public long getUserCreationTime(int userHandle) {
3148 int callingUserId = UserHandle.getCallingUserId();
3149 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003150 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003151 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003152 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003153 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003154 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003155 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003156 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003157 }
3158 }
3159 }
3160 if (userInfo == null) {
3161 throw new SecurityException("userHandle can only be the calling user or a managed "
3162 + "profile associated with this user");
3163 }
3164 return userInfo.creationTime;
3165 }
3166
Amith Yamasani0b285492011-04-14 17:35:23 -07003167 /**
3168 * Caches the list of user ids in an array, adjusting the array size when necessary.
3169 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003170 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003171 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003172 synchronized (mUsersLock) {
3173 final int userSize = mUsers.size();
3174 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003175 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003176 num++;
3177 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003178 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003179 final int[] newUsers = new int[num];
3180 int n = 0;
3181 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003182 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003183 newUsers[n++] = mUsers.keyAt(i);
3184 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003185 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003186 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003187 }
3188 }
3189
3190 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003191 * Called right before a user is started. This gives us a chance to prepare
3192 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003193 */
3194 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003195 UserInfo userInfo = getUserInfo(userId);
3196 if (userInfo == null) {
3197 return;
3198 }
3199 final int userSerial = userInfo.serialNumber;
3200 // Migrate only if build fingerprints mismatch
3201 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003202 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003203 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003204
3205 if (userId != UserHandle.USER_SYSTEM) {
3206 synchronized (mRestrictionsLock) {
3207 applyUserRestrictionsLR(userId);
3208 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003209 }
3210 }
3211
3212 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003213 * Called right before a user is unlocked. This gives us a chance to prepare
3214 * app storage.
3215 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003216 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003217 UserInfo userInfo = getUserInfo(userId);
3218 if (userInfo == null) {
3219 return;
3220 }
3221 final int userSerial = userInfo.serialNumber;
3222 // Migrate only if build fingerprints mismatch
3223 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003224 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003225 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003226 }
3227
3228 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003229 * Examine all users present on given mounted volume, and destroy data
3230 * belonging to users that are no longer valid, or whose user ID has been
3231 * recycled.
3232 */
3233 void reconcileUsers(String volumeUuid) {
3234 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3235 }
3236
3237 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003238 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003239 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003240 * @param userId the user that was just foregrounded
3241 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003242 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003243 UserData userData = getUserDataNoChecks(userId);
3244 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003245 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3246 return;
3247 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003248
3249 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003250 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003251 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003252 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003253 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3254 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003255 }
3256
3257 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003258 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003259 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003260 @VisibleForTesting
3261 int getNextAvailableId() {
3262 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003263 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003264 nextId = scanNextAvailableIdLocked();
3265 if (nextId >= 0) {
3266 return nextId;
3267 }
3268 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3269 // except most recently removed
3270 if (mRemovingUserIds.size() > 0) {
3271 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3272 mRemovingUserIds.clear();
3273 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3274 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003275 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003276 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003277 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003278 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003279 if (nextId < 0) {
3280 throw new IllegalStateException("No user id available!");
3281 }
3282 return nextId;
3283 }
3284
3285 private int scanNextAvailableIdLocked() {
3286 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3287 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3288 return i;
3289 }
3290 }
3291 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003292 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003293
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003294 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003295 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3296 }
3297
Amith Yamasani920ace02012-09-20 22:15:37 -07003298 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003299 public void setSeedAccountData(int userId, String accountName, String accountType,
3300 PersistableBundle accountOptions, boolean persist) {
3301 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3302 synchronized (mPackagesLock) {
3303 final UserData userData;
3304 synchronized (mUsersLock) {
3305 userData = getUserDataLU(userId);
3306 if (userData == null) {
3307 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3308 return;
3309 }
3310 userData.seedAccountName = accountName;
3311 userData.seedAccountType = accountType;
3312 userData.seedAccountOptions = accountOptions;
3313 userData.persistSeedData = persist;
3314 }
3315 if (persist) {
3316 writeUserLP(userData);
3317 }
3318 }
3319 }
3320
3321 @Override
3322 public String getSeedAccountName() throws RemoteException {
3323 checkManageUsersPermission("Cannot get seed account information");
3324 synchronized (mUsersLock) {
3325 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3326 return userData.seedAccountName;
3327 }
3328 }
3329
3330 @Override
3331 public String getSeedAccountType() throws RemoteException {
3332 checkManageUsersPermission("Cannot get seed account information");
3333 synchronized (mUsersLock) {
3334 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3335 return userData.seedAccountType;
3336 }
3337 }
3338
3339 @Override
3340 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3341 checkManageUsersPermission("Cannot get seed account information");
3342 synchronized (mUsersLock) {
3343 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3344 return userData.seedAccountOptions;
3345 }
3346 }
3347
3348 @Override
3349 public void clearSeedAccountData() throws RemoteException {
3350 checkManageUsersPermission("Cannot clear seed account information");
3351 synchronized (mPackagesLock) {
3352 UserData userData;
3353 synchronized (mUsersLock) {
3354 userData = getUserDataLU(UserHandle.getCallingUserId());
3355 if (userData == null) return;
3356 userData.clearSeedAccountData();
3357 }
3358 writeUserLP(userData);
3359 }
3360 }
3361
3362 @Override
3363 public boolean someUserHasSeedAccount(String accountName, String accountType)
3364 throws RemoteException {
3365 checkManageUsersPermission("Cannot check seed account information");
3366 synchronized (mUsersLock) {
3367 final int userSize = mUsers.size();
3368 for (int i = 0; i < userSize; i++) {
3369 final UserData data = mUsers.valueAt(i);
3370 if (data.info.isInitialized()) continue;
3371 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3372 continue;
3373 }
3374 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3375 continue;
3376 }
3377 return true;
3378 }
3379 }
3380 return false;
3381 }
3382
3383 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003384 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003385 FileDescriptor err, String[] args, ShellCallback callback,
3386 ResultReceiver resultReceiver) {
3387 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003388 }
3389
3390 int onShellCommand(Shell shell, String cmd) {
3391 if (cmd == null) {
3392 return shell.handleDefaultCommands(cmd);
3393 }
3394
3395 final PrintWriter pw = shell.getOutPrintWriter();
3396 try {
3397 switch(cmd) {
3398 case "list":
3399 return runList(pw);
3400 }
3401 } catch (RemoteException e) {
3402 pw.println("Remote exception: " + e);
3403 }
3404 return -1;
3405 }
3406
3407 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003408 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003409 final List<UserInfo> users = getUsers(false);
3410 if (users == null) {
3411 pw.println("Error: couldn't get users");
3412 return 1;
3413 } else {
3414 pw.println("Users:");
3415 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003416 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003417 pw.println("\t" + users.get(i).toString() + running);
3418 }
3419 return 0;
3420 }
3421 }
3422
3423 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003424 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003425 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003426
3427 long now = System.currentTimeMillis();
3428 StringBuilder sb = new StringBuilder();
3429 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003430 synchronized (mUsersLock) {
3431 pw.println("Users:");
3432 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003433 UserData userData = mUsers.valueAt(i);
3434 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003435 continue;
3436 }
Amith Yamasani12747872015-12-07 14:19:49 -08003437 UserInfo userInfo = userData.info;
3438 final int userId = userInfo.id;
3439 pw.print(" "); pw.print(userInfo);
3440 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003441 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003442 pw.print(" <removing> ");
3443 }
Amith Yamasani12747872015-12-07 14:19:49 -08003444 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003445 pw.print(" <partial>");
3446 }
3447 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003448 pw.print(" State: ");
3449 final int state;
3450 synchronized (mUserStates) {
3451 state = mUserStates.get(userId, -1);
3452 }
3453 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003454 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003455 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003456 pw.println("<unknown>");
3457 } else {
3458 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003459 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003460 sb.append(" ago");
3461 pw.println(sb);
3462 }
3463 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003464 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003465 pw.println("<unknown>");
3466 } else {
3467 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003468 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003469 sb.append(" ago");
3470 pw.println(sb);
3471 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003472 pw.print(" Last logged in fingerprint: ");
3473 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003474 pw.print(" Has profile owner: ");
3475 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003476 pw.println(" Restrictions:");
3477 synchronized (mRestrictionsLock) {
3478 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003479 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003480 pw.println(" Device policy global restrictions:");
3481 UserRestrictionsUtils.dumpRestrictions(
3482 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003483 pw.println(" Device policy local restrictions:");
3484 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003485 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003486 pw.println(" Effective restrictions:");
3487 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003488 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003489 }
Amith Yamasani12747872015-12-07 14:19:49 -08003490
3491 if (userData.account != null) {
3492 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003493 pw.println();
3494 }
Amith Yamasani12747872015-12-07 14:19:49 -08003495
3496 if (userData.seedAccountName != null) {
3497 pw.print(" Seed account name: " + userData.seedAccountName);
3498 pw.println();
3499 if (userData.seedAccountType != null) {
3500 pw.print(" account type: " + userData.seedAccountType);
3501 pw.println();
3502 }
3503 if (userData.seedAccountOptions != null) {
3504 pw.print(" account options exist");
3505 pw.println();
3506 }
3507 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003508 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003509 }
Amith Yamasani12747872015-12-07 14:19:49 -08003510 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003511 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003512 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003513 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003514 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003515 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003516 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003517 synchronized (mUsersLock) {
3518 pw.println();
3519 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003520 if (mRemovingUserIds.size() > 0) {
3521 pw.println();
3522 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3523 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003524 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003525 synchronized (mUserStates) {
3526 pw.println(" Started users state: " + mUserStates);
3527 }
Amith Yamasani12747872015-12-07 14:19:49 -08003528 // Dump some capabilities
3529 pw.println();
3530 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3531 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003532 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3533 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003534 }
3535 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003536
3537 final class MainHandler extends Handler {
3538
3539 @Override
3540 public void handleMessage(Message msg) {
3541 switch (msg.what) {
3542 case WRITE_USER_MSG:
3543 removeMessages(WRITE_USER_MSG, msg.obj);
3544 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003545 int userId = ((UserData) msg.obj).info.id;
3546 UserData userData = getUserDataNoChecks(userId);
3547 if (userData != null) {
3548 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003549 }
3550 }
3551 }
3552 }
3553 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003554
3555 /**
3556 * @param userId
3557 * @return whether the user has been initialized yet
3558 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003559 boolean isUserInitialized(int userId) {
3560 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003561 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003562
3563 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003564 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003565 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3566 boolean isDeviceOwner, int cameraRestrictionScope) {
3567 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3568 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003569 }
3570
3571 @Override
3572 public Bundle getBaseUserRestrictions(int userId) {
3573 synchronized (mRestrictionsLock) {
3574 return mBaseUserRestrictions.get(userId);
3575 }
3576 }
3577
3578 @Override
3579 public void setBaseUserRestrictionsByDpmsForMigration(
3580 int userId, Bundle baseRestrictions) {
3581 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003582 if (updateRestrictionsIfNeededLR(
3583 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3584 invalidateEffectiveUserRestrictionsLR(userId);
3585 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003586 }
3587
Amith Yamasani12747872015-12-07 14:19:49 -08003588 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003589 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003590 if (userData != null) {
3591 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003592 } else {
3593 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3594 }
3595 }
3596 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003597
3598 @Override
3599 public boolean getUserRestriction(int userId, String key) {
3600 return getUserRestrictions(userId).getBoolean(key);
3601 }
3602
3603 @Override
3604 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3605 synchronized (mUserRestrictionsListeners) {
3606 mUserRestrictionsListeners.add(listener);
3607 }
3608 }
3609
3610 @Override
3611 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3612 synchronized (mUserRestrictionsListeners) {
3613 mUserRestrictionsListeners.remove(listener);
3614 }
3615 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003616
3617 @Override
3618 public void setDeviceManaged(boolean isManaged) {
3619 synchronized (mUsersLock) {
3620 mIsDeviceManaged = isManaged;
3621 }
3622 }
3623
3624 @Override
3625 public void setUserManaged(int userId, boolean isManaged) {
3626 synchronized (mUsersLock) {
3627 mIsUserManaged.put(userId, isManaged);
3628 }
3629 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003630
3631 @Override
3632 public void setUserIcon(int userId, Bitmap bitmap) {
3633 long ident = Binder.clearCallingIdentity();
3634 try {
3635 synchronized (mPackagesLock) {
3636 UserData userData = getUserDataNoChecks(userId);
3637 if (userData == null || userData.info.partial) {
3638 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3639 return;
3640 }
3641 writeBitmapLP(userData.info, bitmap);
3642 writeUserLP(userData);
3643 }
3644 sendUserInfoChangedBroadcast(userId);
3645 } finally {
3646 Binder.restoreCallingIdentity(ident);
3647 }
3648 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003649
3650 @Override
3651 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3652 synchronized (mUsersLock) {
3653 mForceEphemeralUsers = forceEphemeralUsers;
3654 }
3655 }
3656
3657 @Override
3658 public void removeAllUsers() {
3659 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3660 // Remove the non-system users straight away.
3661 removeNonSystemUsers();
3662 } else {
3663 // Switch to the system user first and then remove the other users.
3664 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3665 @Override
3666 public void onReceive(Context context, Intent intent) {
3667 int userId =
3668 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3669 if (userId != UserHandle.USER_SYSTEM) {
3670 return;
3671 }
3672 mContext.unregisterReceiver(this);
3673 removeNonSystemUsers();
3674 }
3675 };
3676 IntentFilter userSwitchedFilter = new IntentFilter();
3677 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3678 mContext.registerReceiver(
3679 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3680
3681 // Switch to the system user.
3682 ActivityManager am =
3683 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3684 am.switchUser(UserHandle.USER_SYSTEM);
3685 }
3686 }
phweisse9c44062016-02-10 12:57:38 +01003687
3688 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003689 public void onEphemeralUserStop(int userId) {
3690 synchronized (mUsersLock) {
3691 UserInfo userInfo = getUserInfoLU(userId);
3692 if (userInfo != null && userInfo.isEphemeral()) {
3693 // Do not allow switching back to the ephemeral user again as the user is going
3694 // to be deleted.
3695 userInfo.flags |= UserInfo.FLAG_DISABLED;
3696 if (userInfo.isGuest()) {
3697 // Indicate that the guest will be deleted after it stops.
3698 userInfo.guestToRemove = true;
3699 }
3700 }
3701 }
3702 }
3703
3704 @Override
phweisse9c44062016-02-10 12:57:38 +01003705 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003706 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003707 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003708 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003709 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3710 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3711 }
3712 return user;
3713 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003714
3715 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003716 public boolean removeUserEvenWhenDisallowed(int userId) {
3717 return removeUserUnchecked(userId);
3718 }
3719
3720 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003721 public boolean isUserRunning(int userId) {
3722 synchronized (mUserStates) {
3723 return mUserStates.get(userId, -1) >= 0;
3724 }
3725 }
3726
3727 @Override
3728 public void setUserState(int userId, int userState) {
3729 synchronized (mUserStates) {
3730 mUserStates.put(userId, userState);
3731 }
3732 }
3733
3734 @Override
3735 public void removeUserState(int userId) {
3736 synchronized (mUserStates) {
3737 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003738 }
3739 }
3740
3741 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003742 public int[] getUserIds() {
3743 return UserManagerService.this.getUserIds();
3744 }
3745
3746 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003747 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003748 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003749 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003750 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003751 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003752 // Special case, in the stopping/shutdown state user key can still be unlocked
3753 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3754 return StorageManager.isUserKeyUnlocked(userId);
3755 }
3756 return (state == UserState.STATE_RUNNING_UNLOCKING)
3757 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003758 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003759
3760 @Override
3761 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003762 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003763 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003764 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003765 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003766 // Special case, in the stopping/shutdown state user key can still be unlocked
3767 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3768 return StorageManager.isUserKeyUnlocked(userId);
3769 }
3770 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003771 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003772
3773 @Override
3774 public boolean isUserInitialized(int userId) {
3775 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3776 }
3777
3778 @Override
3779 public boolean exists(int userId) {
3780 return getUserInfoNoChecks(userId) != null;
3781 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003782 }
3783
3784 /* Remove all the users except of the system one. */
3785 private void removeNonSystemUsers() {
3786 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3787 synchronized (mUsersLock) {
3788 final int userSize = mUsers.size();
3789 for (int i = 0; i < userSize; i++) {
3790 UserInfo ui = mUsers.valueAt(i).info;
3791 if (ui.id != UserHandle.USER_SYSTEM) {
3792 usersToRemove.add(ui);
3793 }
3794 }
3795 }
3796 for (UserInfo ui: usersToRemove) {
3797 removeUser(ui.id);
3798 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003799 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003800
3801 private class Shell extends ShellCommand {
3802 @Override
3803 public int onCommand(String cmd) {
3804 return onShellCommand(this, cmd);
3805 }
3806
3807 @Override
3808 public void onHelp() {
3809 final PrintWriter pw = getOutPrintWriter();
3810 pw.println("User manager (user) commands:");
3811 pw.println(" help");
3812 pw.println(" Print this help text.");
3813 pw.println("");
3814 pw.println(" list");
3815 pw.println(" Prints all users on the system.");
3816 }
3817 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003818
3819 private static void debug(String message) {
3820 Log.d(LOG_TAG, message +
3821 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3822 }
Kenny Guy02c89902016-11-15 19:36:38 +00003823
3824 @VisibleForTesting
3825 static int getMaxManagedProfiles() {
3826 // Allow overriding max managed profiles on debuggable builds for testing
3827 // of multiple profiles.
3828 if (!Build.IS_DEBUGGABLE) {
3829 return MAX_MANAGED_PROFILES;
3830 } else {
3831 return SystemProperties.getInt("persist.sys.max_profiles",
3832 MAX_MANAGED_PROFILES);
3833 }
3834 }
3835
3836 @VisibleForTesting
3837 int getFreeProfileBadgeLU(int parentUserId) {
3838 int maxManagedProfiles = getMaxManagedProfiles();
3839 boolean[] usedBadges = new boolean[maxManagedProfiles];
3840 final int userSize = mUsers.size();
3841 for (int i = 0; i < userSize; i++) {
3842 UserInfo ui = mUsers.valueAt(i).info;
3843 // Check which badge indexes are already used by this profile group.
3844 if (ui.isManagedProfile()
3845 && ui.profileGroupId == parentUserId
3846 && !mRemovingUserIds.get(ui.id)
3847 && ui.profileBadge < maxManagedProfiles) {
3848 usedBadges[ui.profileBadge] = true;
3849 }
3850 }
3851 for (int i = 0; i < maxManagedProfiles; i++) {
3852 if (!usedBadges[i]) {
3853 return i;
3854 }
3855 }
3856 return 0;
3857 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003858
3859 /**
3860 * Checks if the given user has a managed profile associated with it.
3861 * @param userId The parent user
3862 * @return
3863 */
3864 boolean hasManagedProfile(int userId) {
3865 synchronized (mUsersLock) {
3866 UserInfo userInfo = getUserInfoLU(userId);
3867 final int userSize = mUsers.size();
3868 for (int i = 0; i < userSize; i++) {
3869 UserInfo profile = mUsers.valueAt(i).info;
3870 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3871 return true;
3872 }
3873 }
3874 return false;
3875 }
3876 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003877}