blob: b9fcf4e39203d351bbd44d65b1a8c453e7d071ae [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 }
1496 }
1497 });
1498 }
1499
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001500 // Package private for the inner class.
1501 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001502 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001503 }
1504
1505 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001506 // Package private for the inner class.
1507 void applyUserRestrictionsForAllUsersLR() {
1508 if (DBG) {
1509 debug("applyUserRestrictionsForAllUsersLR");
1510 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001511 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001512 mCachedEffectiveUserRestrictions.clear();
1513
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001514 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001515 // it on a handler.
1516 final Runnable r = new Runnable() {
1517 @Override
1518 public void run() {
1519 // Then get the list of running users.
1520 final int[] runningUsers;
1521 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001522 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001523 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001524 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001525 return;
1526 }
1527 // Then re-calculate the effective restrictions and apply, only for running users.
1528 // It's okay if a new user has started after the getRunningUserIds() call,
1529 // because we'll do the same thing (re-calculate the restrictions and apply)
1530 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001531 synchronized (mRestrictionsLock) {
1532 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001533 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001534 }
1535 }
1536 }
1537 };
1538 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001539 }
1540
Amith Yamasani258848d2012-08-10 17:06:33 -07001541 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001542 * Check if we've hit the limit of how many users can be created.
1543 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001544 private boolean isUserLimitReached() {
1545 int count;
1546 synchronized (mUsersLock) {
1547 count = getAliveUsersExcludingGuestsCountLU();
1548 }
1549 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001550 }
1551
1552 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001553 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001554 checkManageUsersPermission("check if more managed profiles can be added.");
1555 if (ActivityManager.isLowRamDeviceStatic()) {
1556 return false;
1557 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001558 if (!mContext.getPackageManager().hasSystemFeature(
1559 PackageManager.FEATURE_MANAGED_USERS)) {
1560 return false;
1561 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001562 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001563 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001564 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001565 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001566 return false;
1567 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001568 synchronized(mUsersLock) {
1569 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001570 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001571 return false;
1572 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001573 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1574 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001575 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001576 return usersCountAfterRemoving == 1
1577 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001578 }
1579 }
1580
Fyodor Kupolov82402752015-10-28 14:54:51 -07001581 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001582 int aliveUserCount = 0;
1583 final int totalUserCount = mUsers.size();
1584 // Skip over users being removed
1585 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001586 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001587 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001588 aliveUserCount++;
1589 }
1590 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001591 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001592 }
1593
1594 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001595 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001596 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1597 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1598 * permissions can make certain calls to the UserManager.
1599 *
1600 * @param message used as message if SecurityException is thrown
1601 * @throws SecurityException if the caller does not have enough privilege.
1602 */
1603 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1604 final int uid = Binder.getCallingUid();
1605 if (uid != Process.SYSTEM_UID && uid != 0
1606 && ActivityManager.checkComponentPermission(
1607 Manifest.permission.MANAGE_USERS,
1608 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1609 && ActivityManager.checkComponentPermission(
1610 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1611 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1612 throw new SecurityException(
1613 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1614 + message);
1615 }
1616 }
1617
1618 /**
1619 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001620 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001621 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001622 *
1623 * @param message used as message if SecurityException is thrown
1624 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001625 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001626 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001627 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001628 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001629 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1630 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001631 }
1632
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001633 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001634 * Enforces that only the system UID or root's UID or apps that have the
1635 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1636 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1637 * can make certain calls to the UserManager.
1638 *
1639 * @param message used as message if SecurityException is thrown
1640 * @throws SecurityException if the caller is not system or root
1641 * @see #hasManageOrCreateUsersPermission()
1642 */
1643 private static final void checkManageOrCreateUsersPermission(String message) {
1644 if (!hasManageOrCreateUsersPermission()) {
1645 throw new SecurityException(
1646 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1647 }
1648 }
1649
1650 /**
1651 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1652 * to create user/profiles other than what is allowed for
1653 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1654 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1655 */
1656 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1657 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1658 if (!hasManageOrCreateUsersPermission()) {
1659 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1660 + "permission to create an user with flags: " + creationFlags);
1661 }
1662 } else if (!hasManageUsersPermission()) {
1663 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1664 + " with flags: " + creationFlags);
1665 }
1666 }
1667
1668 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001669 * @return whether the calling UID is system UID or root's UID or the calling app has the
1670 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1671 */
1672 private static final boolean hasManageUsersPermission() {
1673 final int callingUid = Binder.getCallingUid();
1674 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1675 || callingUid == Process.ROOT_UID
1676 || ActivityManager.checkComponentPermission(
1677 android.Manifest.permission.MANAGE_USERS,
1678 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1679 }
1680
1681 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001682 * @return whether the calling UID is system UID or root's UID or the calling app has the
1683 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1684 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1685 */
1686 private static final boolean hasManageOrCreateUsersPermission() {
1687 final int callingUid = Binder.getCallingUid();
1688 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1689 || callingUid == Process.ROOT_UID
1690 || ActivityManager.checkComponentPermission(
1691 android.Manifest.permission.MANAGE_USERS,
1692 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1693 || ActivityManager.checkComponentPermission(
1694 android.Manifest.permission.CREATE_USERS,
1695 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1696 }
1697
1698 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001699 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1700 * UserManager.
1701 *
1702 * @param message used as message if SecurityException is thrown
1703 * @throws SecurityException if the caller is not system or root
1704 */
1705 private static void checkSystemOrRoot(String message) {
1706 final int uid = Binder.getCallingUid();
1707 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1708 throw new SecurityException("Only system may: " + message);
1709 }
1710 }
1711
Fyodor Kupolov82402752015-10-28 14:54:51 -07001712 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001713 try {
1714 File dir = new File(mUsersDir, Integer.toString(info.id));
1715 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001716 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001717 if (!dir.exists()) {
1718 dir.mkdir();
1719 FileUtils.setPermissions(
1720 dir.getPath(),
1721 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1722 -1, -1);
1723 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001724 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001725 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001726 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001727 info.iconPath = file.getAbsolutePath();
1728 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001729 try {
1730 os.close();
1731 } catch (IOException ioe) {
1732 // What the ... !
1733 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001734 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001735 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001736 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001737 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001738 }
1739
Amith Yamasani0b285492011-04-14 17:35:23 -07001740 /**
1741 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1742 * cache it elsewhere.
1743 * @return the array of user ids.
1744 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001745 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001746 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001747 return mUserIds;
1748 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001749 }
1750
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001751 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001752 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001753 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001754 return;
1755 }
1756 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001757 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001758 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001759 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001760 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001761 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001762 int type;
1763 while ((type = parser.next()) != XmlPullParser.START_TAG
1764 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001765 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001766 }
1767
1768 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001769 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001770 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001771 return;
1772 }
1773
Amith Yamasani2a003292012-08-14 18:25:45 -07001774 mNextSerialNumber = -1;
1775 if (parser.getName().equals(TAG_USERS)) {
1776 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1777 if (lastSerialNumber != null) {
1778 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1779 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001780 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1781 if (versionNumber != null) {
1782 mUserVersion = Integer.parseInt(versionNumber);
1783 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001784 }
1785
Pavel Grafov6a40f092016-10-25 15:46:51 +01001786 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1787 // currently), take care of it in case of upgrade.
1788 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001789
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001790 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301791 if (type == XmlPullParser.START_TAG) {
1792 final String name = parser.getName();
1793 if (name.equals(TAG_USER)) {
1794 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001795
Amith Yamasani12747872015-12-07 14:19:49 -08001796 UserData userData = readUserLP(Integer.parseInt(id));
1797
1798 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001799 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001800 mUsers.put(userData.info.id, userData);
1801 if (mNextSerialNumber < 0
1802 || mNextSerialNumber <= userData.info.id) {
1803 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001804 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301805 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001806 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301807 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001808 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1809 && type != XmlPullParser.END_TAG) {
1810 if (type == XmlPullParser.START_TAG) {
1811 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001812 synchronized (mGuestRestrictions) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001813 mGuestRestrictions.putAll(
1814 UserRestrictionsUtils.readRestrictions(parser));
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001815 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001816 }
1817 break;
1818 }
1819 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001820 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1821 // Legacy name, should only be encountered when upgrading from pre-O.
1822 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001823 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1824 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001825 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001826 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001827 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1828 // Should only happen when upgrading from pre-O (version < 7).
1829 oldDevicePolicyGlobalUserRestrictions =
1830 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001831 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001832 }
1833 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001834
Fyodor Kupolov82402752015-10-28 14:54:51 -07001835 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001836 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001837 } catch (IOException | XmlPullParserException e) {
1838 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001839 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001840 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001841 }
1842 }
1843
Amith Yamasani6f34b412012-10-22 18:19:27 -07001844 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001845 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001846 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001847 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001848 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001849 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001850 int userVersion = mUserVersion;
1851 if (userVersion < 1) {
1852 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001853 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1854 if ("Primary".equals(userData.info.name)) {
1855 userData.info.name =
1856 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1857 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001858 }
1859 userVersion = 1;
1860 }
1861
Amith Yamasanibc9625052012-11-15 14:39:18 -08001862 if (userVersion < 2) {
1863 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001864 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1865 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1866 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1867 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001868 }
1869 userVersion = 2;
1870 }
1871
Amith Yamasani350962c2013-08-06 11:18:53 -07001872
Amith Yamasani5e486f52013-08-07 11:06:44 -07001873 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001874 userVersion = 4;
1875 }
1876
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001877 if (userVersion < 5) {
1878 initDefaultGuestRestrictions();
1879 userVersion = 5;
1880 }
1881
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001882 if (userVersion < 6) {
1883 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001884 synchronized (mUsersLock) {
1885 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001886 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001887 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001888 if (!splitSystemUser && userData.info.isRestricted()
1889 && (userData.info.restrictedProfileParentId
1890 == UserInfo.NO_PROFILE_GROUP_ID)) {
1891 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1892 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001893 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001894 }
1895 }
1896 userVersion = 6;
1897 }
1898
Pavel Grafov6a40f092016-10-25 15:46:51 +01001899 if (userVersion < 7) {
1900 // Previously only one user could enforce global restrictions, now it is per-user.
1901 synchronized (mRestrictionsLock) {
1902 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1903 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1904 mDevicePolicyGlobalUserRestrictions.put(
1905 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1906 }
1907 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1908 // it from local to global bundle for all users who set it.
1909 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1910 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1911 );
1912 }
1913 userVersion = 7;
1914 }
1915
Amith Yamasani6f34b412012-10-22 18:19:27 -07001916 if (userVersion < USER_VERSION) {
1917 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1918 + USER_VERSION);
1919 } else {
1920 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001921
1922 if (originalVersion < mUserVersion) {
1923 writeUserListLP();
1924 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001925 }
1926 }
1927
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001928 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001929 int flags = UserInfo.FLAG_INITIALIZED;
1930 // In split system user mode, the admin and primary flags are assigned to the first human
1931 // user.
1932 if (!UserManager.isSplitSystemUser()) {
1933 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1934 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001935 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001936 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001937 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001938 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001939 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001940
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001941 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001942 try {
1943 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1944 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1945 for (String userRestriction : defaultFirstUserRestrictions) {
1946 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1947 restrictions.putBoolean(userRestriction, true);
1948 }
1949 }
1950 } catch (Resources.NotFoundException e) {
1951 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1952 }
1953
Pavel Grafov6a40f092016-10-25 15:46:51 +01001954 if (!restrictions.isEmpty()) {
1955 synchronized (mRestrictionsLock) {
1956 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1957 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001958 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001959
Fyodor Kupolov82402752015-10-28 14:54:51 -07001960 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001961 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001962
Amith Yamasani12747872015-12-07 14:19:49 -08001963 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001964 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001965 }
1966
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001967 private String getOwnerName() {
1968 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1969 }
1970
Amith Yamasani12747872015-12-07 14:19:49 -08001971 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001972 if (DBG) {
1973 debug("scheduleWriteUser");
1974 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001975 // No need to wrap it within a lock -- worst case, we'll just post the same message
1976 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001977 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1978 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001979 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1980 }
1981 }
1982
Amith Yamasani12747872015-12-07 14:19:49 -08001983 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001984 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001985 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001986 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001987 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001988 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001989 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001990 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001991 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001992 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001993 userFile.finishWrite(fos);
1994 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001995 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001996 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001997 }
1998 }
1999
2000 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002001 * Writes the user file in this format:
2002 *
2003 * <user flags="20039023" id="0">
2004 * <name>Primary</name>
2005 * </user>
2006 */
2007 @VisibleForTesting
2008 void writeUserLP(UserData userData, OutputStream os)
2009 throws IOException, XmlPullParserException {
2010 // XmlSerializer serializer = XmlUtils.serializerInstance();
2011 final XmlSerializer serializer = new FastXmlSerializer();
2012 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2013 serializer.startDocument(null, true);
2014 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2015
2016 final UserInfo userInfo = userData.info;
2017 serializer.startTag(null, TAG_USER);
2018 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2019 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2020 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2021 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2022 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2023 Long.toString(userInfo.lastLoggedInTime));
2024 if (userInfo.lastLoggedInFingerprint != null) {
2025 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2026 userInfo.lastLoggedInFingerprint);
2027 }
2028 if (userInfo.iconPath != null) {
2029 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2030 }
2031 if (userInfo.partial) {
2032 serializer.attribute(null, ATTR_PARTIAL, "true");
2033 }
2034 if (userInfo.guestToRemove) {
2035 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2036 }
2037 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2038 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2039 Integer.toString(userInfo.profileGroupId));
2040 }
2041 serializer.attribute(null, ATTR_PROFILE_BADGE,
2042 Integer.toString(userInfo.profileBadge));
2043 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2044 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2045 Integer.toString(userInfo.restrictedProfileParentId));
2046 }
2047 // Write seed data
2048 if (userData.persistSeedData) {
2049 if (userData.seedAccountName != null) {
2050 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2051 }
2052 if (userData.seedAccountType != null) {
2053 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2054 }
2055 }
2056 if (userInfo.name != null) {
2057 serializer.startTag(null, TAG_NAME);
2058 serializer.text(userInfo.name);
2059 serializer.endTag(null, TAG_NAME);
2060 }
2061 synchronized (mRestrictionsLock) {
2062 UserRestrictionsUtils.writeRestrictions(serializer,
2063 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2064 UserRestrictionsUtils.writeRestrictions(serializer,
2065 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2066 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002067 UserRestrictionsUtils.writeRestrictions(serializer,
2068 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2069 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002070 }
2071
2072 if (userData.account != null) {
2073 serializer.startTag(null, TAG_ACCOUNT);
2074 serializer.text(userData.account);
2075 serializer.endTag(null, TAG_ACCOUNT);
2076 }
2077
2078 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2079 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2080 userData.seedAccountOptions.saveToXml(serializer);
2081 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2082 }
2083
2084 serializer.endTag(null, TAG_USER);
2085
2086 serializer.endDocument();
2087 }
2088
2089 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002090 * Writes the user list file in this format:
2091 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002092 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002093 * <user id="0"></user>
2094 * <user id="2"></user>
2095 * </users>
2096 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002097 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002098 if (DBG) {
2099 debug("writeUserList");
2100 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002101 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002102 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002103 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002104 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002105 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2106
2107 // XmlSerializer serializer = XmlUtils.serializerInstance();
2108 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002109 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002110 serializer.startDocument(null, true);
2111 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2112
2113 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002114 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002115 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002116
Adam Lesinskieddeb492014-09-08 17:50:03 -07002117 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002118 synchronized (mGuestRestrictions) {
2119 UserRestrictionsUtils
2120 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2121 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302122 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002123 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2124 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2125 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002126 int[] userIdsToWrite;
2127 synchronized (mUsersLock) {
2128 userIdsToWrite = new int[mUsers.size()];
2129 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002130 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002131 userIdsToWrite[i] = user.id;
2132 }
2133 }
2134 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002135 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002136 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002137 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002138 }
2139
2140 serializer.endTag(null, TAG_USERS);
2141
2142 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002143 userListFile.finishWrite(fos);
2144 } catch (Exception e) {
2145 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002146 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002147 }
2148 }
2149
Amith Yamasani12747872015-12-07 14:19:49 -08002150 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002151 FileInputStream fis = null;
2152 try {
2153 AtomicFile userFile =
2154 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2155 fis = userFile.openRead();
2156 return readUserLP(id, fis);
2157 } catch (IOException ioe) {
2158 Slog.e(LOG_TAG, "Error reading user list");
2159 } catch (XmlPullParserException pe) {
2160 Slog.e(LOG_TAG, "Error reading user list");
2161 } finally {
2162 IoUtils.closeQuietly(fis);
2163 }
2164 return null;
2165 }
2166
2167 @VisibleForTesting
2168 UserData readUserLP(int id, InputStream is) throws IOException,
2169 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002170 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002171 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002172 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002173 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002174 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002175 long creationTime = 0L;
2176 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002177 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002178 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002179 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002180 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002181 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002182 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002183 boolean persistSeedData = false;
2184 String seedAccountName = null;
2185 String seedAccountType = null;
2186 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002187 Bundle baseRestrictions = null;
2188 Bundle localRestrictions = null;
2189 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002190
Kenny Guy02c89902016-11-15 19:36:38 +00002191 XmlPullParser parser = Xml.newPullParser();
2192 parser.setInput(is, StandardCharsets.UTF_8.name());
2193 int type;
2194 while ((type = parser.next()) != XmlPullParser.START_TAG
2195 && type != XmlPullParser.END_DOCUMENT) {
2196 // Skip
2197 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002198
Kenny Guy02c89902016-11-15 19:36:38 +00002199 if (type != XmlPullParser.START_TAG) {
2200 Slog.e(LOG_TAG, "Unable to read user " + id);
2201 return null;
2202 }
2203
2204 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2205 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2206 if (storedId != id) {
2207 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002208 return null;
2209 }
Kenny Guy02c89902016-11-15 19:36:38 +00002210 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2211 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2212 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2213 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2214 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2215 lastLoggedInFingerprint = parser.getAttributeValue(null,
2216 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2217 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2218 UserInfo.NO_PROFILE_GROUP_ID);
2219 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2220 restrictedProfileParentId = readIntAttribute(parser,
2221 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2222 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2223 if ("true".equals(valueString)) {
2224 partial = true;
2225 }
2226 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2227 if ("true".equals(valueString)) {
2228 guestToRemove = true;
2229 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002230
Kenny Guy02c89902016-11-15 19:36:38 +00002231 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2232 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2233 if (seedAccountName != null || seedAccountType != null) {
2234 persistSeedData = true;
2235 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002236
Kenny Guy02c89902016-11-15 19:36:38 +00002237 int outerDepth = parser.getDepth();
2238 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2239 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2240 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2241 continue;
2242 }
2243 String tag = parser.getName();
2244 if (TAG_NAME.equals(tag)) {
2245 type = parser.next();
2246 if (type == XmlPullParser.TEXT) {
2247 name = parser.getText();
2248 }
2249 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002250 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002251 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002252 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2253 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2254 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002255 } else if (TAG_ACCOUNT.equals(tag)) {
2256 type = parser.next();
2257 if (type == XmlPullParser.TEXT) {
2258 account = parser.getText();
2259 }
2260 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2261 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002262 persistSeedData = true;
2263 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002264 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002265 }
Kenny Guy02c89902016-11-15 19:36:38 +00002266
2267 // Create the UserInfo object that gets passed around
2268 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2269 userInfo.serialNumber = serialNumber;
2270 userInfo.creationTime = creationTime;
2271 userInfo.lastLoggedInTime = lastLoggedInTime;
2272 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2273 userInfo.partial = partial;
2274 userInfo.guestToRemove = guestToRemove;
2275 userInfo.profileGroupId = profileGroupId;
2276 userInfo.profileBadge = profileBadge;
2277 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2278
2279 // Create the UserData object that's internal to this class
2280 UserData userData = new UserData();
2281 userData.info = userInfo;
2282 userData.account = account;
2283 userData.seedAccountName = seedAccountName;
2284 userData.seedAccountType = seedAccountType;
2285 userData.persistSeedData = persistSeedData;
2286 userData.seedAccountOptions = seedAccountOptions;
2287
2288 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002289 if (baseRestrictions != null) {
2290 mBaseUserRestrictions.put(id, baseRestrictions);
2291 }
2292 if (localRestrictions != null) {
2293 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2294 }
2295 if (globalRestrictions != null) {
2296 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2297 }
Kenny Guy02c89902016-11-15 19:36:38 +00002298 }
2299 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002300 }
2301
Amith Yamasani920ace02012-09-20 22:15:37 -07002302 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2303 String valueString = parser.getAttributeValue(null, attr);
2304 if (valueString == null) return defaultValue;
2305 try {
2306 return Integer.parseInt(valueString);
2307 } catch (NumberFormatException nfe) {
2308 return defaultValue;
2309 }
2310 }
2311
2312 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2313 String valueString = parser.getAttributeValue(null, attr);
2314 if (valueString == null) return defaultValue;
2315 try {
2316 return Long.parseLong(valueString);
2317 } catch (NumberFormatException nfe) {
2318 return defaultValue;
2319 }
2320 }
2321
Amith Yamasanib82add22013-07-09 11:24:44 -07002322 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002323 * Removes the app restrictions file for a specific package and user id, if it exists.
2324 */
2325 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2326 synchronized (mPackagesLock) {
2327 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002328 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002329 if (resFile.exists()) {
2330 resFile.delete();
2331 }
2332 }
2333 }
2334
Kenny Guya52dc3e2014-02-11 15:33:14 +00002335 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002336 public UserInfo createProfileForUser(String name, int flags, int userId,
2337 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002338 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002339 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002340 }
2341
Amith Yamasani258848d2012-08-10 17:06:33 -07002342 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002343 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2344 String[] disallowedPackages) {
2345 checkManageOrCreateUsersPermission(flags);
2346 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2347 }
2348
2349 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002350 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2351 checkManageOrCreateUsersPermission("Only the system can remove users");
2352 return removeUserUnchecked(userHandle);
2353 }
2354
2355 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002356 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002357 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002358 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002359 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002360
Jessica Hummelbe81c802014-04-22 15:49:22 +01002361 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002362 return createUserInternal(name, flags, parentId, null);
2363 }
2364
2365 private UserInfo createUserInternal(String name, int flags, int parentId,
2366 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002367 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2368 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2369 : UserManager.DISALLOW_ADD_USER;
2370 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2371 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002372 return null;
2373 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002374 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2375 }
2376
2377 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2378 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002379 DeviceStorageMonitorInternal dsm = LocalServices
2380 .getService(DeviceStorageMonitorInternal.class);
2381 if (dsm.isMemoryLow()) {
2382 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2383 return null;
2384 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002385 if (ActivityManager.isLowRamDeviceStatic()) {
2386 return null;
2387 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002388 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002389 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002390 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002391 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002392 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002393 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002394 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002395 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002396 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002397 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002398 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002399 if (parentId != UserHandle.USER_NULL) {
2400 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002401 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002402 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002403 if (parent == null) return null;
2404 }
2405 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2406 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2407 return null;
2408 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002409 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2410 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002411 // been reached, cannot add a user.
2412 return null;
2413 }
2414 // If we're adding a guest and there already exists one, bail.
2415 if (isGuest && findCurrentGuestUser() != null) {
2416 return null;
2417 }
2418 // In legacy mode, restricted profile's parent can only be the owner user
2419 if (isRestricted && !UserManager.isSplitSystemUser()
2420 && (parentId != UserHandle.USER_SYSTEM)) {
2421 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2422 return null;
2423 }
2424 if (isRestricted && UserManager.isSplitSystemUser()) {
2425 if (parent == null) {
2426 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2427 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002428 return null;
2429 }
Amith Yamasani12747872015-12-07 14:19:49 -08002430 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002431 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2432 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002433 return null;
2434 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002435 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002436 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2437 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002438 Log.e(LOG_TAG,
2439 "Ephemeral users are supported on split-system-user systems only.");
2440 return null;
2441 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002442 // In split system user mode, we assign the first human user the primary flag.
2443 // And if there is no device owner, we also assign the admin flag to primary user.
2444 if (UserManager.isSplitSystemUser()
2445 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2446 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002447 synchronized (mUsersLock) {
2448 if (!mIsDeviceManaged) {
2449 flags |= UserInfo.FLAG_ADMIN;
2450 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002451 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002452 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002453
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002454 userId = getNextAvailableId();
2455 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002456 boolean ephemeralGuests = Resources.getSystem()
2457 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002458
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002459 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002460 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2461 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2462 || (parent != null && parent.info.isEphemeral())) {
2463 flags |= UserInfo.FLAG_EPHEMERAL;
2464 }
2465
2466 userInfo = new UserInfo(userId, name, null, flags);
2467 userInfo.serialNumber = mNextSerialNumber++;
2468 long now = System.currentTimeMillis();
2469 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2470 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002471 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002472 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2473 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2474 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002475 userData = new UserData();
2476 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002477 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002478 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002479 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002480 writeUserListLP();
2481 if (parent != null) {
2482 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002483 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2484 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002485 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002486 }
Amith Yamasani12747872015-12-07 14:19:49 -08002487 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002488 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002489 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2490 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002491 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002492 }
Amith Yamasani12747872015-12-07 14:19:49 -08002493 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002494 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002495 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002496 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002497 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002498 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002499 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002500 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002501 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002502 userInfo.partial = false;
2503 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002504 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002505 }
2506 updateUserIds();
2507 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002508 if (isGuest) {
2509 synchronized (mGuestRestrictions) {
2510 restrictions.putAll(mGuestRestrictions);
2511 }
2512 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002513 synchronized (mRestrictionsLock) {
2514 mBaseUserRestrictions.append(userId, restrictions);
2515 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002516 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002517 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2518 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2519 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2520 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002521 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002522 } finally {
2523 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002524 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002525 return userInfo;
2526 }
2527
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002528 @VisibleForTesting
2529 UserData putUserInfo(UserInfo userInfo) {
2530 final UserData userData = new UserData();
2531 userData.info = userInfo;
2532 synchronized (mUsers) {
2533 mUsers.put(userInfo.id, userData);
2534 }
2535 return userData;
2536 }
2537
2538 @VisibleForTesting
2539 void removeUserInfo(int userId) {
2540 synchronized (mUsers) {
2541 mUsers.remove(userId);
2542 }
2543 }
2544
Amith Yamasani0b285492011-04-14 17:35:23 -07002545 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002546 * @hide
2547 */
Amith Yamasani12747872015-12-07 14:19:49 -08002548 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002549 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002550 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002551 final UserInfo user = createProfileForUser(
2552 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002553 if (user == null) {
2554 return null;
2555 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002556 long identity = Binder.clearCallingIdentity();
2557 try {
2558 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2559 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2560 // the putIntForUser() will fail.
2561 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2562 android.provider.Settings.Secure.LOCATION_MODE,
2563 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2564 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2565 } finally {
2566 Binder.restoreCallingIdentity(identity);
2567 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002568 return user;
2569 }
2570
2571 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002572 * Find the current guest user. If the Guest user is partial,
2573 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002574 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002575 private UserInfo findCurrentGuestUser() {
2576 synchronized (mUsersLock) {
2577 final int size = mUsers.size();
2578 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002579 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002580 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2581 return user;
2582 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002583 }
2584 }
2585 return null;
2586 }
2587
2588 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002589 * Mark this guest user for deletion to allow us to create another guest
2590 * and switch to that user before actually removing this guest.
2591 * @param userHandle the userid of the current guest
2592 * @return whether the user could be marked for deletion
2593 */
Amith Yamasani12747872015-12-07 14:19:49 -08002594 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002595 public boolean markGuestForDeletion(int userHandle) {
2596 checkManageUsersPermission("Only the system can remove users");
2597 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2598 UserManager.DISALLOW_REMOVE_USER, false)) {
2599 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2600 return false;
2601 }
2602
2603 long ident = Binder.clearCallingIdentity();
2604 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002605 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002606 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002607 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002608 userData = mUsers.get(userHandle);
2609 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002610 return false;
2611 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002612 }
Amith Yamasani12747872015-12-07 14:19:49 -08002613 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002614 return false;
2615 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002616 // We set this to a guest user that is to be removed. This is a temporary state
2617 // where we are allowed to add new Guest users, even if this one is still not
2618 // removed. This user will still show up in getUserInfo() calls.
2619 // If we don't get around to removing this Guest user, it will be purged on next
2620 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002621 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002622 // Mark it as disabled, so that it isn't returned any more when
2623 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002624 userData.info.flags |= UserInfo.FLAG_DISABLED;
2625 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002626 }
2627 } finally {
2628 Binder.restoreCallingIdentity(ident);
2629 }
2630 return true;
2631 }
2632
2633 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002634 * Removes a user and all data directories created for that user. This method should be called
2635 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002636 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002637 */
Amith Yamasani12747872015-12-07 14:19:49 -08002638 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002639 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002640 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002641 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002642
2643 final boolean isManagedProfile;
2644 synchronized (mUsersLock) {
2645 UserInfo userInfo = getUserInfoLU(userHandle);
2646 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2647 }
2648 String restriction = isManagedProfile
2649 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2650 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2651 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002652 return false;
2653 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002654 return removeUserUnchecked(userHandle);
2655 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002656
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002657 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002658 long ident = Binder.clearCallingIdentity();
2659 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002660 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002661 int currentUser = ActivityManager.getCurrentUser();
2662 if (currentUser == userHandle) {
2663 Log.w(LOG_TAG, "Current user cannot be removed");
2664 return false;
2665 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002666 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002667 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002668 userData = mUsers.get(userHandle);
2669 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002670 return false;
2671 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002672
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002673 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002674 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002675
Kenny Guyee58b4f2014-05-23 15:19:53 +01002676 try {
2677 mAppOpsService.removeUser(userHandle);
2678 } catch (RemoteException e) {
2679 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2680 }
2681 // Set this to a partially created user, so that the user will be purged
2682 // on next startup, in case the runtime stops now before stopping and
2683 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002684 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002685 // Mark it as disabled, so that it isn't returned any more when
2686 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002687 userData.info.flags |= UserInfo.FLAG_DISABLED;
2688 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002689 }
2690
Amith Yamasani12747872015-12-07 14:19:49 -08002691 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2692 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002693 // Send broadcast to notify system that the user removed was a
2694 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002695 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002696 }
2697
2698 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2699 int res;
2700 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002701 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002702 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002703 @Override
2704 public void userStopped(int userId) {
2705 finishRemoveUser(userId);
2706 }
2707 @Override
2708 public void userStopAborted(int userId) {
2709 }
2710 });
2711 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002712 return false;
2713 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002714 return res == ActivityManager.USER_OP_SUCCESS;
2715 } finally {
2716 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002717 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002718 }
2719
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002720 @VisibleForTesting
2721 void addRemovingUserIdLocked(int userId) {
2722 // We remember deleted user IDs to prevent them from being
2723 // reused during the current boot; they can still be reused
2724 // after a reboot or recycling of userIds.
2725 mRemovingUserIds.put(userId, true);
2726 mRecentlyRemovedIds.add(userId);
2727 // Keep LRU queue of recently removed IDs for recycling
2728 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2729 mRecentlyRemovedIds.removeFirst();
2730 }
2731 }
2732
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002733 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002734 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002735 // Let other services shutdown any activity and clean up their state before completely
2736 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002737 long ident = Binder.clearCallingIdentity();
2738 try {
2739 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2740 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002741 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2742 android.Manifest.permission.MANAGE_USERS,
2743
2744 new BroadcastReceiver() {
2745 @Override
2746 public void onReceive(Context context, Intent intent) {
2747 if (DBG) {
2748 Slog.i(LOG_TAG,
2749 "USER_REMOVED broadcast sent, cleaning up user data "
2750 + userHandle);
2751 }
2752 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002753 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002754 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002755 // Clean up any ActivityManager state
2756 LocalServices.getService(ActivityManagerInternal.class)
2757 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002758 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002759 }
2760 }.start();
2761 }
2762 },
2763
2764 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002765 } finally {
2766 Binder.restoreCallingIdentity(ident);
2767 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002768 }
2769
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002770 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002771 try {
2772 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2773 } catch (IllegalStateException e) {
2774 // This may be simply because the user was partially created.
2775 Slog.i(LOG_TAG,
2776 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2777 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002778
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002779 // Cleanup gatekeeper secure user id
2780 try {
2781 final IGateKeeperService gk = GateKeeper.getService();
2782 if (gk != null) {
2783 gk.clearSecureUserId(userHandle);
2784 }
2785 } catch (Exception ex) {
2786 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2787 }
2788
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002789 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002790 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002791
2792 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002793 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002794 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2795
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002796 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002797 synchronized (mUsersLock) {
2798 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002799 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002800 }
2801 synchronized (mUserStates) {
2802 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002803 }
2804 synchronized (mRestrictionsLock) {
2805 mBaseUserRestrictions.remove(userHandle);
2806 mAppliedUserRestrictions.remove(userHandle);
2807 mCachedEffectiveUserRestrictions.remove(userHandle);
2808 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002809 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2810 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2811 applyUserRestrictionsForAllUsersLR();
2812 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002813 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002814 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002815 synchronized (mPackagesLock) {
2816 writeUserListLP();
2817 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002818 // Remove user file
2819 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2820 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002821 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002822 if (RELEASE_DELETED_USER_ID) {
2823 synchronized (mUsers) {
2824 mRemovingUserIds.delete(userHandle);
2825 }
2826 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002827 }
2828
Kenny Guyf8d3a232014-05-15 16:09:52 +01002829 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002830 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002831 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2832 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002833 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002834 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002835 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002836 }
2837
Amith Yamasani2a003292012-08-14 18:25:45 -07002838 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002839 public Bundle getApplicationRestrictions(String packageName) {
2840 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2841 }
2842
2843 @Override
2844 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002845 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002846 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002847 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002848 }
2849 synchronized (mPackagesLock) {
2850 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002851 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002852 }
2853 }
2854
2855 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002856 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002857 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002858 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002859 if (restrictions != null) {
2860 restrictions.setDefusable(true);
2861 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002862 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002863 if (restrictions == null || restrictions.isEmpty()) {
2864 cleanAppRestrictionsForPackage(packageName, userId);
2865 } else {
2866 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002867 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002868 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002869 }
Robin Lee66e5d962014-04-09 16:44:21 +01002870
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002871 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2872 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2873 changeIntent.setPackage(packageName);
2874 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2875 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002876 }
2877
2878 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002879 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002880 try {
2881 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002882 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002883 } catch (NameNotFoundException nnfe) {
2884 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002885 } finally {
2886 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002887 }
2888 }
2889
Fyodor Kupolov82402752015-10-28 14:54:51 -07002890 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002891 AtomicFile restrictionsFile =
2892 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2893 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002894 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002895 }
2896
2897 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002898 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002899 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002900 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002901 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002902 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002903 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002904
2905 FileInputStream fis = null;
2906 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002907 fis = restrictionsFile.openRead();
2908 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002909 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002910 XmlUtils.nextElement(parser);
2911 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002912 Slog.e(LOG_TAG, "Unable to read restrictions file "
2913 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002914 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002915 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002916 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2917 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002918 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002919 } catch (IOException|XmlPullParserException e) {
2920 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002921 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002922 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002923 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002924 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002925 }
2926
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002927 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2928 XmlPullParser parser) throws XmlPullParserException, IOException {
2929 int type = parser.getEventType();
2930 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2931 String key = parser.getAttributeValue(null, ATTR_KEY);
2932 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2933 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2934 if (multiple != null) {
2935 values.clear();
2936 int count = Integer.parseInt(multiple);
2937 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2938 if (type == XmlPullParser.START_TAG
2939 && parser.getName().equals(TAG_VALUE)) {
2940 values.add(parser.nextText().trim());
2941 count--;
2942 }
2943 }
2944 String [] valueStrings = new String[values.size()];
2945 values.toArray(valueStrings);
2946 restrictions.putStringArray(key, valueStrings);
2947 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2948 restrictions.putBundle(key, readBundleEntry(parser, values));
2949 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2950 final int outerDepth = parser.getDepth();
2951 ArrayList<Bundle> bundleList = new ArrayList<>();
2952 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2953 Bundle childBundle = readBundleEntry(parser, values);
2954 bundleList.add(childBundle);
2955 }
2956 restrictions.putParcelableArray(key,
2957 bundleList.toArray(new Bundle[bundleList.size()]));
2958 } else {
2959 String value = parser.nextText().trim();
2960 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2961 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2962 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2963 restrictions.putInt(key, Integer.parseInt(value));
2964 } else {
2965 restrictions.putString(key, value);
2966 }
2967 }
2968 }
2969 }
2970
2971 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2972 throws IOException, XmlPullParserException {
2973 Bundle childBundle = new Bundle();
2974 final int outerDepth = parser.getDepth();
2975 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2976 readEntry(childBundle, values, parser);
2977 }
2978 return childBundle;
2979 }
2980
Fyodor Kupolov82402752015-10-28 14:54:51 -07002981 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002982 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002983 AtomicFile restrictionsFile = new AtomicFile(
2984 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002985 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002986 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002987 }
2988
2989 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002990 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002991 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002992 try {
2993 fos = restrictionsFile.startWrite();
2994 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2995
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002996 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002997 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002998 serializer.startDocument(null, true);
2999 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3000
3001 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003002 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003003 serializer.endTag(null, TAG_RESTRICTIONS);
3004
3005 serializer.endDocument();
3006 restrictionsFile.finishWrite(fos);
3007 } catch (Exception e) {
3008 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003009 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3010 }
3011 }
3012
3013 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3014 throws IOException {
3015 for (String key : restrictions.keySet()) {
3016 Object value = restrictions.get(key);
3017 serializer.startTag(null, TAG_ENTRY);
3018 serializer.attribute(null, ATTR_KEY, key);
3019
3020 if (value instanceof Boolean) {
3021 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3022 serializer.text(value.toString());
3023 } else if (value instanceof Integer) {
3024 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3025 serializer.text(value.toString());
3026 } else if (value == null || value instanceof String) {
3027 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3028 serializer.text(value != null ? (String) value : "");
3029 } else if (value instanceof Bundle) {
3030 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3031 writeBundle((Bundle) value, serializer);
3032 } else if (value instanceof Parcelable[]) {
3033 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3034 Parcelable[] array = (Parcelable[]) value;
3035 for (Parcelable parcelable : array) {
3036 if (!(parcelable instanceof Bundle)) {
3037 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3038 }
3039 serializer.startTag(null, TAG_ENTRY);
3040 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3041 writeBundle((Bundle) parcelable, serializer);
3042 serializer.endTag(null, TAG_ENTRY);
3043 }
3044 } else {
3045 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3046 String[] values = (String[]) value;
3047 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3048 for (String choice : values) {
3049 serializer.startTag(null, TAG_VALUE);
3050 serializer.text(choice != null ? choice : "");
3051 serializer.endTag(null, TAG_VALUE);
3052 }
3053 }
3054 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003055 }
3056 }
3057
3058 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003059 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003060 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003061 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003062 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003063 }
3064 }
3065
3066 @Override
3067 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003068 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003069 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003070 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003071 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003072 }
3073 // Not found
3074 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003075 }
3076 }
3077
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003078 @Override
3079 public long getUserCreationTime(int userHandle) {
3080 int callingUserId = UserHandle.getCallingUserId();
3081 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003082 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003083 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003084 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003085 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003086 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003087 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003088 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003089 }
3090 }
3091 }
3092 if (userInfo == null) {
3093 throw new SecurityException("userHandle can only be the calling user or a managed "
3094 + "profile associated with this user");
3095 }
3096 return userInfo.creationTime;
3097 }
3098
Amith Yamasani0b285492011-04-14 17:35:23 -07003099 /**
3100 * Caches the list of user ids in an array, adjusting the array size when necessary.
3101 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003102 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003103 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003104 synchronized (mUsersLock) {
3105 final int userSize = mUsers.size();
3106 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003107 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003108 num++;
3109 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003110 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003111 final int[] newUsers = new int[num];
3112 int n = 0;
3113 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003114 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003115 newUsers[n++] = mUsers.keyAt(i);
3116 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003117 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003118 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003119 }
3120 }
3121
3122 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003123 * Called right before a user is started. This gives us a chance to prepare
3124 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003125 */
3126 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003127 UserInfo userInfo = getUserInfo(userId);
3128 if (userInfo == null) {
3129 return;
3130 }
3131 final int userSerial = userInfo.serialNumber;
3132 // Migrate only if build fingerprints mismatch
3133 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003134 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003135 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003136
3137 if (userId != UserHandle.USER_SYSTEM) {
3138 synchronized (mRestrictionsLock) {
3139 applyUserRestrictionsLR(userId);
3140 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003141 }
3142 }
3143
3144 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003145 * Called right before a user is unlocked. This gives us a chance to prepare
3146 * app storage.
3147 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003148 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003149 UserInfo userInfo = getUserInfo(userId);
3150 if (userInfo == null) {
3151 return;
3152 }
3153 final int userSerial = userInfo.serialNumber;
3154 // Migrate only if build fingerprints mismatch
3155 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003156 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003157 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003158 }
3159
3160 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003161 * Examine all users present on given mounted volume, and destroy data
3162 * belonging to users that are no longer valid, or whose user ID has been
3163 * recycled.
3164 */
3165 void reconcileUsers(String volumeUuid) {
3166 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3167 }
3168
3169 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003170 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003171 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003172 * @param userId the user that was just foregrounded
3173 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003174 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003175 UserData userData = getUserDataNoChecks(userId);
3176 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003177 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3178 return;
3179 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003180
3181 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003182 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003183 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003184 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003185 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3186 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003187 }
3188
3189 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003190 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003191 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003192 @VisibleForTesting
3193 int getNextAvailableId() {
3194 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003195 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003196 nextId = scanNextAvailableIdLocked();
3197 if (nextId >= 0) {
3198 return nextId;
3199 }
3200 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3201 // except most recently removed
3202 if (mRemovingUserIds.size() > 0) {
3203 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3204 mRemovingUserIds.clear();
3205 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3206 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003207 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003208 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003209 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003210 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003211 if (nextId < 0) {
3212 throw new IllegalStateException("No user id available!");
3213 }
3214 return nextId;
3215 }
3216
3217 private int scanNextAvailableIdLocked() {
3218 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3219 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3220 return i;
3221 }
3222 }
3223 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003224 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003225
Amith Yamasanifc95e702013-09-26 13:20:17 -07003226 private String packageToRestrictionsFileName(String packageName) {
3227 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3228 }
3229
Amith Yamasani920ace02012-09-20 22:15:37 -07003230 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003231 public void setSeedAccountData(int userId, String accountName, String accountType,
3232 PersistableBundle accountOptions, boolean persist) {
3233 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3234 synchronized (mPackagesLock) {
3235 final UserData userData;
3236 synchronized (mUsersLock) {
3237 userData = getUserDataLU(userId);
3238 if (userData == null) {
3239 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3240 return;
3241 }
3242 userData.seedAccountName = accountName;
3243 userData.seedAccountType = accountType;
3244 userData.seedAccountOptions = accountOptions;
3245 userData.persistSeedData = persist;
3246 }
3247 if (persist) {
3248 writeUserLP(userData);
3249 }
3250 }
3251 }
3252
3253 @Override
3254 public String getSeedAccountName() throws RemoteException {
3255 checkManageUsersPermission("Cannot get seed account information");
3256 synchronized (mUsersLock) {
3257 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3258 return userData.seedAccountName;
3259 }
3260 }
3261
3262 @Override
3263 public String getSeedAccountType() throws RemoteException {
3264 checkManageUsersPermission("Cannot get seed account information");
3265 synchronized (mUsersLock) {
3266 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3267 return userData.seedAccountType;
3268 }
3269 }
3270
3271 @Override
3272 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3273 checkManageUsersPermission("Cannot get seed account information");
3274 synchronized (mUsersLock) {
3275 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3276 return userData.seedAccountOptions;
3277 }
3278 }
3279
3280 @Override
3281 public void clearSeedAccountData() throws RemoteException {
3282 checkManageUsersPermission("Cannot clear seed account information");
3283 synchronized (mPackagesLock) {
3284 UserData userData;
3285 synchronized (mUsersLock) {
3286 userData = getUserDataLU(UserHandle.getCallingUserId());
3287 if (userData == null) return;
3288 userData.clearSeedAccountData();
3289 }
3290 writeUserLP(userData);
3291 }
3292 }
3293
3294 @Override
3295 public boolean someUserHasSeedAccount(String accountName, String accountType)
3296 throws RemoteException {
3297 checkManageUsersPermission("Cannot check seed account information");
3298 synchronized (mUsersLock) {
3299 final int userSize = mUsers.size();
3300 for (int i = 0; i < userSize; i++) {
3301 final UserData data = mUsers.valueAt(i);
3302 if (data.info.isInitialized()) continue;
3303 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3304 continue;
3305 }
3306 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3307 continue;
3308 }
3309 return true;
3310 }
3311 }
3312 return false;
3313 }
3314
3315 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003316 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003317 FileDescriptor err, String[] args, ShellCallback callback,
3318 ResultReceiver resultReceiver) {
3319 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003320 }
3321
3322 int onShellCommand(Shell shell, String cmd) {
3323 if (cmd == null) {
3324 return shell.handleDefaultCommands(cmd);
3325 }
3326
3327 final PrintWriter pw = shell.getOutPrintWriter();
3328 try {
3329 switch(cmd) {
3330 case "list":
3331 return runList(pw);
3332 }
3333 } catch (RemoteException e) {
3334 pw.println("Remote exception: " + e);
3335 }
3336 return -1;
3337 }
3338
3339 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003340 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003341 final List<UserInfo> users = getUsers(false);
3342 if (users == null) {
3343 pw.println("Error: couldn't get users");
3344 return 1;
3345 } else {
3346 pw.println("Users:");
3347 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003348 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003349 pw.println("\t" + users.get(i).toString() + running);
3350 }
3351 return 0;
3352 }
3353 }
3354
3355 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003356 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3357 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3358 != PackageManager.PERMISSION_GRANTED) {
3359 pw.println("Permission Denial: can't dump UserManager from from pid="
3360 + Binder.getCallingPid()
3361 + ", uid=" + Binder.getCallingUid()
3362 + " without permission "
3363 + android.Manifest.permission.DUMP);
3364 return;
3365 }
3366
3367 long now = System.currentTimeMillis();
3368 StringBuilder sb = new StringBuilder();
3369 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003370 synchronized (mUsersLock) {
3371 pw.println("Users:");
3372 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003373 UserData userData = mUsers.valueAt(i);
3374 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003375 continue;
3376 }
Amith Yamasani12747872015-12-07 14:19:49 -08003377 UserInfo userInfo = userData.info;
3378 final int userId = userInfo.id;
3379 pw.print(" "); pw.print(userInfo);
3380 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003381 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003382 pw.print(" <removing> ");
3383 }
Amith Yamasani12747872015-12-07 14:19:49 -08003384 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003385 pw.print(" <partial>");
3386 }
3387 pw.println();
3388 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003389 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003390 pw.println("<unknown>");
3391 } else {
3392 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003393 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003394 sb.append(" ago");
3395 pw.println(sb);
3396 }
3397 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003398 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003399 pw.println("<unknown>");
3400 } else {
3401 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003402 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003403 sb.append(" ago");
3404 pw.println(sb);
3405 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003406 pw.print(" Last logged in fingerprint: ");
3407 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003408 pw.print(" Has profile owner: ");
3409 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003410 pw.println(" Restrictions:");
3411 synchronized (mRestrictionsLock) {
3412 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003413 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003414 pw.println(" Device policy global restrictions:");
3415 UserRestrictionsUtils.dumpRestrictions(
3416 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003417 pw.println(" Device policy local restrictions:");
3418 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003419 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003420 pw.println(" Effective restrictions:");
3421 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003422 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003423 }
Amith Yamasani12747872015-12-07 14:19:49 -08003424
3425 if (userData.account != null) {
3426 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003427 pw.println();
3428 }
Amith Yamasani12747872015-12-07 14:19:49 -08003429
3430 if (userData.seedAccountName != null) {
3431 pw.print(" Seed account name: " + userData.seedAccountName);
3432 pw.println();
3433 if (userData.seedAccountType != null) {
3434 pw.print(" account type: " + userData.seedAccountType);
3435 pw.println();
3436 }
3437 if (userData.seedAccountOptions != null) {
3438 pw.print(" account options exist");
3439 pw.println();
3440 }
3441 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003442 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003443 }
Amith Yamasani12747872015-12-07 14:19:49 -08003444 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003445 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003446 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003447 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003448 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003449 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003450 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003451 synchronized (mUsersLock) {
3452 pw.println();
3453 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003454 if (mRemovingUserIds.size() > 0) {
3455 pw.println();
3456 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3457 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003458 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003459 synchronized (mUserStates) {
3460 pw.println(" Started users state: " + mUserStates);
3461 }
Amith Yamasani12747872015-12-07 14:19:49 -08003462 // Dump some capabilities
3463 pw.println();
3464 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3465 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003466 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3467 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003468 }
3469 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003470
3471 final class MainHandler extends Handler {
3472
3473 @Override
3474 public void handleMessage(Message msg) {
3475 switch (msg.what) {
3476 case WRITE_USER_MSG:
3477 removeMessages(WRITE_USER_MSG, msg.obj);
3478 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003479 int userId = ((UserData) msg.obj).info.id;
3480 UserData userData = getUserDataNoChecks(userId);
3481 if (userData != null) {
3482 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003483 }
3484 }
3485 }
3486 }
3487 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003488
3489 /**
3490 * @param userId
3491 * @return whether the user has been initialized yet
3492 */
3493 boolean isInitialized(int userId) {
3494 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3495 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003496
3497 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003498 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003499 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3500 boolean isDeviceOwner, int cameraRestrictionScope) {
3501 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3502 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003503 }
3504
3505 @Override
3506 public Bundle getBaseUserRestrictions(int userId) {
3507 synchronized (mRestrictionsLock) {
3508 return mBaseUserRestrictions.get(userId);
3509 }
3510 }
3511
3512 @Override
3513 public void setBaseUserRestrictionsByDpmsForMigration(
3514 int userId, Bundle baseRestrictions) {
3515 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003516 if (updateRestrictionsIfNeededLR(
3517 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3518 invalidateEffectiveUserRestrictionsLR(userId);
3519 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003520 }
3521
Amith Yamasani12747872015-12-07 14:19:49 -08003522 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003523 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003524 if (userData != null) {
3525 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003526 } else {
3527 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3528 }
3529 }
3530 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003531
3532 @Override
3533 public boolean getUserRestriction(int userId, String key) {
3534 return getUserRestrictions(userId).getBoolean(key);
3535 }
3536
3537 @Override
3538 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3539 synchronized (mUserRestrictionsListeners) {
3540 mUserRestrictionsListeners.add(listener);
3541 }
3542 }
3543
3544 @Override
3545 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3546 synchronized (mUserRestrictionsListeners) {
3547 mUserRestrictionsListeners.remove(listener);
3548 }
3549 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003550
3551 @Override
3552 public void setDeviceManaged(boolean isManaged) {
3553 synchronized (mUsersLock) {
3554 mIsDeviceManaged = isManaged;
3555 }
3556 }
3557
3558 @Override
3559 public void setUserManaged(int userId, boolean isManaged) {
3560 synchronized (mUsersLock) {
3561 mIsUserManaged.put(userId, isManaged);
3562 }
3563 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003564
3565 @Override
3566 public void setUserIcon(int userId, Bitmap bitmap) {
3567 long ident = Binder.clearCallingIdentity();
3568 try {
3569 synchronized (mPackagesLock) {
3570 UserData userData = getUserDataNoChecks(userId);
3571 if (userData == null || userData.info.partial) {
3572 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3573 return;
3574 }
3575 writeBitmapLP(userData.info, bitmap);
3576 writeUserLP(userData);
3577 }
3578 sendUserInfoChangedBroadcast(userId);
3579 } finally {
3580 Binder.restoreCallingIdentity(ident);
3581 }
3582 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003583
3584 @Override
3585 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3586 synchronized (mUsersLock) {
3587 mForceEphemeralUsers = forceEphemeralUsers;
3588 }
3589 }
3590
3591 @Override
3592 public void removeAllUsers() {
3593 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3594 // Remove the non-system users straight away.
3595 removeNonSystemUsers();
3596 } else {
3597 // Switch to the system user first and then remove the other users.
3598 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3599 @Override
3600 public void onReceive(Context context, Intent intent) {
3601 int userId =
3602 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3603 if (userId != UserHandle.USER_SYSTEM) {
3604 return;
3605 }
3606 mContext.unregisterReceiver(this);
3607 removeNonSystemUsers();
3608 }
3609 };
3610 IntentFilter userSwitchedFilter = new IntentFilter();
3611 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3612 mContext.registerReceiver(
3613 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3614
3615 // Switch to the system user.
3616 ActivityManager am =
3617 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3618 am.switchUser(UserHandle.USER_SYSTEM);
3619 }
3620 }
phweisse9c44062016-02-10 12:57:38 +01003621
3622 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003623 public void onEphemeralUserStop(int userId) {
3624 synchronized (mUsersLock) {
3625 UserInfo userInfo = getUserInfoLU(userId);
3626 if (userInfo != null && userInfo.isEphemeral()) {
3627 // Do not allow switching back to the ephemeral user again as the user is going
3628 // to be deleted.
3629 userInfo.flags |= UserInfo.FLAG_DISABLED;
3630 if (userInfo.isGuest()) {
3631 // Indicate that the guest will be deleted after it stops.
3632 userInfo.guestToRemove = true;
3633 }
3634 }
3635 }
3636 }
3637
3638 @Override
phweisse9c44062016-02-10 12:57:38 +01003639 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003640 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003641 // Keep this in sync with UserManager.createUser
3642 if (user != null && !user.isAdmin()) {
3643 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3644 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3645 }
3646 return user;
3647 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003648
3649 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003650 public boolean removeUserEvenWhenDisallowed(int userId) {
3651 return removeUserUnchecked(userId);
3652 }
3653
3654 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003655 public boolean isUserRunning(int userId) {
3656 synchronized (mUserStates) {
3657 return mUserStates.get(userId, -1) >= 0;
3658 }
3659 }
3660
3661 @Override
3662 public void setUserState(int userId, int userState) {
3663 synchronized (mUserStates) {
3664 mUserStates.put(userId, userState);
3665 }
3666 }
3667
3668 @Override
3669 public void removeUserState(int userId) {
3670 synchronized (mUserStates) {
3671 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003672 }
3673 }
3674
3675 @Override
3676 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003677 synchronized (mUserStates) {
3678 int state = mUserStates.get(userId, -1);
3679 return (state == UserState.STATE_RUNNING_UNLOCKING)
3680 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003681 }
3682 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003683
3684 @Override
3685 public boolean isUserUnlocked(int userId) {
3686 synchronized (mUserStates) {
3687 int state = mUserStates.get(userId, -1);
3688 return state == UserState.STATE_RUNNING_UNLOCKED;
3689 }
3690 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003691 }
3692
3693 /* Remove all the users except of the system one. */
3694 private void removeNonSystemUsers() {
3695 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3696 synchronized (mUsersLock) {
3697 final int userSize = mUsers.size();
3698 for (int i = 0; i < userSize; i++) {
3699 UserInfo ui = mUsers.valueAt(i).info;
3700 if (ui.id != UserHandle.USER_SYSTEM) {
3701 usersToRemove.add(ui);
3702 }
3703 }
3704 }
3705 for (UserInfo ui: usersToRemove) {
3706 removeUser(ui.id);
3707 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003708 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003709
3710 private class Shell extends ShellCommand {
3711 @Override
3712 public int onCommand(String cmd) {
3713 return onShellCommand(this, cmd);
3714 }
3715
3716 @Override
3717 public void onHelp() {
3718 final PrintWriter pw = getOutPrintWriter();
3719 pw.println("User manager (user) commands:");
3720 pw.println(" help");
3721 pw.println(" Print this help text.");
3722 pw.println("");
3723 pw.println(" list");
3724 pw.println(" Prints all users on the system.");
3725 }
3726 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003727
3728 private static void debug(String message) {
3729 Log.d(LOG_TAG, message +
3730 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3731 }
Kenny Guy02c89902016-11-15 19:36:38 +00003732
3733 @VisibleForTesting
3734 static int getMaxManagedProfiles() {
3735 // Allow overriding max managed profiles on debuggable builds for testing
3736 // of multiple profiles.
3737 if (!Build.IS_DEBUGGABLE) {
3738 return MAX_MANAGED_PROFILES;
3739 } else {
3740 return SystemProperties.getInt("persist.sys.max_profiles",
3741 MAX_MANAGED_PROFILES);
3742 }
3743 }
3744
3745 @VisibleForTesting
3746 int getFreeProfileBadgeLU(int parentUserId) {
3747 int maxManagedProfiles = getMaxManagedProfiles();
3748 boolean[] usedBadges = new boolean[maxManagedProfiles];
3749 final int userSize = mUsers.size();
3750 for (int i = 0; i < userSize; i++) {
3751 UserInfo ui = mUsers.valueAt(i).info;
3752 // Check which badge indexes are already used by this profile group.
3753 if (ui.isManagedProfile()
3754 && ui.profileGroupId == parentUserId
3755 && !mRemovingUserIds.get(ui.id)
3756 && ui.profileBadge < maxManagedProfiles) {
3757 usedBadges[ui.profileBadge] = true;
3758 }
3759 }
3760 for (int i = 0; i < maxManagedProfiles; i++) {
3761 if (!usedBadges[i]) {
3762 return i;
3763 }
3764 }
3765 return 0;
3766 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003767
3768 /**
3769 * Checks if the given user has a managed profile associated with it.
3770 * @param userId The parent user
3771 * @return
3772 */
3773 boolean hasManagedProfile(int userId) {
3774 synchronized (mUsersLock) {
3775 UserInfo userInfo = getUserInfoLU(userId);
3776 final int userSize = mUsers.size();
3777 for (int i = 0; i < userSize; i++) {
3778 UserInfo profile = mUsers.valueAt(i).info;
3779 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3780 return true;
3781 }
3782 }
3783 return false;
3784 }
3785 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003786}