blob: 8ecf6f74bc8f0673a55d67f89e0e2ed6aafe40ce [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;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
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;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070074import android.system.ErrnoException;
75import android.system.Os;
76import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070077import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080092import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070093import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070094import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000095import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070096import com.android.server.LocalServices;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060097import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070098import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000099import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700100import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100101
Jeff Sharkey47f71082016-02-01 17:03:54 -0700102import libcore.io.IoUtils;
103import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800104
105import org.xmlpull.v1.XmlPullParser;
106import org.xmlpull.v1.XmlPullParserException;
107import org.xmlpull.v1.XmlSerializer;
108
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109import java.io.BufferedOutputStream;
110import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700111import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.io.FileOutputStream;
Kenny Guy02c89902016-11-15 19:36:38 +0000115import java.io.InputStream;
116import java.io.OutputStream;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700118import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100119import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100121import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700122import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123import java.util.List;
124
Makoto Onuki068c54a2015-10-13 14:34:03 -0700125/**
126 * Service for {@link UserManager}.
127 *
128 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700129 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800130 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700131 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
132 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
133 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700134 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700135public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700136
Amith Yamasani2a003292012-08-14 18:25:45 -0700137 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800138 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800139 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700140 // Can be used for manual testing of id recycling
141 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700142
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800144 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700146 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700148 private static final String ATTR_CREATION_TIME = "created";
149 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600150 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700151 private static final String ATTR_SERIAL_NO = "serialNumber";
152 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700153 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700154 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700155 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100156 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000157 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700158 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800159 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
160 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530161 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700162 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800164 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800165 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100166 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
167 "device_policy_global_restrictions";
168 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100169 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100170 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800171 private static final String TAG_ENTRY = "entry";
172 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800173 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800174 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700175 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700177
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700178 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
179 private static final String ATTR_TYPE_STRING = "s";
180 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700181 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700182 private static final String ATTR_TYPE_BUNDLE = "B";
183 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700184
Amith Yamasani0b285492011-04-14 17:35:23 -0700185 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700186 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700187 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100188 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700189
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800190 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700191 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800192
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700193 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
194 UserInfo.FLAG_MANAGED_PROFILE
195 | UserInfo.FLAG_EPHEMERAL
196 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700197 | UserInfo.FLAG_GUEST
198 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700199
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700200 @VisibleForTesting
201 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700202 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700203 @VisibleForTesting
204 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
205
206 // Max size of the queue of recently removed users
207 @VisibleForTesting
208 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700209
Pavel Grafov6a40f092016-10-25 15:46:51 +0100210 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700211
Amith Yamasani920ace02012-09-20 22:15:37 -0700212 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
213
Nicolas Prevotb8186812015-08-06 15:00:03 +0100214 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700215 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000216 @VisibleForTesting
217 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700218
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800219 static final int WRITE_USER_MSG = 1;
220 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530221
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800222 // Tron counters
223 private static final String TRON_GUEST_CREATED = "users_guest_created";
224 private static final String TRON_USER_CREATED = "users_user_created";
225
Dianne Hackborn4428e172012-08-24 17:43:05 -0700226 private final Context mContext;
227 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700228 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800229 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700230 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600231 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700232 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700233
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800234 private final Handler mHandler;
235
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700236 private final File mUsersDir;
237 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700238
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800239 private static final IBinder mUserRestriconToken = new Binder();
240
Makoto Onuki068c54a2015-10-13 14:34:03 -0700241 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800242 * User-related information that is used for persisting to flash. Only UserInfo is
243 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800244 */
Kenny Guy02c89902016-11-15 19:36:38 +0000245 @VisibleForTesting
246 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800247 // Basic user information and properties
248 UserInfo info;
249 // Account name used when there is a strong association between a user and an account
250 String account;
251 // Account information for seeding into a newly created user. This could also be
252 // used for login validation for an existing user, for updating their credentials.
253 // In the latter case, data may not need to be persisted as it is only valid for the
254 // current login session.
255 String seedAccountName;
256 String seedAccountType;
257 PersistableBundle seedAccountOptions;
258 // Whether to perist the seed account information to be available after a boot
259 boolean persistSeedData;
260
261 void clearSeedAccountData() {
262 seedAccountName = null;
263 seedAccountType = null;
264 seedAccountOptions = null;
265 persistSeedData = false;
266 }
267 }
268
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800269 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800270 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800271
272 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700273 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100274 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700275 *
276 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
277 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
278 * maybe shared between {@link #mBaseUserRestrictions} and
279 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
280 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700281 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700282 */
283 @GuardedBy("mRestrictionsLock")
284 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
285
286 /**
287 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
288 * with device / profile owner restrictions. We'll initialize it lazily; use
289 * {@link #getEffectiveUserRestrictions} to access it.
290 *
291 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
292 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
293 * maybe shared between {@link #mBaseUserRestrictions} and
294 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
295 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700296 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700297 */
298 @GuardedBy("mRestrictionsLock")
299 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
300
Makoto Onuki4f160732015-10-27 17:15:38 -0700301 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800302 * User restrictions that have already been applied in
303 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
304 * that have changed since the last
305 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700306 */
307 @GuardedBy("mRestrictionsLock")
308 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
309
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800310 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800311 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100312 * that should be applied to all users, including guests. Only non-empty restriction bundles are
313 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800314 */
315 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100316 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800317
318 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100319 * Id of the user that set global restrictions.
320 */
321 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100322 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100323
324 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800325 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100326 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800327 */
328 @GuardedBy("mRestrictionsLock")
329 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
330
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800331 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530332 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800333
334 /**
335 * Set of user IDs being actively removed. Removed IDs linger in this set
336 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700337 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800338 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700339 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800340 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700341
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700342 /**
343 * Queue of recently removed userIds. Used for recycling of userIds
344 */
345 @GuardedBy("mUsersLock")
346 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
347
Fyodor Kupolov82402752015-10-28 14:54:51 -0700348 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700349 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800350 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700351 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700352 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700353
Jason Monk62062992014-05-06 09:55:28 -0400354 private IAppOpsService mAppOpsService;
355
Makoto Onuki068c54a2015-10-13 14:34:03 -0700356 private final LocalService mLocalService;
357
Makoto Onukie7927da2015-11-25 10:05:17 -0800358 @GuardedBy("mUsersLock")
359 private boolean mIsDeviceManaged;
360
361 @GuardedBy("mUsersLock")
362 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
363
Makoto Onukid45a4a22015-11-02 17:17:38 -0800364 @GuardedBy("mUserRestrictionsListeners")
365 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
366 new ArrayList<>();
367
Clara Bayarria1771112015-12-18 16:29:18 +0000368 private final LockPatternUtils mLockPatternUtils;
369
Ricky Waib1dd80b2016-06-07 18:00:55 +0100370 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
371 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
372
373 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
374 @Override
375 public void onReceive(Context context, Intent intent) {
376 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
377 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
378 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
379 setQuietModeEnabled(userHandle, false);
380 if (target != null) {
381 try {
382 mContext.startIntentSender(target, null, 0, 0, 0);
383 } catch (IntentSender.SendIntentException e) {
384 /* ignore */
385 }
386 }
387 }
388 }
389 };
390
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100391 /**
392 * Whether all users should be created ephemeral.
393 */
394 @GuardedBy("mUsersLock")
395 private boolean mForceEphemeralUsers;
396
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000397 @GuardedBy("mUserStates")
398 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700399
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700401
Dianne Hackborn4428e172012-08-24 17:43:05 -0700402 public static UserManagerService getInstance() {
403 synchronized (UserManagerService.class) {
404 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700405 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700406 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700407
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700408 public static class LifeCycle extends SystemService {
409
410 private UserManagerService mUms;
411
412 /**
413 * @param context
414 */
415 public LifeCycle(Context context) {
416 super(context);
417 }
418
419 @Override
420 public void onStart() {
421 mUms = UserManagerService.getInstance();
422 publishBinderService(Context.USER_SERVICE, mUms);
423 }
424
425 @Override
426 public void onBootPhase(int phase) {
427 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
428 mUms.cleanupPartialUsers();
429 }
430 }
431 }
432
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700433 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800434 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700435 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800436 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700437 }
438
Dianne Hackborn4428e172012-08-24 17:43:05 -0700439 /**
440 * Called by package manager to create the service. This is closely
441 * associated with the package manager, and the given lock is the
442 * package manager's own lock.
443 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800444 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
445 Object packagesLock) {
446 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700447 }
448
Dianne Hackborn4428e172012-08-24 17:43:05 -0700449 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800450 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700451 mContext = context;
452 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700453 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800454 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800455 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800456 synchronized (mPackagesLock) {
457 mUsersDir = new File(dataDir, USER_INFO_DIR);
458 mUsersDir.mkdirs();
459 // Make zeroth user directory, for services to migrate their files to that location
460 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
461 userZeroDir.mkdirs();
462 FileUtils.setPermissions(mUsersDir.toString(),
463 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
464 -1, -1);
465 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
466 initDefaultGuestRestrictions();
467 readUserListLP();
468 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700469 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700470 mLocalService = new LocalService();
471 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000472 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000473 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700474 }
475
476 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400477 mAppOpsService = IAppOpsService.Stub.asInterface(
478 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800479
480 synchronized (mRestrictionsLock) {
481 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400482 }
Samuel Tand9453b82016-03-14 15:57:02 -0700483
484 UserInfo currentGuestUser = findCurrentGuestUser();
485 if (currentGuestUser != null && !hasUserRestriction(
486 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
487 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
488 // to it, in case this guest was created in a previous version where this
489 // user restriction was not a default guest restriction.
490 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
491 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700492
Ricky Waib1dd80b2016-06-07 18:00:55 +0100493 mContext.registerReceiver(mDisableQuietModeCallback,
494 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
495 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700496 }
497
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700498 void cleanupPartialUsers() {
499 // Prune out any partially created, partially removed and ephemeral users.
500 ArrayList<UserInfo> partials = new ArrayList<>();
501 synchronized (mUsersLock) {
502 final int userSize = mUsers.size();
503 for (int i = 0; i < userSize; i++) {
504 UserInfo ui = mUsers.valueAt(i).info;
505 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
506 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700507 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700508 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700509 }
510 }
511 }
512 final int partialsSize = partials.size();
513 for (int i = 0; i < partialsSize; i++) {
514 UserInfo ui = partials.get(i);
515 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
516 + " (name=" + ui.name + ")");
517 removeUserState(ui.id);
518 }
519 }
520
Amith Yamasani258848d2012-08-10 17:06:33 -0700521 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800522 public String getUserAccount(int userId) {
523 checkManageUserAndAcrossUsersFullPermission("get user account");
524 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800525 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800526 }
527 }
528
529 @Override
530 public void setUserAccount(int userId, String accountName) {
531 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800532 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800533 synchronized (mPackagesLock) {
534 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800535 final UserData userData = mUsers.get(userId);
536 if (userData == null) {
537 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
538 return;
539 }
540 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800541 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800542 userData.account = accountName;
543 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800544 }
545 }
546
547 if (userToUpdate != null) {
548 writeUserLP(userToUpdate);
549 }
550 }
551 }
552
553 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700554 public UserInfo getPrimaryUser() {
555 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700557 final int userSize = mUsers.size();
558 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800559 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800560 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700561 return ui;
562 }
563 }
564 }
565 return null;
566 }
567
568 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700569 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700570 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700571 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700572 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700573 final int userSize = mUsers.size();
574 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800575 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700576 if (ui.partial) {
577 continue;
578 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800579 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700580 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700581 }
Amith Yamasani13593602012-03-22 16:16:17 -0700582 }
583 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700584 }
Amith Yamasani13593602012-03-22 16:16:17 -0700585 }
586
Amith Yamasani258848d2012-08-10 17:06:33 -0700587 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100588 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700589 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800590 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700591 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700592 } else {
593 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800594 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700595 final long ident = Binder.clearCallingIdentity();
596 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700597 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700598 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100599 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700600 } finally {
601 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000602 }
603 }
604
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700605 @Override
606 public int[] getProfileIds(int userId, boolean enabledOnly) {
607 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700608 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700609 }
610 final long ident = Binder.clearCallingIdentity();
611 try {
612 synchronized (mUsersLock) {
613 return getProfileIdsLU(userId, enabledOnly).toArray();
614 }
615 } finally {
616 Binder.restoreCallingIdentity(ident);
617 }
618 }
619
Amith Yamasanibe465322014-04-24 13:45:17 -0700620 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700621 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700622 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
623 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
624 for (int i = 0; i < profileIds.size(); i++) {
625 int profileId = profileIds.get(i);
626 UserInfo userInfo = mUsers.get(profileId).info;
627 // If full info is not required - clear PII data to prevent 3P apps from reading it
628 if (!fullInfo) {
629 userInfo = new UserInfo(userInfo);
630 userInfo.name = null;
631 userInfo.iconPath = null;
632 } else {
633 userInfo = userWithName(userInfo);
634 }
635 users.add(userInfo);
636 }
637 return users;
638 }
639
640 /**
641 * Assume permissions already checked and caller's identity cleared
642 */
643 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700644 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700645 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700646 if (user == null) {
647 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700648 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700649 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700650 final int userSize = mUsers.size();
651 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800652 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700653 if (!isProfileOf(user, profile)) {
654 continue;
655 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100656 if (enabledOnly && !profile.isEnabled()) {
657 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700658 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700659 if (mRemovingUserIds.get(profile.id)) {
660 continue;
661 }
Tony Mak80189cd2016-04-05 17:21:42 +0100662 if (profile.partial) {
663 continue;
664 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700665 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700666 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700667 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700668 }
669
Jessica Hummelbe81c802014-04-22 15:49:22 +0100670 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700671 public int getCredentialOwnerProfile(int userHandle) {
672 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000673 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700674 synchronized (mUsersLock) {
675 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700676 if (profileParent != null) {
677 return profileParent.id;
678 }
679 }
680 }
681
682 return userHandle;
683 }
684
685 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700686 public boolean isSameProfileGroup(int userId, int otherUserId) {
687 if (userId == otherUserId) return true;
688 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700689 return isSameProfileGroupNoChecks(userId, otherUserId);
690 }
691
692 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700693 synchronized (mUsersLock) {
694 UserInfo userInfo = getUserInfoLU(userId);
695 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
696 return false;
697 }
698 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
699 if (otherUserInfo == null
700 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
701 return false;
702 }
703 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700704 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700705 }
706
707 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100708 public UserInfo getProfileParent(int userHandle) {
709 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700710 synchronized (mUsersLock) {
711 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700712 }
713 }
714
Fyodor Kupolov82402752015-10-28 14:54:51 -0700715 private UserInfo getProfileParentLU(int userHandle) {
716 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700717 if (profile == null) {
718 return null;
719 }
720 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800721 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700722 return null;
723 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700724 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100725 }
726 }
727
Fyodor Kupolov82402752015-10-28 14:54:51 -0700728 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100729 return user.id == profile.id ||
730 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
731 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000732 }
733
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000734 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000735 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100736 Intent intent = new Intent();
737 if (inQuietMode) {
738 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
739 } else {
740 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
741 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000742 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
743 intent.putExtra(Intent.EXTRA_USER, profileHandle);
744 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000745 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000746 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000747 }
748
749 @Override
750 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
751 checkManageUsersPermission("silence profile");
752 boolean changed = false;
753 UserInfo profile, parent;
754 synchronized (mPackagesLock) {
755 synchronized (mUsersLock) {
756 profile = getUserInfoLU(userHandle);
757 parent = getProfileParentLU(userHandle);
758
759 }
760 if (profile == null || !profile.isManagedProfile()) {
761 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
762 }
763 if (profile.isQuietModeEnabled() != enableQuietMode) {
764 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800765 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000766 changed = true;
767 }
768 }
769 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000770 long identity = Binder.clearCallingIdentity();
771 try {
772 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800773 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100774 LocalServices.getService(ActivityManagerInternal.class)
775 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000776 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800777 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000778 }
779 } catch (RemoteException e) {
780 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
781 } finally {
782 Binder.restoreCallingIdentity(identity);
783 }
784
785 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
786 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000787 }
788 }
789
790 @Override
791 public boolean isQuietModeEnabled(int userHandle) {
792 synchronized (mPackagesLock) {
793 UserInfo info;
794 synchronized (mUsersLock) {
795 info = getUserInfoLU(userHandle);
796 }
797 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000798 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000799 }
800 return info.isQuietModeEnabled();
801 }
802 }
803
Kenny Guya52dc3e2014-02-11 15:33:14 +0000804 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100805 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100806 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600807 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100808 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100809 // if the user is already unlocked, no need to show a profile challenge
810 setQuietModeEnabled(userHandle, false);
811 return true;
812 }
813
814 long identity = Binder.clearCallingIdentity();
815 try {
816 // otherwise, we show a profile challenge to trigger decryption of the user
817 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
818 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100819 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
820 // lock, confirm screenlock page will know and show personal challenge, and unlock
821 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100822 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
823 userHandle);
824 if (unlockIntent == null) {
825 return false;
826 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100827 final Intent callBackIntent = new Intent(
828 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100829 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100830 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100831 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100832 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
833 callBackIntent.setPackage(mContext.getPackageName());
834 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
835 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
836 mContext,
837 0,
838 callBackIntent,
839 PendingIntent.FLAG_CANCEL_CURRENT |
840 PendingIntent.FLAG_ONE_SHOT |
841 PendingIntent.FLAG_IMMUTABLE);
842 // After unlocking the challenge, it will disable quiet mode and run the original
843 // intentSender
844 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100845 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
846 mContext.startActivity(unlockIntent);
847 } finally {
848 Binder.restoreCallingIdentity(identity);
849 }
850 return false;
851 }
852
853 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100854 public void setUserEnabled(int userId) {
855 checkManageUsersPermission("enable user");
856 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700857 UserInfo info;
858 synchronized (mUsersLock) {
859 info = getUserInfoLU(userId);
860 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100861 if (info != null && !info.isEnabled()) {
862 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800863 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100864 }
865 }
866 }
867
Andrew Scull85a63bc2016-10-24 13:47:47 +0100868 /**
869 * Evicts a user's CE key by stopping and restarting the user.
870 *
871 * The key is evicted automatically by the user controller when the user has stopped.
872 */
873 @Override
874 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
875 checkManageUsersPermission("evict CE key");
876 final IActivityManager am = ActivityManagerNative.getDefault();
877 final long identity = Binder.clearCallingIdentity();
878 try {
879 am.restartUserInBackground(userId);
880 } catch (RemoteException re) {
881 throw re.rethrowAsRuntimeException();
882 } finally {
883 Binder.restoreCallingIdentity(identity);
884 }
885 }
886
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100887 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700888 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700889 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000890 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700891 return userWithName(getUserInfoLU(userId));
892 }
893 }
894
895 /**
896 * Returns a UserInfo object with the name filled in, for Owner, or the original
897 * if the name is already set.
898 */
899 private UserInfo userWithName(UserInfo orig) {
900 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
901 UserInfo withName = new UserInfo(orig);
902 withName.name = getOwnerName();
903 return withName;
904 } else {
905 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000906 }
907 }
908
909 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000910 public int getManagedProfileBadge(@UserIdInt int userId) {
911 int callingUserId = UserHandle.getCallingUserId();
912 if (callingUserId != userId && !hasManageUsersPermission()) {
913 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
914 throw new SecurityException(
915 "You need MANAGE_USERS permission to: check if specified user a " +
916 "managed profile outside your profile group");
917 }
918 }
919 synchronized (mUsersLock) {
920 UserInfo userInfo = getUserInfoLU(userId);
921 return userInfo != null ? userInfo.profileBadge : 0;
922 }
923 }
924
925 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000926 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000927 int callingUserId = UserHandle.getCallingUserId();
928 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700929 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700930 throw new SecurityException(
931 "You need MANAGE_USERS permission to: check if specified user a " +
932 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000933 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000934 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700935 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700936 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000937 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700938 }
939 }
940
Amith Yamasani71e6c692013-03-24 17:39:28 -0700941 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700942 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800943 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700944 return mLocalService.isUserUnlockingOrUnlocked(userId);
945 }
946
947 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800948 public boolean isUserUnlocked(int userId) {
949 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
950 return mLocalService.isUserUnlockingOrUnlocked(userId);
951 }
952
953 @Override
954 public boolean isUserRunning(int userId) {
955 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
956 return mLocalService.isUserRunning(userId);
957 }
958
959 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
960 int callingUserId = UserHandle.getCallingUserId();
961 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
962 hasManageUsersPermission()) {
963 return;
964 }
965 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
966 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
967 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
968 + "to: check " + name);
969 }
970 }
971
972 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700973 public boolean isDemoUser(int userId) {
974 int callingUserId = UserHandle.getCallingUserId();
975 if (callingUserId != userId && !hasManageUsersPermission()) {
976 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
977 + " is a demo user");
978 }
979 synchronized (mUsersLock) {
980 UserInfo userInfo = getUserInfoLU(userId);
981 return userInfo != null && userInfo.isDemo();
982 }
983 }
984
985 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700986 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700987 synchronized (mUsersLock) {
988 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700989 }
990 }
991
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700992 @Override
993 public boolean canHaveRestrictedProfile(int userId) {
994 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700995 synchronized (mUsersLock) {
996 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700997 if (userInfo == null || !userInfo.canHaveProfile()) {
998 return false;
999 }
1000 if (!userInfo.isAdmin()) {
1001 return false;
1002 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001003 // restricted profile can be created if there is no DO set and the admin user has no PO;
1004 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001005 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001006 }
1007
Amith Yamasani195263742012-08-21 15:40:12 -07001008 /*
1009 * Should be locked on mUsers before calling this.
1010 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001011 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001012 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001013 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001014 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001015 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1016 return null;
1017 }
Amith Yamasani12747872015-12-07 14:19:49 -08001018 return userData != null ? userData.info : null;
1019 }
1020
1021 private UserData getUserDataLU(int userId) {
1022 final UserData userData = mUsers.get(userId);
1023 // If it is partial and not in the process of being removed, return as unknown user.
1024 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1025 return null;
1026 }
1027 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001028 }
1029
Fyodor Kupolov82402752015-10-28 14:54:51 -07001030 /**
1031 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1032 * <p>No permissions checking or any addition checks are made</p>
1033 */
1034 private UserInfo getUserInfoNoChecks(int userId) {
1035 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001036 final UserData userData = mUsers.get(userId);
1037 return userData != null ? userData.info : null;
1038 }
1039 }
1040
1041 /**
1042 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1043 * <p>No permissions checking or any addition checks are made</p>
1044 */
1045 private UserData getUserDataNoChecks(int userId) {
1046 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001047 return mUsers.get(userId);
1048 }
1049 }
1050
Amith Yamasani236b2b52015-08-18 14:32:14 -07001051 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001052 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001053 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001054 }
1055
Amith Yamasani258848d2012-08-10 17:06:33 -07001056 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001057 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001058 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001059 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001060 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001061 UserData userData = getUserDataNoChecks(userId);
1062 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001063 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1064 return;
1065 }
Amith Yamasani12747872015-12-07 14:19:49 -08001066 if (name != null && !name.equals(userData.info.name)) {
1067 userData.info.name = name;
1068 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001069 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001070 }
1071 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001072 if (changed) {
1073 sendUserInfoChangedBroadcast(userId);
1074 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001075 }
1076
Amith Yamasani258848d2012-08-10 17:06:33 -07001077 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001078 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001079 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001080 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1081 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1082 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001083 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001084 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001085 }
1086
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001087
1088
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001089 private void sendUserInfoChangedBroadcast(int userId) {
1090 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1091 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1092 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001093 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001094 }
1095
Amith Yamasani258848d2012-08-10 17:06:33 -07001096 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001097 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001098 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001099 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001100 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1101 if (targetUserInfo == null || targetUserInfo.partial) {
1102 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001103 return null;
1104 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001105
1106 final int callingUserId = UserHandle.getCallingUserId();
1107 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1108 final int targetGroupId = targetUserInfo.profileGroupId;
1109 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1110 && callingGroupId == targetGroupId);
1111 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001112 checkManageUsersPermission("get the icon of a user who is not related");
1113 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001114
1115 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001116 return null;
1117 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001118 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001119 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001120
1121 try {
1122 return ParcelFileDescriptor.open(
1123 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1124 } catch (FileNotFoundException e) {
1125 Log.e(LOG_TAG, "Couldn't find icon file", e);
1126 }
1127 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001128 }
1129
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001130 public void makeInitialized(int userId) {
1131 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001132 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001133 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001134 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001135 userData = mUsers.get(userId);
1136 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001137 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001138 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001139 }
Amith Yamasani12747872015-12-07 14:19:49 -08001140 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1141 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001142 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001143 }
1144 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001145 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001146 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001147 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001148 }
1149
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001150 /**
1151 * If default guest restrictions haven't been initialized yet, add the basic
1152 * restrictions.
1153 */
1154 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001155 synchronized (mGuestRestrictions) {
1156 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001157 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001158 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001159 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1160 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1161 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001162 }
1163 }
1164
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001165 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301166 public Bundle getDefaultGuestRestrictions() {
1167 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001168 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301169 return new Bundle(mGuestRestrictions);
1170 }
1171 }
1172
1173 @Override
1174 public void setDefaultGuestRestrictions(Bundle restrictions) {
1175 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001176 synchronized (mGuestRestrictions) {
1177 mGuestRestrictions.clear();
1178 mGuestRestrictions.putAll(restrictions);
1179 }
1180 synchronized (mPackagesLock) {
1181 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301182 }
1183 }
1184
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001185 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001186 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001187 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001188 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1189 boolean isDeviceOwner, int cameraRestrictionScope) {
1190 final Bundle global = new Bundle();
1191 final Bundle local = new Bundle();
1192
1193 // Sort restrictions into local and global ensuring they don't overlap.
1194 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1195 cameraRestrictionScope, global, local);
1196
1197 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001198 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001199 // Update global and local restrictions if they were changed.
1200 globalChanged = updateRestrictionsIfNeededLR(
1201 userId, global, mDevicePolicyGlobalUserRestrictions);
1202 localChanged = updateRestrictionsIfNeededLR(
1203 userId, local, mDevicePolicyLocalUserRestrictions);
1204
1205 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001206 // Remember the global restriction owner userId to be able to make a distinction
1207 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001208 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001209 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001210 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001211 // When profile owner sets restrictions it passes null global bundle and we
1212 // reset global restriction owner userId.
1213 // This means this user used to have DO, but now the DO is gone and the user
1214 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001215 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001216 }
1217 }
1218 }
1219 if (DBG) {
1220 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1221 + " global=" + global + (globalChanged ? " (changed)" : "")
1222 + " local=" + local + (localChanged ? " (changed)" : "")
1223 );
1224 }
1225 // Don't call them within the mRestrictionsLock.
1226 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001227 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001228 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001229 }
1230 }
1231
1232 synchronized (mRestrictionsLock) {
1233 if (globalChanged) {
1234 applyUserRestrictionsForAllUsersLR();
1235 } else if (localChanged) {
1236 applyUserRestrictionsLR(userId);
1237 }
1238 }
1239 }
1240
Pavel Grafov6a40f092016-10-25 15:46:51 +01001241 /**
1242 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1243 * empty, record is removed from the array.
1244 * @return whether restrictions bundle is different from the old one.
1245 */
1246 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1247 SparseArray<Bundle> restrictionsArray) {
1248 final boolean changed =
1249 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1250 if (changed) {
1251 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1252 restrictionsArray.put(userId, restrictions);
1253 } else {
1254 restrictionsArray.delete(userId);
1255 }
1256 }
1257 return changed;
1258 }
1259
Makoto Onuki068c54a2015-10-13 14:34:03 -07001260 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001261 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001262 final Bundle baseRestrictions =
1263 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001264 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001265 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001266
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001267 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1268 // Common case first.
1269 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001270 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001271 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1272 UserRestrictionsUtils.merge(effective, global);
1273 UserRestrictionsUtils.merge(effective, local);
1274
Makoto Onuki068c54a2015-10-13 14:34:03 -07001275 return effective;
1276 }
1277
1278 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001279 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001280 if (DBG) {
1281 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1282 }
1283 mCachedEffectiveUserRestrictions.remove(userId);
1284 }
1285
1286 private Bundle getEffectiveUserRestrictions(int userId) {
1287 synchronized (mRestrictionsLock) {
1288 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1289 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001290 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001291 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1292 }
1293 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001294 }
1295 }
1296
Makoto Onuki068c54a2015-10-13 14:34:03 -07001297 /** @return a specific user restriction that's in effect currently. */
1298 @Override
1299 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001300 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1301 return false;
1302 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001303 Bundle restrictions = getEffectiveUserRestrictions(userId);
1304 return restrictions != null && restrictions.getBoolean(restrictionKey);
1305 }
1306
1307 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001308 * @hide
1309 *
1310 * Returns who set a user restriction on a user.
1311 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1312 * @param restrictionKey the string key representing the restriction
1313 * @param userId the id of the user for whom to retrieve the restrictions.
1314 * @return The source of user restriction. Any combination of
1315 * {@link UserManager#RESTRICTION_NOT_SET},
1316 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1317 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1318 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1319 */
1320 @Override
1321 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001322 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1323 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001324 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001325 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1326 result |= enforcingUsers.get(i).getUserRestrictionSource();
1327 }
1328 return result;
1329 }
1330
1331 @Override
1332 public List<EnforcingUser> getUserRestrictionSources(
1333 String restrictionKey, @UserIdInt int userId) {
1334 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001335
1336 // Shortcut for the most common case
1337 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001338 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001339 }
1340
Pavel Grafov6a40f092016-10-25 15:46:51 +01001341 final List<EnforcingUser> result = new ArrayList<>();
1342
1343 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001344 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001345 result.add(new EnforcingUser(
1346 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001347 }
1348
Pavel Grafov6a40f092016-10-25 15:46:51 +01001349 synchronized (mRestrictionsLock) {
1350 // Check if it is set by profile owner.
1351 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1352 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1353 result.add(getEnforcingUserLocked(userId));
1354 }
1355
1356 // Iterate over all users who enforce global restrictions.
1357 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1358 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1359 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1360 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1361 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001362 }
1363 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001364 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001365 return result;
1366 }
1367
Pavel Grafov6a40f092016-10-25 15:46:51 +01001368 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1369 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1370 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1371 return new EnforcingUser(userId, source);
1372 }
1373
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001374 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001375 * @return UserRestrictions that are in effect currently. This always returns a new
1376 * {@link Bundle}.
1377 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001378 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001379 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001380 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001381 }
1382
1383 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001384 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1385 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001386 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1387 return false;
1388 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001389 synchronized (mRestrictionsLock) {
1390 Bundle bundle = mBaseUserRestrictions.get(userId);
1391 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1392 }
1393 }
1394
1395 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001396 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001397 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001398 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1399 return;
1400 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001401 synchronized (mRestrictionsLock) {
1402 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1403 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001404 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1405 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001406 newRestrictions.putBoolean(key, value);
1407
Fyodor Kupolov82402752015-10-28 14:54:51 -07001408 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001409 }
1410 }
1411
Makoto Onuki068c54a2015-10-13 14:34:03 -07001412 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001413 * Optionally updating user restrictions, calculate the effective user restrictions and also
1414 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001415 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001416 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001417 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001418 * @param userId target user ID.
1419 */
1420 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001421 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001422 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001423 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1424 mAppliedUserRestrictions.get(userId));
1425
1426 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001427 if (newBaseRestrictions != null) {
1428 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001429 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1430
Pavel Grafov6a40f092016-10-25 15:46:51 +01001431 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001432 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001433 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001434
Pavel Grafov6a40f092016-10-25 15:46:51 +01001435 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001436 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001437 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001438 }
1439
Fyodor Kupolov82402752015-10-28 14:54:51 -07001440 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001441
Makoto Onuki759a7632015-10-28 16:43:10 -07001442 mCachedEffectiveUserRestrictions.put(userId, effective);
1443
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001444 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001445 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001446 debug("Applying user restrictions: userId=" + userId
1447 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001448 }
1449
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001450 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001451 mHandler.post(new Runnable() {
1452 @Override
1453 public void run() {
1454 try {
1455 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1456 } catch (RemoteException e) {
1457 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1458 }
1459 }
1460 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001461 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001462
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001463 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001464
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001465 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001466 }
1467
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001468 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001469 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001470 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1471 // actually, but we still need some kind of synchronization otherwise we might end up
1472 // calling listeners out-of-order, thus "LR".
1473
1474 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1475 return;
1476 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001477
1478 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1479 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1480
1481 mHandler.post(new Runnable() {
1482 @Override
1483 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001484 UserRestrictionsUtils.applyUserRestrictions(
1485 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001486
Makoto Onukid45a4a22015-11-02 17:17:38 -08001487 final UserRestrictionsListener[] listeners;
1488 synchronized (mUserRestrictionsListeners) {
1489 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1490 mUserRestrictionsListeners.toArray(listeners);
1491 }
1492 for (int i = 0; i < listeners.length; i++) {
1493 listeners[i].onUserRestrictionsChanged(userId,
1494 newRestrictionsFinal, prevRestrictionsFinal);
1495 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001496
1497 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1498 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1499 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001500 }
1501 });
1502 }
1503
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 // Package private for the inner class.
1505 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001506 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001507 }
1508
1509 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001510 // Package private for the inner class.
1511 void applyUserRestrictionsForAllUsersLR() {
1512 if (DBG) {
1513 debug("applyUserRestrictionsForAllUsersLR");
1514 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001515 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001516 mCachedEffectiveUserRestrictions.clear();
1517
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001518 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001519 // it on a handler.
1520 final Runnable r = new Runnable() {
1521 @Override
1522 public void run() {
1523 // Then get the list of running users.
1524 final int[] runningUsers;
1525 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001526 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001527 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001528 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001529 return;
1530 }
1531 // Then re-calculate the effective restrictions and apply, only for running users.
1532 // It's okay if a new user has started after the getRunningUserIds() call,
1533 // because we'll do the same thing (re-calculate the restrictions and apply)
1534 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001535 synchronized (mRestrictionsLock) {
1536 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001537 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001538 }
1539 }
1540 }
1541 };
1542 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001543 }
1544
Amith Yamasani258848d2012-08-10 17:06:33 -07001545 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001546 * Check if we've hit the limit of how many users can be created.
1547 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001548 private boolean isUserLimitReached() {
1549 int count;
1550 synchronized (mUsersLock) {
1551 count = getAliveUsersExcludingGuestsCountLU();
1552 }
1553 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001554 }
1555
1556 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001557 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001558 checkManageUsersPermission("check if more managed profiles can be added.");
1559 if (ActivityManager.isLowRamDeviceStatic()) {
1560 return false;
1561 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001562 if (!mContext.getPackageManager().hasSystemFeature(
1563 PackageManager.FEATURE_MANAGED_USERS)) {
1564 return false;
1565 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001566 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001567 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001568 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001569 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001570 return false;
1571 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001572 synchronized(mUsersLock) {
1573 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001574 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001575 return false;
1576 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001577 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1578 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001579 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001580 return usersCountAfterRemoving == 1
1581 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001582 }
1583 }
1584
Fyodor Kupolov82402752015-10-28 14:54:51 -07001585 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001586 int aliveUserCount = 0;
1587 final int totalUserCount = mUsers.size();
1588 // Skip over users being removed
1589 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001590 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001591 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001592 aliveUserCount++;
1593 }
1594 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001595 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001596 }
1597
1598 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001599 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001600 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1601 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1602 * permissions can make certain calls to the UserManager.
1603 *
1604 * @param message used as message if SecurityException is thrown
1605 * @throws SecurityException if the caller does not have enough privilege.
1606 */
1607 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1608 final int uid = Binder.getCallingUid();
1609 if (uid != Process.SYSTEM_UID && uid != 0
1610 && ActivityManager.checkComponentPermission(
1611 Manifest.permission.MANAGE_USERS,
1612 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1613 && ActivityManager.checkComponentPermission(
1614 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1615 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1616 throw new SecurityException(
1617 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1618 + message);
1619 }
1620 }
1621
1622 /**
1623 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001624 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001625 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001626 *
1627 * @param message used as message if SecurityException is thrown
1628 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001629 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001630 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001631 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001632 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001633 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1634 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001635 }
1636
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001637 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001638 * Enforces that only the system UID or root's UID or apps that have the
1639 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1640 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1641 * can make certain calls to the UserManager.
1642 *
1643 * @param message used as message if SecurityException is thrown
1644 * @throws SecurityException if the caller is not system or root
1645 * @see #hasManageOrCreateUsersPermission()
1646 */
1647 private static final void checkManageOrCreateUsersPermission(String message) {
1648 if (!hasManageOrCreateUsersPermission()) {
1649 throw new SecurityException(
1650 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1651 }
1652 }
1653
1654 /**
1655 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1656 * to create user/profiles other than what is allowed for
1657 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1658 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1659 */
1660 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1661 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1662 if (!hasManageOrCreateUsersPermission()) {
1663 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1664 + "permission to create an user with flags: " + creationFlags);
1665 }
1666 } else if (!hasManageUsersPermission()) {
1667 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1668 + " with flags: " + creationFlags);
1669 }
1670 }
1671
1672 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001673 * @return whether the calling UID is system UID or root's UID or the calling app has the
1674 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1675 */
1676 private static final boolean hasManageUsersPermission() {
1677 final int callingUid = Binder.getCallingUid();
1678 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1679 || callingUid == Process.ROOT_UID
1680 || ActivityManager.checkComponentPermission(
1681 android.Manifest.permission.MANAGE_USERS,
1682 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1683 }
1684
1685 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001686 * @return whether the calling UID is system UID or root's UID or the calling app has the
1687 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1688 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1689 */
1690 private static final boolean hasManageOrCreateUsersPermission() {
1691 final int callingUid = Binder.getCallingUid();
1692 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1693 || callingUid == Process.ROOT_UID
1694 || ActivityManager.checkComponentPermission(
1695 android.Manifest.permission.MANAGE_USERS,
1696 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1697 || ActivityManager.checkComponentPermission(
1698 android.Manifest.permission.CREATE_USERS,
1699 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1700 }
1701
1702 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001703 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1704 * UserManager.
1705 *
1706 * @param message used as message if SecurityException is thrown
1707 * @throws SecurityException if the caller is not system or root
1708 */
1709 private static void checkSystemOrRoot(String message) {
1710 final int uid = Binder.getCallingUid();
1711 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1712 throw new SecurityException("Only system may: " + message);
1713 }
1714 }
1715
Fyodor Kupolov82402752015-10-28 14:54:51 -07001716 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001717 try {
1718 File dir = new File(mUsersDir, Integer.toString(info.id));
1719 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001720 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001721 if (!dir.exists()) {
1722 dir.mkdir();
1723 FileUtils.setPermissions(
1724 dir.getPath(),
1725 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1726 -1, -1);
1727 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001728 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001729 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001730 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001731 info.iconPath = file.getAbsolutePath();
1732 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001733 try {
1734 os.close();
1735 } catch (IOException ioe) {
1736 // What the ... !
1737 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001738 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001739 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001740 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001741 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001742 }
1743
Amith Yamasani0b285492011-04-14 17:35:23 -07001744 /**
1745 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1746 * cache it elsewhere.
1747 * @return the array of user ids.
1748 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001749 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001750 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001751 return mUserIds;
1752 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001753 }
1754
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001755 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001756 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001757 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001758 return;
1759 }
1760 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001761 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001762 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001763 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001764 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001765 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001766 int type;
1767 while ((type = parser.next()) != XmlPullParser.START_TAG
1768 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001769 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001770 }
1771
1772 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001773 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001774 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001775 return;
1776 }
1777
Amith Yamasani2a003292012-08-14 18:25:45 -07001778 mNextSerialNumber = -1;
1779 if (parser.getName().equals(TAG_USERS)) {
1780 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1781 if (lastSerialNumber != null) {
1782 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1783 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001784 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1785 if (versionNumber != null) {
1786 mUserVersion = Integer.parseInt(versionNumber);
1787 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001788 }
1789
Pavel Grafov6a40f092016-10-25 15:46:51 +01001790 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1791 // currently), take care of it in case of upgrade.
1792 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001793
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001794 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301795 if (type == XmlPullParser.START_TAG) {
1796 final String name = parser.getName();
1797 if (name.equals(TAG_USER)) {
1798 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001799
Amith Yamasani12747872015-12-07 14:19:49 -08001800 UserData userData = readUserLP(Integer.parseInt(id));
1801
1802 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001803 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001804 mUsers.put(userData.info.id, userData);
1805 if (mNextSerialNumber < 0
1806 || mNextSerialNumber <= userData.info.id) {
1807 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001808 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301809 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001810 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301811 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001812 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1813 && type != XmlPullParser.END_TAG) {
1814 if (type == XmlPullParser.START_TAG) {
1815 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001816 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07001817 UserRestrictionsUtils
1818 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001819 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001820 }
1821 break;
1822 }
1823 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001824 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1825 // Legacy name, should only be encountered when upgrading from pre-O.
1826 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001827 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1828 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001829 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001830 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001831 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1832 // Should only happen when upgrading from pre-O (version < 7).
1833 oldDevicePolicyGlobalUserRestrictions =
1834 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001835 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001836 }
1837 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001838
Fyodor Kupolov82402752015-10-28 14:54:51 -07001839 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001840 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001841 } catch (IOException | XmlPullParserException e) {
1842 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001843 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001844 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001845 }
1846 }
1847
Amith Yamasani6f34b412012-10-22 18:19:27 -07001848 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001849 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001850 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001851 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001852 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001853 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001854 int userVersion = mUserVersion;
1855 if (userVersion < 1) {
1856 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001857 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1858 if ("Primary".equals(userData.info.name)) {
1859 userData.info.name =
1860 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1861 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001862 }
1863 userVersion = 1;
1864 }
1865
Amith Yamasanibc9625052012-11-15 14:39:18 -08001866 if (userVersion < 2) {
1867 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001868 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1869 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1870 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1871 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001872 }
1873 userVersion = 2;
1874 }
1875
Amith Yamasani350962c2013-08-06 11:18:53 -07001876
Amith Yamasani5e486f52013-08-07 11:06:44 -07001877 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001878 userVersion = 4;
1879 }
1880
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001881 if (userVersion < 5) {
1882 initDefaultGuestRestrictions();
1883 userVersion = 5;
1884 }
1885
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001886 if (userVersion < 6) {
1887 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001888 synchronized (mUsersLock) {
1889 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001890 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001891 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001892 if (!splitSystemUser && userData.info.isRestricted()
1893 && (userData.info.restrictedProfileParentId
1894 == UserInfo.NO_PROFILE_GROUP_ID)) {
1895 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1896 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001897 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001898 }
1899 }
1900 userVersion = 6;
1901 }
1902
Pavel Grafov6a40f092016-10-25 15:46:51 +01001903 if (userVersion < 7) {
1904 // Previously only one user could enforce global restrictions, now it is per-user.
1905 synchronized (mRestrictionsLock) {
1906 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1907 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1908 mDevicePolicyGlobalUserRestrictions.put(
1909 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1910 }
1911 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1912 // it from local to global bundle for all users who set it.
1913 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1914 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1915 );
1916 }
1917 userVersion = 7;
1918 }
1919
Amith Yamasani6f34b412012-10-22 18:19:27 -07001920 if (userVersion < USER_VERSION) {
1921 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1922 + USER_VERSION);
1923 } else {
1924 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001925
1926 if (originalVersion < mUserVersion) {
1927 writeUserListLP();
1928 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001929 }
1930 }
1931
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001932 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001933 int flags = UserInfo.FLAG_INITIALIZED;
1934 // In split system user mode, the admin and primary flags are assigned to the first human
1935 // user.
1936 if (!UserManager.isSplitSystemUser()) {
1937 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1938 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001939 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001940 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001941 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001942 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001943 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001944
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001945 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001946 try {
1947 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1948 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1949 for (String userRestriction : defaultFirstUserRestrictions) {
1950 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1951 restrictions.putBoolean(userRestriction, true);
1952 }
1953 }
1954 } catch (Resources.NotFoundException e) {
1955 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1956 }
1957
Pavel Grafov6a40f092016-10-25 15:46:51 +01001958 if (!restrictions.isEmpty()) {
1959 synchronized (mRestrictionsLock) {
1960 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1961 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001962 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001963
Fyodor Kupolov82402752015-10-28 14:54:51 -07001964 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001965 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001966
Amith Yamasani12747872015-12-07 14:19:49 -08001967 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001968 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001969 }
1970
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001971 private String getOwnerName() {
1972 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1973 }
1974
Amith Yamasani12747872015-12-07 14:19:49 -08001975 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001976 if (DBG) {
1977 debug("scheduleWriteUser");
1978 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001979 // No need to wrap it within a lock -- worst case, we'll just post the same message
1980 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001981 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1982 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001983 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1984 }
1985 }
1986
Amith Yamasani12747872015-12-07 14:19:49 -08001987 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001988 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001989 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001990 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001991 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001992 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001993 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001994 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001995 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001996 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001997 userFile.finishWrite(fos);
1998 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001999 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002000 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002001 }
2002 }
2003
2004 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002005 * Writes the user file in this format:
2006 *
2007 * <user flags="20039023" id="0">
2008 * <name>Primary</name>
2009 * </user>
2010 */
2011 @VisibleForTesting
2012 void writeUserLP(UserData userData, OutputStream os)
2013 throws IOException, XmlPullParserException {
2014 // XmlSerializer serializer = XmlUtils.serializerInstance();
2015 final XmlSerializer serializer = new FastXmlSerializer();
2016 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2017 serializer.startDocument(null, true);
2018 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2019
2020 final UserInfo userInfo = userData.info;
2021 serializer.startTag(null, TAG_USER);
2022 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2023 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2024 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2025 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2026 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2027 Long.toString(userInfo.lastLoggedInTime));
2028 if (userInfo.lastLoggedInFingerprint != null) {
2029 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2030 userInfo.lastLoggedInFingerprint);
2031 }
2032 if (userInfo.iconPath != null) {
2033 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2034 }
2035 if (userInfo.partial) {
2036 serializer.attribute(null, ATTR_PARTIAL, "true");
2037 }
2038 if (userInfo.guestToRemove) {
2039 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2040 }
2041 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2042 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2043 Integer.toString(userInfo.profileGroupId));
2044 }
2045 serializer.attribute(null, ATTR_PROFILE_BADGE,
2046 Integer.toString(userInfo.profileBadge));
2047 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2048 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2049 Integer.toString(userInfo.restrictedProfileParentId));
2050 }
2051 // Write seed data
2052 if (userData.persistSeedData) {
2053 if (userData.seedAccountName != null) {
2054 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2055 }
2056 if (userData.seedAccountType != null) {
2057 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2058 }
2059 }
2060 if (userInfo.name != null) {
2061 serializer.startTag(null, TAG_NAME);
2062 serializer.text(userInfo.name);
2063 serializer.endTag(null, TAG_NAME);
2064 }
2065 synchronized (mRestrictionsLock) {
2066 UserRestrictionsUtils.writeRestrictions(serializer,
2067 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2068 UserRestrictionsUtils.writeRestrictions(serializer,
2069 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2070 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002071 UserRestrictionsUtils.writeRestrictions(serializer,
2072 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2073 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002074 }
2075
2076 if (userData.account != null) {
2077 serializer.startTag(null, TAG_ACCOUNT);
2078 serializer.text(userData.account);
2079 serializer.endTag(null, TAG_ACCOUNT);
2080 }
2081
2082 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2083 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2084 userData.seedAccountOptions.saveToXml(serializer);
2085 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2086 }
2087
2088 serializer.endTag(null, TAG_USER);
2089
2090 serializer.endDocument();
2091 }
2092
2093 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002094 * Writes the user list file in this format:
2095 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002096 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002097 * <user id="0"></user>
2098 * <user id="2"></user>
2099 * </users>
2100 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002101 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002102 if (DBG) {
2103 debug("writeUserList");
2104 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002105 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002106 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002107 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002108 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002109 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2110
2111 // XmlSerializer serializer = XmlUtils.serializerInstance();
2112 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002113 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002114 serializer.startDocument(null, true);
2115 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2116
2117 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002118 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002119 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002120
Adam Lesinskieddeb492014-09-08 17:50:03 -07002121 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002122 synchronized (mGuestRestrictions) {
2123 UserRestrictionsUtils
2124 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2125 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302126 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002127 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2128 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2129 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002130 int[] userIdsToWrite;
2131 synchronized (mUsersLock) {
2132 userIdsToWrite = new int[mUsers.size()];
2133 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002134 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002135 userIdsToWrite[i] = user.id;
2136 }
2137 }
2138 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002139 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002140 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002141 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002142 }
2143
2144 serializer.endTag(null, TAG_USERS);
2145
2146 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002147 userListFile.finishWrite(fos);
2148 } catch (Exception e) {
2149 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002150 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002151 }
2152 }
2153
Amith Yamasani12747872015-12-07 14:19:49 -08002154 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002155 FileInputStream fis = null;
2156 try {
2157 AtomicFile userFile =
2158 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2159 fis = userFile.openRead();
2160 return readUserLP(id, fis);
2161 } catch (IOException ioe) {
2162 Slog.e(LOG_TAG, "Error reading user list");
2163 } catch (XmlPullParserException pe) {
2164 Slog.e(LOG_TAG, "Error reading user list");
2165 } finally {
2166 IoUtils.closeQuietly(fis);
2167 }
2168 return null;
2169 }
2170
2171 @VisibleForTesting
2172 UserData readUserLP(int id, InputStream is) throws IOException,
2173 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002174 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002175 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002176 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002177 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002178 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002179 long creationTime = 0L;
2180 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002181 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002182 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002183 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002184 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002185 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002186 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002187 boolean persistSeedData = false;
2188 String seedAccountName = null;
2189 String seedAccountType = null;
2190 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002191 Bundle baseRestrictions = null;
2192 Bundle localRestrictions = null;
2193 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002194
Kenny Guy02c89902016-11-15 19:36:38 +00002195 XmlPullParser parser = Xml.newPullParser();
2196 parser.setInput(is, StandardCharsets.UTF_8.name());
2197 int type;
2198 while ((type = parser.next()) != XmlPullParser.START_TAG
2199 && type != XmlPullParser.END_DOCUMENT) {
2200 // Skip
2201 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002202
Kenny Guy02c89902016-11-15 19:36:38 +00002203 if (type != XmlPullParser.START_TAG) {
2204 Slog.e(LOG_TAG, "Unable to read user " + id);
2205 return null;
2206 }
2207
2208 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2209 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2210 if (storedId != id) {
2211 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002212 return null;
2213 }
Kenny Guy02c89902016-11-15 19:36:38 +00002214 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2215 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2216 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2217 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2218 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2219 lastLoggedInFingerprint = parser.getAttributeValue(null,
2220 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2221 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2222 UserInfo.NO_PROFILE_GROUP_ID);
2223 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2224 restrictedProfileParentId = readIntAttribute(parser,
2225 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2226 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2227 if ("true".equals(valueString)) {
2228 partial = true;
2229 }
2230 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2231 if ("true".equals(valueString)) {
2232 guestToRemove = true;
2233 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002234
Kenny Guy02c89902016-11-15 19:36:38 +00002235 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2236 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2237 if (seedAccountName != null || seedAccountType != null) {
2238 persistSeedData = true;
2239 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002240
Kenny Guy02c89902016-11-15 19:36:38 +00002241 int outerDepth = parser.getDepth();
2242 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2243 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2244 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2245 continue;
2246 }
2247 String tag = parser.getName();
2248 if (TAG_NAME.equals(tag)) {
2249 type = parser.next();
2250 if (type == XmlPullParser.TEXT) {
2251 name = parser.getText();
2252 }
2253 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002254 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002255 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002256 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2257 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2258 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002259 } else if (TAG_ACCOUNT.equals(tag)) {
2260 type = parser.next();
2261 if (type == XmlPullParser.TEXT) {
2262 account = parser.getText();
2263 }
2264 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2265 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002266 persistSeedData = true;
2267 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002268 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002269 }
Kenny Guy02c89902016-11-15 19:36:38 +00002270
2271 // Create the UserInfo object that gets passed around
2272 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2273 userInfo.serialNumber = serialNumber;
2274 userInfo.creationTime = creationTime;
2275 userInfo.lastLoggedInTime = lastLoggedInTime;
2276 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2277 userInfo.partial = partial;
2278 userInfo.guestToRemove = guestToRemove;
2279 userInfo.profileGroupId = profileGroupId;
2280 userInfo.profileBadge = profileBadge;
2281 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2282
2283 // Create the UserData object that's internal to this class
2284 UserData userData = new UserData();
2285 userData.info = userInfo;
2286 userData.account = account;
2287 userData.seedAccountName = seedAccountName;
2288 userData.seedAccountType = seedAccountType;
2289 userData.persistSeedData = persistSeedData;
2290 userData.seedAccountOptions = seedAccountOptions;
2291
2292 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002293 if (baseRestrictions != null) {
2294 mBaseUserRestrictions.put(id, baseRestrictions);
2295 }
2296 if (localRestrictions != null) {
2297 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2298 }
2299 if (globalRestrictions != null) {
2300 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2301 }
Kenny Guy02c89902016-11-15 19:36:38 +00002302 }
2303 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002304 }
2305
Amith Yamasani920ace02012-09-20 22:15:37 -07002306 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2307 String valueString = parser.getAttributeValue(null, attr);
2308 if (valueString == null) return defaultValue;
2309 try {
2310 return Integer.parseInt(valueString);
2311 } catch (NumberFormatException nfe) {
2312 return defaultValue;
2313 }
2314 }
2315
2316 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2317 String valueString = parser.getAttributeValue(null, attr);
2318 if (valueString == null) return defaultValue;
2319 try {
2320 return Long.parseLong(valueString);
2321 } catch (NumberFormatException nfe) {
2322 return defaultValue;
2323 }
2324 }
2325
Amith Yamasanib82add22013-07-09 11:24:44 -07002326 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002327 * Removes the app restrictions file for a specific package and user id, if it exists.
2328 */
2329 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2330 synchronized (mPackagesLock) {
2331 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002332 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002333 if (resFile.exists()) {
2334 resFile.delete();
2335 }
2336 }
2337 }
2338
Kenny Guya52dc3e2014-02-11 15:33:14 +00002339 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002340 public UserInfo createProfileForUser(String name, int flags, int userId,
2341 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002342 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002343 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002344 }
2345
Amith Yamasani258848d2012-08-10 17:06:33 -07002346 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002347 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2348 String[] disallowedPackages) {
2349 checkManageOrCreateUsersPermission(flags);
2350 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2351 }
2352
2353 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002354 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2355 checkManageOrCreateUsersPermission("Only the system can remove users");
2356 return removeUserUnchecked(userHandle);
2357 }
2358
2359 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002360 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002361 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002362 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002363 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002364
Jessica Hummelbe81c802014-04-22 15:49:22 +01002365 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002366 return createUserInternal(name, flags, parentId, null);
2367 }
2368
2369 private UserInfo createUserInternal(String name, int flags, int parentId,
2370 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002371 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2372 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2373 : UserManager.DISALLOW_ADD_USER;
2374 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2375 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002376 return null;
2377 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002378 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2379 }
2380
2381 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2382 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002383 DeviceStorageMonitorInternal dsm = LocalServices
2384 .getService(DeviceStorageMonitorInternal.class);
2385 if (dsm.isMemoryLow()) {
2386 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2387 return null;
2388 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002389 if (ActivityManager.isLowRamDeviceStatic()) {
2390 return null;
2391 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002392 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002393 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002394 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002395 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002396 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002397 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002398 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002399 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002400 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002401 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002402 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002403 if (parentId != UserHandle.USER_NULL) {
2404 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002405 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002406 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002407 if (parent == null) return null;
2408 }
2409 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2410 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2411 return null;
2412 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002413 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2414 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002415 // been reached, cannot add a user.
2416 return null;
2417 }
2418 // If we're adding a guest and there already exists one, bail.
2419 if (isGuest && findCurrentGuestUser() != null) {
2420 return null;
2421 }
2422 // In legacy mode, restricted profile's parent can only be the owner user
2423 if (isRestricted && !UserManager.isSplitSystemUser()
2424 && (parentId != UserHandle.USER_SYSTEM)) {
2425 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2426 return null;
2427 }
2428 if (isRestricted && UserManager.isSplitSystemUser()) {
2429 if (parent == null) {
2430 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2431 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002432 return null;
2433 }
Amith Yamasani12747872015-12-07 14:19:49 -08002434 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002435 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2436 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002437 return null;
2438 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002439 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002440 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2441 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002442 Log.e(LOG_TAG,
2443 "Ephemeral users are supported on split-system-user systems only.");
2444 return null;
2445 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002446 // In split system user mode, we assign the first human user the primary flag.
2447 // And if there is no device owner, we also assign the admin flag to primary user.
2448 if (UserManager.isSplitSystemUser()
2449 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2450 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002451 synchronized (mUsersLock) {
2452 if (!mIsDeviceManaged) {
2453 flags |= UserInfo.FLAG_ADMIN;
2454 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002455 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002456 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002457
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002458 userId = getNextAvailableId();
2459 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002460 boolean ephemeralGuests = Resources.getSystem()
2461 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002462
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002463 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002464 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2465 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2466 || (parent != null && parent.info.isEphemeral())) {
2467 flags |= UserInfo.FLAG_EPHEMERAL;
2468 }
2469
2470 userInfo = new UserInfo(userId, name, null, flags);
2471 userInfo.serialNumber = mNextSerialNumber++;
2472 long now = System.currentTimeMillis();
2473 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2474 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002475 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002476 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2477 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2478 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002479 userData = new UserData();
2480 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002481 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002482 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002483 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002484 writeUserListLP();
2485 if (parent != null) {
2486 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002487 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2488 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002489 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002490 }
Amith Yamasani12747872015-12-07 14:19:49 -08002491 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002492 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002493 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2494 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002495 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002496 }
Amith Yamasani12747872015-12-07 14:19:49 -08002497 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002498 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002499 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002500 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002501 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002502 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002503 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002504 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002505 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002506 userInfo.partial = false;
2507 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002508 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002509 }
2510 updateUserIds();
2511 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002512 if (isGuest) {
2513 synchronized (mGuestRestrictions) {
2514 restrictions.putAll(mGuestRestrictions);
2515 }
2516 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002517 synchronized (mRestrictionsLock) {
2518 mBaseUserRestrictions.append(userId, restrictions);
2519 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002520 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002521 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2522 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2523 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2524 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002525 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002526 } finally {
2527 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002528 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002529 return userInfo;
2530 }
2531
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002532 @VisibleForTesting
2533 UserData putUserInfo(UserInfo userInfo) {
2534 final UserData userData = new UserData();
2535 userData.info = userInfo;
2536 synchronized (mUsers) {
2537 mUsers.put(userInfo.id, userData);
2538 }
2539 return userData;
2540 }
2541
2542 @VisibleForTesting
2543 void removeUserInfo(int userId) {
2544 synchronized (mUsers) {
2545 mUsers.remove(userId);
2546 }
2547 }
2548
Amith Yamasani0b285492011-04-14 17:35:23 -07002549 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002550 * @hide
2551 */
Amith Yamasani12747872015-12-07 14:19:49 -08002552 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002553 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002554 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002555 final UserInfo user = createProfileForUser(
2556 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002557 if (user == null) {
2558 return null;
2559 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002560 long identity = Binder.clearCallingIdentity();
2561 try {
2562 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2563 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2564 // the putIntForUser() will fail.
2565 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2566 android.provider.Settings.Secure.LOCATION_MODE,
2567 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2568 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2569 } finally {
2570 Binder.restoreCallingIdentity(identity);
2571 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002572 return user;
2573 }
2574
2575 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002576 * Find the current guest user. If the Guest user is partial,
2577 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002578 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002579 private UserInfo findCurrentGuestUser() {
2580 synchronized (mUsersLock) {
2581 final int size = mUsers.size();
2582 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002583 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002584 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2585 return user;
2586 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002587 }
2588 }
2589 return null;
2590 }
2591
2592 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002593 * Mark this guest user for deletion to allow us to create another guest
2594 * and switch to that user before actually removing this guest.
2595 * @param userHandle the userid of the current guest
2596 * @return whether the user could be marked for deletion
2597 */
Amith Yamasani12747872015-12-07 14:19:49 -08002598 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002599 public boolean markGuestForDeletion(int userHandle) {
2600 checkManageUsersPermission("Only the system can remove users");
2601 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2602 UserManager.DISALLOW_REMOVE_USER, false)) {
2603 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2604 return false;
2605 }
2606
2607 long ident = Binder.clearCallingIdentity();
2608 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002609 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002610 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002611 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002612 userData = mUsers.get(userHandle);
2613 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002614 return false;
2615 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002616 }
Amith Yamasani12747872015-12-07 14:19:49 -08002617 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002618 return false;
2619 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002620 // We set this to a guest user that is to be removed. This is a temporary state
2621 // where we are allowed to add new Guest users, even if this one is still not
2622 // removed. This user will still show up in getUserInfo() calls.
2623 // If we don't get around to removing this Guest user, it will be purged on next
2624 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002625 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002626 // Mark it as disabled, so that it isn't returned any more when
2627 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002628 userData.info.flags |= UserInfo.FLAG_DISABLED;
2629 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002630 }
2631 } finally {
2632 Binder.restoreCallingIdentity(ident);
2633 }
2634 return true;
2635 }
2636
2637 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002638 * Removes a user and all data directories created for that user. This method should be called
2639 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002640 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002641 */
Amith Yamasani12747872015-12-07 14:19:49 -08002642 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002643 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002644 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002645 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002646
2647 final boolean isManagedProfile;
2648 synchronized (mUsersLock) {
2649 UserInfo userInfo = getUserInfoLU(userHandle);
2650 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2651 }
2652 String restriction = isManagedProfile
2653 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2654 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2655 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002656 return false;
2657 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002658 return removeUserUnchecked(userHandle);
2659 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002660
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002661 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002662 long ident = Binder.clearCallingIdentity();
2663 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002664 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002665 int currentUser = ActivityManager.getCurrentUser();
2666 if (currentUser == userHandle) {
2667 Log.w(LOG_TAG, "Current user cannot be removed");
2668 return false;
2669 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002670 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002671 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002672 userData = mUsers.get(userHandle);
2673 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002674 return false;
2675 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002676
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002677 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002678 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002679
Kenny Guyee58b4f2014-05-23 15:19:53 +01002680 try {
2681 mAppOpsService.removeUser(userHandle);
2682 } catch (RemoteException e) {
2683 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2684 }
2685 // Set this to a partially created user, so that the user will be purged
2686 // on next startup, in case the runtime stops now before stopping and
2687 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002688 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002689 // Mark it as disabled, so that it isn't returned any more when
2690 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002691 userData.info.flags |= UserInfo.FLAG_DISABLED;
2692 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002693 }
2694
Amith Yamasani12747872015-12-07 14:19:49 -08002695 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2696 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002697 // Send broadcast to notify system that the user removed was a
2698 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002699 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002700 }
2701
2702 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2703 int res;
2704 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002705 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002706 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002707 @Override
2708 public void userStopped(int userId) {
2709 finishRemoveUser(userId);
2710 }
2711 @Override
2712 public void userStopAborted(int userId) {
2713 }
2714 });
2715 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002716 return false;
2717 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002718 return res == ActivityManager.USER_OP_SUCCESS;
2719 } finally {
2720 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002721 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002722 }
2723
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002724 @VisibleForTesting
2725 void addRemovingUserIdLocked(int userId) {
2726 // We remember deleted user IDs to prevent them from being
2727 // reused during the current boot; they can still be reused
2728 // after a reboot or recycling of userIds.
2729 mRemovingUserIds.put(userId, true);
2730 mRecentlyRemovedIds.add(userId);
2731 // Keep LRU queue of recently removed IDs for recycling
2732 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2733 mRecentlyRemovedIds.removeFirst();
2734 }
2735 }
2736
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002737 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002738 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002739 // Let other services shutdown any activity and clean up their state before completely
2740 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002741 long ident = Binder.clearCallingIdentity();
2742 try {
2743 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2744 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002745 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2746 android.Manifest.permission.MANAGE_USERS,
2747
2748 new BroadcastReceiver() {
2749 @Override
2750 public void onReceive(Context context, Intent intent) {
2751 if (DBG) {
2752 Slog.i(LOG_TAG,
2753 "USER_REMOVED broadcast sent, cleaning up user data "
2754 + userHandle);
2755 }
2756 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002757 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002758 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002759 // Clean up any ActivityManager state
2760 LocalServices.getService(ActivityManagerInternal.class)
2761 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002762 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002763 }
2764 }.start();
2765 }
2766 },
2767
2768 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002769 } finally {
2770 Binder.restoreCallingIdentity(ident);
2771 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002772 }
2773
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002774 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002775 try {
2776 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2777 } catch (IllegalStateException e) {
2778 // This may be simply because the user was partially created.
2779 Slog.i(LOG_TAG,
2780 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2781 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002782
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002783 // Cleanup gatekeeper secure user id
2784 try {
2785 final IGateKeeperService gk = GateKeeper.getService();
2786 if (gk != null) {
2787 gk.clearSecureUserId(userHandle);
2788 }
2789 } catch (Exception ex) {
2790 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2791 }
2792
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002793 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002794 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002795
2796 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002797 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002798 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2799
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002800 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002801 synchronized (mUsersLock) {
2802 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002803 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002804 }
2805 synchronized (mUserStates) {
2806 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002807 }
2808 synchronized (mRestrictionsLock) {
2809 mBaseUserRestrictions.remove(userHandle);
2810 mAppliedUserRestrictions.remove(userHandle);
2811 mCachedEffectiveUserRestrictions.remove(userHandle);
2812 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002813 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2814 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2815 applyUserRestrictionsForAllUsersLR();
2816 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002817 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002818 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002819 synchronized (mPackagesLock) {
2820 writeUserListLP();
2821 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002822 // Remove user file
2823 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2824 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002825 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002826 if (RELEASE_DELETED_USER_ID) {
2827 synchronized (mUsers) {
2828 mRemovingUserIds.delete(userHandle);
2829 }
2830 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002831 }
2832
Kenny Guyf8d3a232014-05-15 16:09:52 +01002833 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002834 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002835 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2836 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002837 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002838 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002839 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002840 }
2841
Amith Yamasani2a003292012-08-14 18:25:45 -07002842 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002843 public Bundle getApplicationRestrictions(String packageName) {
2844 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2845 }
2846
2847 @Override
2848 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002849 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002850 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002851 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002852 }
2853 synchronized (mPackagesLock) {
2854 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002855 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002856 }
2857 }
2858
2859 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002860 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002861 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002862 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002863 if (restrictions != null) {
2864 restrictions.setDefusable(true);
2865 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002866 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002867 if (restrictions == null || restrictions.isEmpty()) {
2868 cleanAppRestrictionsForPackage(packageName, userId);
2869 } else {
2870 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002871 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002872 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002873 }
Robin Lee66e5d962014-04-09 16:44:21 +01002874
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002875 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2876 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2877 changeIntent.setPackage(packageName);
2878 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2879 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002880 }
2881
2882 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002883 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002884 try {
2885 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002886 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002887 } catch (NameNotFoundException nnfe) {
2888 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002889 } finally {
2890 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002891 }
2892 }
2893
Fyodor Kupolov82402752015-10-28 14:54:51 -07002894 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002895 AtomicFile restrictionsFile =
2896 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2897 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002898 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002899 }
2900
2901 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002902 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002903 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002904 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002905 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002906 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002907 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002908
2909 FileInputStream fis = null;
2910 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002911 fis = restrictionsFile.openRead();
2912 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002913 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002914 XmlUtils.nextElement(parser);
2915 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002916 Slog.e(LOG_TAG, "Unable to read restrictions file "
2917 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002918 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002919 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002920 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2921 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002922 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002923 } catch (IOException|XmlPullParserException e) {
2924 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002925 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002926 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002927 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002928 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002929 }
2930
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002931 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2932 XmlPullParser parser) throws XmlPullParserException, IOException {
2933 int type = parser.getEventType();
2934 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2935 String key = parser.getAttributeValue(null, ATTR_KEY);
2936 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2937 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2938 if (multiple != null) {
2939 values.clear();
2940 int count = Integer.parseInt(multiple);
2941 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2942 if (type == XmlPullParser.START_TAG
2943 && parser.getName().equals(TAG_VALUE)) {
2944 values.add(parser.nextText().trim());
2945 count--;
2946 }
2947 }
2948 String [] valueStrings = new String[values.size()];
2949 values.toArray(valueStrings);
2950 restrictions.putStringArray(key, valueStrings);
2951 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2952 restrictions.putBundle(key, readBundleEntry(parser, values));
2953 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2954 final int outerDepth = parser.getDepth();
2955 ArrayList<Bundle> bundleList = new ArrayList<>();
2956 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2957 Bundle childBundle = readBundleEntry(parser, values);
2958 bundleList.add(childBundle);
2959 }
2960 restrictions.putParcelableArray(key,
2961 bundleList.toArray(new Bundle[bundleList.size()]));
2962 } else {
2963 String value = parser.nextText().trim();
2964 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2965 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2966 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2967 restrictions.putInt(key, Integer.parseInt(value));
2968 } else {
2969 restrictions.putString(key, value);
2970 }
2971 }
2972 }
2973 }
2974
2975 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2976 throws IOException, XmlPullParserException {
2977 Bundle childBundle = new Bundle();
2978 final int outerDepth = parser.getDepth();
2979 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2980 readEntry(childBundle, values, parser);
2981 }
2982 return childBundle;
2983 }
2984
Fyodor Kupolov82402752015-10-28 14:54:51 -07002985 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002986 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002987 AtomicFile restrictionsFile = new AtomicFile(
2988 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002989 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002990 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002991 }
2992
2993 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002994 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002995 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002996 try {
2997 fos = restrictionsFile.startWrite();
2998 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2999
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003000 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003001 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003002 serializer.startDocument(null, true);
3003 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3004
3005 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003006 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003007 serializer.endTag(null, TAG_RESTRICTIONS);
3008
3009 serializer.endDocument();
3010 restrictionsFile.finishWrite(fos);
3011 } catch (Exception e) {
3012 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003013 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3014 }
3015 }
3016
3017 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3018 throws IOException {
3019 for (String key : restrictions.keySet()) {
3020 Object value = restrictions.get(key);
3021 serializer.startTag(null, TAG_ENTRY);
3022 serializer.attribute(null, ATTR_KEY, key);
3023
3024 if (value instanceof Boolean) {
3025 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3026 serializer.text(value.toString());
3027 } else if (value instanceof Integer) {
3028 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3029 serializer.text(value.toString());
3030 } else if (value == null || value instanceof String) {
3031 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3032 serializer.text(value != null ? (String) value : "");
3033 } else if (value instanceof Bundle) {
3034 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3035 writeBundle((Bundle) value, serializer);
3036 } else if (value instanceof Parcelable[]) {
3037 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3038 Parcelable[] array = (Parcelable[]) value;
3039 for (Parcelable parcelable : array) {
3040 if (!(parcelable instanceof Bundle)) {
3041 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3042 }
3043 serializer.startTag(null, TAG_ENTRY);
3044 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3045 writeBundle((Bundle) parcelable, serializer);
3046 serializer.endTag(null, TAG_ENTRY);
3047 }
3048 } else {
3049 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3050 String[] values = (String[]) value;
3051 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3052 for (String choice : values) {
3053 serializer.startTag(null, TAG_VALUE);
3054 serializer.text(choice != null ? choice : "");
3055 serializer.endTag(null, TAG_VALUE);
3056 }
3057 }
3058 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003059 }
3060 }
3061
3062 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003063 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003064 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003065 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003066 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003067 }
3068 }
3069
3070 @Override
3071 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003072 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003073 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003074 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003075 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003076 }
3077 // Not found
3078 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003079 }
3080 }
3081
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003082 @Override
3083 public long getUserCreationTime(int userHandle) {
3084 int callingUserId = UserHandle.getCallingUserId();
3085 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003086 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003087 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003088 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003089 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003090 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003091 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003092 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003093 }
3094 }
3095 }
3096 if (userInfo == null) {
3097 throw new SecurityException("userHandle can only be the calling user or a managed "
3098 + "profile associated with this user");
3099 }
3100 return userInfo.creationTime;
3101 }
3102
Amith Yamasani0b285492011-04-14 17:35:23 -07003103 /**
3104 * Caches the list of user ids in an array, adjusting the array size when necessary.
3105 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003106 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003107 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003108 synchronized (mUsersLock) {
3109 final int userSize = mUsers.size();
3110 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003111 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003112 num++;
3113 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003114 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003115 final int[] newUsers = new int[num];
3116 int n = 0;
3117 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003118 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003119 newUsers[n++] = mUsers.keyAt(i);
3120 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003121 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003122 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003123 }
3124 }
3125
3126 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003127 * Called right before a user is started. This gives us a chance to prepare
3128 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003129 */
3130 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003131 UserInfo userInfo = getUserInfo(userId);
3132 if (userInfo == null) {
3133 return;
3134 }
3135 final int userSerial = userInfo.serialNumber;
3136 // Migrate only if build fingerprints mismatch
3137 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003138 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003139 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003140
3141 if (userId != UserHandle.USER_SYSTEM) {
3142 synchronized (mRestrictionsLock) {
3143 applyUserRestrictionsLR(userId);
3144 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003145 }
3146 }
3147
3148 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003149 * Called right before a user is unlocked. This gives us a chance to prepare
3150 * app storage.
3151 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003152 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003153 UserInfo userInfo = getUserInfo(userId);
3154 if (userInfo == null) {
3155 return;
3156 }
3157 final int userSerial = userInfo.serialNumber;
3158 // Migrate only if build fingerprints mismatch
3159 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003160 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003161 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003162 }
3163
3164 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003165 * Examine all users present on given mounted volume, and destroy data
3166 * belonging to users that are no longer valid, or whose user ID has been
3167 * recycled.
3168 */
3169 void reconcileUsers(String volumeUuid) {
3170 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3171 }
3172
3173 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003174 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003175 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003176 * @param userId the user that was just foregrounded
3177 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003178 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003179 UserData userData = getUserDataNoChecks(userId);
3180 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003181 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3182 return;
3183 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003184
3185 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003186 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003187 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003188 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003189 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3190 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003191 }
3192
3193 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003194 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003195 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003196 @VisibleForTesting
3197 int getNextAvailableId() {
3198 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003199 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003200 nextId = scanNextAvailableIdLocked();
3201 if (nextId >= 0) {
3202 return nextId;
3203 }
3204 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3205 // except most recently removed
3206 if (mRemovingUserIds.size() > 0) {
3207 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3208 mRemovingUserIds.clear();
3209 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3210 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003211 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003212 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003213 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003214 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003215 if (nextId < 0) {
3216 throw new IllegalStateException("No user id available!");
3217 }
3218 return nextId;
3219 }
3220
3221 private int scanNextAvailableIdLocked() {
3222 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3223 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3224 return i;
3225 }
3226 }
3227 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003228 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003229
Amith Yamasanifc95e702013-09-26 13:20:17 -07003230 private String packageToRestrictionsFileName(String packageName) {
3231 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3232 }
3233
Amith Yamasani920ace02012-09-20 22:15:37 -07003234 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003235 public void setSeedAccountData(int userId, String accountName, String accountType,
3236 PersistableBundle accountOptions, boolean persist) {
3237 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3238 synchronized (mPackagesLock) {
3239 final UserData userData;
3240 synchronized (mUsersLock) {
3241 userData = getUserDataLU(userId);
3242 if (userData == null) {
3243 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3244 return;
3245 }
3246 userData.seedAccountName = accountName;
3247 userData.seedAccountType = accountType;
3248 userData.seedAccountOptions = accountOptions;
3249 userData.persistSeedData = persist;
3250 }
3251 if (persist) {
3252 writeUserLP(userData);
3253 }
3254 }
3255 }
3256
3257 @Override
3258 public String getSeedAccountName() throws RemoteException {
3259 checkManageUsersPermission("Cannot get seed account information");
3260 synchronized (mUsersLock) {
3261 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3262 return userData.seedAccountName;
3263 }
3264 }
3265
3266 @Override
3267 public String getSeedAccountType() throws RemoteException {
3268 checkManageUsersPermission("Cannot get seed account information");
3269 synchronized (mUsersLock) {
3270 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3271 return userData.seedAccountType;
3272 }
3273 }
3274
3275 @Override
3276 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3277 checkManageUsersPermission("Cannot get seed account information");
3278 synchronized (mUsersLock) {
3279 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3280 return userData.seedAccountOptions;
3281 }
3282 }
3283
3284 @Override
3285 public void clearSeedAccountData() throws RemoteException {
3286 checkManageUsersPermission("Cannot clear seed account information");
3287 synchronized (mPackagesLock) {
3288 UserData userData;
3289 synchronized (mUsersLock) {
3290 userData = getUserDataLU(UserHandle.getCallingUserId());
3291 if (userData == null) return;
3292 userData.clearSeedAccountData();
3293 }
3294 writeUserLP(userData);
3295 }
3296 }
3297
3298 @Override
3299 public boolean someUserHasSeedAccount(String accountName, String accountType)
3300 throws RemoteException {
3301 checkManageUsersPermission("Cannot check seed account information");
3302 synchronized (mUsersLock) {
3303 final int userSize = mUsers.size();
3304 for (int i = 0; i < userSize; i++) {
3305 final UserData data = mUsers.valueAt(i);
3306 if (data.info.isInitialized()) continue;
3307 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3308 continue;
3309 }
3310 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3311 continue;
3312 }
3313 return true;
3314 }
3315 }
3316 return false;
3317 }
3318
3319 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003320 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003321 FileDescriptor err, String[] args, ShellCallback callback,
3322 ResultReceiver resultReceiver) {
3323 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003324 }
3325
3326 int onShellCommand(Shell shell, String cmd) {
3327 if (cmd == null) {
3328 return shell.handleDefaultCommands(cmd);
3329 }
3330
3331 final PrintWriter pw = shell.getOutPrintWriter();
3332 try {
3333 switch(cmd) {
3334 case "list":
3335 return runList(pw);
3336 }
3337 } catch (RemoteException e) {
3338 pw.println("Remote exception: " + e);
3339 }
3340 return -1;
3341 }
3342
3343 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003344 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003345 final List<UserInfo> users = getUsers(false);
3346 if (users == null) {
3347 pw.println("Error: couldn't get users");
3348 return 1;
3349 } else {
3350 pw.println("Users:");
3351 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003352 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003353 pw.println("\t" + users.get(i).toString() + running);
3354 }
3355 return 0;
3356 }
3357 }
3358
3359 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003360 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3361 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3362 != PackageManager.PERMISSION_GRANTED) {
3363 pw.println("Permission Denial: can't dump UserManager from from pid="
3364 + Binder.getCallingPid()
3365 + ", uid=" + Binder.getCallingUid()
3366 + " without permission "
3367 + android.Manifest.permission.DUMP);
3368 return;
3369 }
3370
3371 long now = System.currentTimeMillis();
3372 StringBuilder sb = new StringBuilder();
3373 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003374 synchronized (mUsersLock) {
3375 pw.println("Users:");
3376 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003377 UserData userData = mUsers.valueAt(i);
3378 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003379 continue;
3380 }
Amith Yamasani12747872015-12-07 14:19:49 -08003381 UserInfo userInfo = userData.info;
3382 final int userId = userInfo.id;
3383 pw.print(" "); pw.print(userInfo);
3384 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003385 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003386 pw.print(" <removing> ");
3387 }
Amith Yamasani12747872015-12-07 14:19:49 -08003388 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003389 pw.print(" <partial>");
3390 }
3391 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003392 pw.print(" State: ");
3393 final int state;
3394 synchronized (mUserStates) {
3395 state = mUserStates.get(userId, -1);
3396 }
3397 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003398 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003399 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003400 pw.println("<unknown>");
3401 } else {
3402 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003403 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003404 sb.append(" ago");
3405 pw.println(sb);
3406 }
3407 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003408 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003409 pw.println("<unknown>");
3410 } else {
3411 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003412 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003413 sb.append(" ago");
3414 pw.println(sb);
3415 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003416 pw.print(" Last logged in fingerprint: ");
3417 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003418 pw.print(" Has profile owner: ");
3419 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003420 pw.println(" Restrictions:");
3421 synchronized (mRestrictionsLock) {
3422 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003423 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003424 pw.println(" Device policy global restrictions:");
3425 UserRestrictionsUtils.dumpRestrictions(
3426 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003427 pw.println(" Device policy local restrictions:");
3428 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003429 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003430 pw.println(" Effective restrictions:");
3431 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003432 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003433 }
Amith Yamasani12747872015-12-07 14:19:49 -08003434
3435 if (userData.account != null) {
3436 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003437 pw.println();
3438 }
Amith Yamasani12747872015-12-07 14:19:49 -08003439
3440 if (userData.seedAccountName != null) {
3441 pw.print(" Seed account name: " + userData.seedAccountName);
3442 pw.println();
3443 if (userData.seedAccountType != null) {
3444 pw.print(" account type: " + userData.seedAccountType);
3445 pw.println();
3446 }
3447 if (userData.seedAccountOptions != null) {
3448 pw.print(" account options exist");
3449 pw.println();
3450 }
3451 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003452 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003453 }
Amith Yamasani12747872015-12-07 14:19:49 -08003454 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003455 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003456 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003457 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003458 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003459 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003460 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003461 synchronized (mUsersLock) {
3462 pw.println();
3463 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003464 if (mRemovingUserIds.size() > 0) {
3465 pw.println();
3466 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3467 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003468 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003469 synchronized (mUserStates) {
3470 pw.println(" Started users state: " + mUserStates);
3471 }
Amith Yamasani12747872015-12-07 14:19:49 -08003472 // Dump some capabilities
3473 pw.println();
3474 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3475 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003476 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3477 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003478 }
3479 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003480
3481 final class MainHandler extends Handler {
3482
3483 @Override
3484 public void handleMessage(Message msg) {
3485 switch (msg.what) {
3486 case WRITE_USER_MSG:
3487 removeMessages(WRITE_USER_MSG, msg.obj);
3488 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003489 int userId = ((UserData) msg.obj).info.id;
3490 UserData userData = getUserDataNoChecks(userId);
3491 if (userData != null) {
3492 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003493 }
3494 }
3495 }
3496 }
3497 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003498
3499 /**
3500 * @param userId
3501 * @return whether the user has been initialized yet
3502 */
3503 boolean isInitialized(int userId) {
3504 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3505 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003506
3507 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003508 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003509 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3510 boolean isDeviceOwner, int cameraRestrictionScope) {
3511 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3512 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003513 }
3514
3515 @Override
3516 public Bundle getBaseUserRestrictions(int userId) {
3517 synchronized (mRestrictionsLock) {
3518 return mBaseUserRestrictions.get(userId);
3519 }
3520 }
3521
3522 @Override
3523 public void setBaseUserRestrictionsByDpmsForMigration(
3524 int userId, Bundle baseRestrictions) {
3525 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003526 if (updateRestrictionsIfNeededLR(
3527 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3528 invalidateEffectiveUserRestrictionsLR(userId);
3529 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003530 }
3531
Amith Yamasani12747872015-12-07 14:19:49 -08003532 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003533 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003534 if (userData != null) {
3535 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003536 } else {
3537 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3538 }
3539 }
3540 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003541
3542 @Override
3543 public boolean getUserRestriction(int userId, String key) {
3544 return getUserRestrictions(userId).getBoolean(key);
3545 }
3546
3547 @Override
3548 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3549 synchronized (mUserRestrictionsListeners) {
3550 mUserRestrictionsListeners.add(listener);
3551 }
3552 }
3553
3554 @Override
3555 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3556 synchronized (mUserRestrictionsListeners) {
3557 mUserRestrictionsListeners.remove(listener);
3558 }
3559 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003560
3561 @Override
3562 public void setDeviceManaged(boolean isManaged) {
3563 synchronized (mUsersLock) {
3564 mIsDeviceManaged = isManaged;
3565 }
3566 }
3567
3568 @Override
3569 public void setUserManaged(int userId, boolean isManaged) {
3570 synchronized (mUsersLock) {
3571 mIsUserManaged.put(userId, isManaged);
3572 }
3573 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003574
3575 @Override
3576 public void setUserIcon(int userId, Bitmap bitmap) {
3577 long ident = Binder.clearCallingIdentity();
3578 try {
3579 synchronized (mPackagesLock) {
3580 UserData userData = getUserDataNoChecks(userId);
3581 if (userData == null || userData.info.partial) {
3582 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3583 return;
3584 }
3585 writeBitmapLP(userData.info, bitmap);
3586 writeUserLP(userData);
3587 }
3588 sendUserInfoChangedBroadcast(userId);
3589 } finally {
3590 Binder.restoreCallingIdentity(ident);
3591 }
3592 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003593
3594 @Override
3595 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3596 synchronized (mUsersLock) {
3597 mForceEphemeralUsers = forceEphemeralUsers;
3598 }
3599 }
3600
3601 @Override
3602 public void removeAllUsers() {
3603 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3604 // Remove the non-system users straight away.
3605 removeNonSystemUsers();
3606 } else {
3607 // Switch to the system user first and then remove the other users.
3608 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3609 @Override
3610 public void onReceive(Context context, Intent intent) {
3611 int userId =
3612 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3613 if (userId != UserHandle.USER_SYSTEM) {
3614 return;
3615 }
3616 mContext.unregisterReceiver(this);
3617 removeNonSystemUsers();
3618 }
3619 };
3620 IntentFilter userSwitchedFilter = new IntentFilter();
3621 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3622 mContext.registerReceiver(
3623 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3624
3625 // Switch to the system user.
3626 ActivityManager am =
3627 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3628 am.switchUser(UserHandle.USER_SYSTEM);
3629 }
3630 }
phweisse9c44062016-02-10 12:57:38 +01003631
3632 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003633 public void onEphemeralUserStop(int userId) {
3634 synchronized (mUsersLock) {
3635 UserInfo userInfo = getUserInfoLU(userId);
3636 if (userInfo != null && userInfo.isEphemeral()) {
3637 // Do not allow switching back to the ephemeral user again as the user is going
3638 // to be deleted.
3639 userInfo.flags |= UserInfo.FLAG_DISABLED;
3640 if (userInfo.isGuest()) {
3641 // Indicate that the guest will be deleted after it stops.
3642 userInfo.guestToRemove = true;
3643 }
3644 }
3645 }
3646 }
3647
3648 @Override
phweisse9c44062016-02-10 12:57:38 +01003649 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003650 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003651 // Keep this in sync with UserManager.createUser
3652 if (user != null && !user.isAdmin()) {
3653 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3654 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3655 }
3656 return user;
3657 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003658
3659 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003660 public boolean removeUserEvenWhenDisallowed(int userId) {
3661 return removeUserUnchecked(userId);
3662 }
3663
3664 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003665 public boolean isUserRunning(int userId) {
3666 synchronized (mUserStates) {
3667 return mUserStates.get(userId, -1) >= 0;
3668 }
3669 }
3670
3671 @Override
3672 public void setUserState(int userId, int userState) {
3673 synchronized (mUserStates) {
3674 mUserStates.put(userId, userState);
3675 }
3676 }
3677
3678 @Override
3679 public void removeUserState(int userId) {
3680 synchronized (mUserStates) {
3681 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003682 }
3683 }
3684
3685 @Override
3686 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003687 synchronized (mUserStates) {
3688 int state = mUserStates.get(userId, -1);
3689 return (state == UserState.STATE_RUNNING_UNLOCKING)
3690 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003691 }
3692 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003693
3694 @Override
3695 public boolean isUserUnlocked(int userId) {
3696 synchronized (mUserStates) {
3697 int state = mUserStates.get(userId, -1);
3698 return state == UserState.STATE_RUNNING_UNLOCKED;
3699 }
3700 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003701 }
3702
3703 /* Remove all the users except of the system one. */
3704 private void removeNonSystemUsers() {
3705 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3706 synchronized (mUsersLock) {
3707 final int userSize = mUsers.size();
3708 for (int i = 0; i < userSize; i++) {
3709 UserInfo ui = mUsers.valueAt(i).info;
3710 if (ui.id != UserHandle.USER_SYSTEM) {
3711 usersToRemove.add(ui);
3712 }
3713 }
3714 }
3715 for (UserInfo ui: usersToRemove) {
3716 removeUser(ui.id);
3717 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003718 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003719
3720 private class Shell extends ShellCommand {
3721 @Override
3722 public int onCommand(String cmd) {
3723 return onShellCommand(this, cmd);
3724 }
3725
3726 @Override
3727 public void onHelp() {
3728 final PrintWriter pw = getOutPrintWriter();
3729 pw.println("User manager (user) commands:");
3730 pw.println(" help");
3731 pw.println(" Print this help text.");
3732 pw.println("");
3733 pw.println(" list");
3734 pw.println(" Prints all users on the system.");
3735 }
3736 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003737
3738 private static void debug(String message) {
3739 Log.d(LOG_TAG, message +
3740 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3741 }
Kenny Guy02c89902016-11-15 19:36:38 +00003742
3743 @VisibleForTesting
3744 static int getMaxManagedProfiles() {
3745 // Allow overriding max managed profiles on debuggable builds for testing
3746 // of multiple profiles.
3747 if (!Build.IS_DEBUGGABLE) {
3748 return MAX_MANAGED_PROFILES;
3749 } else {
3750 return SystemProperties.getInt("persist.sys.max_profiles",
3751 MAX_MANAGED_PROFILES);
3752 }
3753 }
3754
3755 @VisibleForTesting
3756 int getFreeProfileBadgeLU(int parentUserId) {
3757 int maxManagedProfiles = getMaxManagedProfiles();
3758 boolean[] usedBadges = new boolean[maxManagedProfiles];
3759 final int userSize = mUsers.size();
3760 for (int i = 0; i < userSize; i++) {
3761 UserInfo ui = mUsers.valueAt(i).info;
3762 // Check which badge indexes are already used by this profile group.
3763 if (ui.isManagedProfile()
3764 && ui.profileGroupId == parentUserId
3765 && !mRemovingUserIds.get(ui.id)
3766 && ui.profileBadge < maxManagedProfiles) {
3767 usedBadges[ui.profileBadge] = true;
3768 }
3769 }
3770 for (int i = 0; i < maxManagedProfiles; i++) {
3771 if (!usedBadges[i]) {
3772 return i;
3773 }
3774 }
3775 return 0;
3776 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003777
3778 /**
3779 * Checks if the given user has a managed profile associated with it.
3780 * @param userId The parent user
3781 * @return
3782 */
3783 boolean hasManagedProfile(int userId) {
3784 synchronized (mUsersLock) {
3785 UserInfo userInfo = getUserInfoLU(userId);
3786 final int userSize = mUsers.size();
3787 for (int i = 0; i < userSize; i++) {
3788 UserInfo profile = mUsers.valueAt(i).info;
3789 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3790 return true;
3791 }
3792 }
3793 return false;
3794 }
3795 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003796}