blob: 9d2d9e5bf5d29e13ec6349909e874ea40887bae9 [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;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070097import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000098import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070099import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100100
Jeff Sharkey47f71082016-02-01 17:03:54 -0700101import libcore.io.IoUtils;
102import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800103
104import org.xmlpull.v1.XmlPullParser;
105import org.xmlpull.v1.XmlPullParserException;
106import org.xmlpull.v1.XmlSerializer;
107
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108import java.io.BufferedOutputStream;
109import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700110import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.FileOutputStream;
Kenny Guy02c89902016-11-15 19:36:38 +0000114import java.io.InputStream;
115import java.io.OutputStream;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700117import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100118import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100120import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700121import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122import java.util.List;
123
Makoto Onuki068c54a2015-10-13 14:34:03 -0700124/**
125 * Service for {@link UserManager}.
126 *
127 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700128 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800129 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700130 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
131 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
132 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700133 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700134public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700135
Amith Yamasani2a003292012-08-14 18:25:45 -0700136 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800137 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800138 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700139 // Can be used for manual testing of id recycling
140 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700141
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800143 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700145 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700147 private static final String ATTR_CREATION_TIME = "created";
148 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600149 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700150 private static final String ATTR_SERIAL_NO = "serialNumber";
151 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700152 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700153 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700154 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100155 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000156 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700157 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800158 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
159 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530160 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700162 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800163 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800164 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100165 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
166 "device_policy_global_restrictions";
167 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100168 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100169 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800170 private static final String TAG_ENTRY = "entry";
171 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800172 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800173 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700174 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800175 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700176
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700177 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
178 private static final String ATTR_TYPE_STRING = "s";
179 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700180 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700181 private static final String ATTR_TYPE_BUNDLE = "B";
182 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700183
Amith Yamasani0b285492011-04-14 17:35:23 -0700184 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700186 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100187 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800189 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700190 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800191
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700192 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
193 UserInfo.FLAG_MANAGED_PROFILE
194 | UserInfo.FLAG_EPHEMERAL
195 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700196 | UserInfo.FLAG_GUEST
197 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700198
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700199 @VisibleForTesting
200 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700201 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700202 @VisibleForTesting
203 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
204
205 // Max size of the queue of recently removed users
206 @VisibleForTesting
207 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700208
Pavel Grafov6a40f092016-10-25 15:46:51 +0100209 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700210
Amith Yamasani920ace02012-09-20 22:15:37 -0700211 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
212
Nicolas Prevotb8186812015-08-06 15:00:03 +0100213 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700214 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000215 @VisibleForTesting
216 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700217
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800218 static final int WRITE_USER_MSG = 1;
219 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530220
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700221 private static final String XATTR_SERIAL = "user.serial";
222
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800223 // Tron counters
224 private static final String TRON_GUEST_CREATED = "users_guest_created";
225 private static final String TRON_USER_CREATED = "users_user_created";
226
Dianne Hackborn4428e172012-08-24 17:43:05 -0700227 private final Context mContext;
228 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700230 // Short-term lock for internal state, when interaction/sync with PM is not required
231 private final Object mUsersLock = new Object();
232 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) {
436 this(context, 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 Kupolove80085d2015-11-06 18:21:39 -0800444 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
445 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700446 }
447
Dianne Hackborn4428e172012-08-24 17:43:05 -0700448 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800449 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700450 mContext = context;
451 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700452 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800453 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800454 synchronized (mPackagesLock) {
455 mUsersDir = new File(dataDir, USER_INFO_DIR);
456 mUsersDir.mkdirs();
457 // Make zeroth user directory, for services to migrate their files to that location
458 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
459 userZeroDir.mkdirs();
460 FileUtils.setPermissions(mUsersDir.toString(),
461 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
462 -1, -1);
463 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
464 initDefaultGuestRestrictions();
465 readUserListLP();
466 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700467 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700468 mLocalService = new LocalService();
469 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000470 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000471 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700472 }
473
474 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400475 mAppOpsService = IAppOpsService.Stub.asInterface(
476 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800477
478 synchronized (mRestrictionsLock) {
479 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400480 }
Samuel Tand9453b82016-03-14 15:57:02 -0700481
482 UserInfo currentGuestUser = findCurrentGuestUser();
483 if (currentGuestUser != null && !hasUserRestriction(
484 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
485 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
486 // to it, in case this guest was created in a previous version where this
487 // user restriction was not a default guest restriction.
488 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
489 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700490
Ricky Waib1dd80b2016-06-07 18:00:55 +0100491 mContext.registerReceiver(mDisableQuietModeCallback,
492 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
493 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700494 }
495
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700496 void cleanupPartialUsers() {
497 // Prune out any partially created, partially removed and ephemeral users.
498 ArrayList<UserInfo> partials = new ArrayList<>();
499 synchronized (mUsersLock) {
500 final int userSize = mUsers.size();
501 for (int i = 0; i < userSize; i++) {
502 UserInfo ui = mUsers.valueAt(i).info;
503 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
504 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700505 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700506 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700507 }
508 }
509 }
510 final int partialsSize = partials.size();
511 for (int i = 0; i < partialsSize; i++) {
512 UserInfo ui = partials.get(i);
513 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
514 + " (name=" + ui.name + ")");
515 removeUserState(ui.id);
516 }
517 }
518
Amith Yamasani258848d2012-08-10 17:06:33 -0700519 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800520 public String getUserAccount(int userId) {
521 checkManageUserAndAcrossUsersFullPermission("get user account");
522 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800523 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800524 }
525 }
526
527 @Override
528 public void setUserAccount(int userId, String accountName) {
529 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800530 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800531 synchronized (mPackagesLock) {
532 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800533 final UserData userData = mUsers.get(userId);
534 if (userData == null) {
535 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
536 return;
537 }
538 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800539 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800540 userData.account = accountName;
541 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800542 }
543 }
544
545 if (userToUpdate != null) {
546 writeUserLP(userToUpdate);
547 }
548 }
549 }
550
551 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700552 public UserInfo getPrimaryUser() {
553 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700554 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700555 final int userSize = mUsers.size();
556 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800557 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800558 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700559 return ui;
560 }
561 }
562 }
563 return null;
564 }
565
566 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700567 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700568 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700569 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700570 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700571 final int userSize = mUsers.size();
572 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800573 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700574 if (ui.partial) {
575 continue;
576 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800577 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700578 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700579 }
Amith Yamasani13593602012-03-22 16:16:17 -0700580 }
581 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700582 }
Amith Yamasani13593602012-03-22 16:16:17 -0700583 }
584
Amith Yamasani258848d2012-08-10 17:06:33 -0700585 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100586 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700587 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800588 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700589 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700590 } else {
591 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800592 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700593 final long ident = Binder.clearCallingIdentity();
594 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700595 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700596 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100597 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700598 } finally {
599 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000600 }
601 }
602
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700603 @Override
604 public int[] getProfileIds(int userId, boolean enabledOnly) {
605 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700606 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700607 }
608 final long ident = Binder.clearCallingIdentity();
609 try {
610 synchronized (mUsersLock) {
611 return getProfileIdsLU(userId, enabledOnly).toArray();
612 }
613 } finally {
614 Binder.restoreCallingIdentity(ident);
615 }
616 }
617
Amith Yamasanibe465322014-04-24 13:45:17 -0700618 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700619 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700620 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
621 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
622 for (int i = 0; i < profileIds.size(); i++) {
623 int profileId = profileIds.get(i);
624 UserInfo userInfo = mUsers.get(profileId).info;
625 // If full info is not required - clear PII data to prevent 3P apps from reading it
626 if (!fullInfo) {
627 userInfo = new UserInfo(userInfo);
628 userInfo.name = null;
629 userInfo.iconPath = null;
630 } else {
631 userInfo = userWithName(userInfo);
632 }
633 users.add(userInfo);
634 }
635 return users;
636 }
637
638 /**
639 * Assume permissions already checked and caller's identity cleared
640 */
641 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700642 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700643 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700644 if (user == null) {
645 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700646 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700647 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700648 final int userSize = mUsers.size();
649 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800650 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700651 if (!isProfileOf(user, profile)) {
652 continue;
653 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100654 if (enabledOnly && !profile.isEnabled()) {
655 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700656 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700657 if (mRemovingUserIds.get(profile.id)) {
658 continue;
659 }
Tony Mak80189cd2016-04-05 17:21:42 +0100660 if (profile.partial) {
661 continue;
662 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700663 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700664 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700665 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700666 }
667
Jessica Hummelbe81c802014-04-22 15:49:22 +0100668 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700669 public int getCredentialOwnerProfile(int userHandle) {
670 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000671 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700672 synchronized (mUsersLock) {
673 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700674 if (profileParent != null) {
675 return profileParent.id;
676 }
677 }
678 }
679
680 return userHandle;
681 }
682
683 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700684 public boolean isSameProfileGroup(int userId, int otherUserId) {
685 if (userId == otherUserId) return true;
686 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700687 return isSameProfileGroupNoChecks(userId, otherUserId);
688 }
689
690 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700691 synchronized (mUsersLock) {
692 UserInfo userInfo = getUserInfoLU(userId);
693 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
694 return false;
695 }
696 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
697 if (otherUserInfo == null
698 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
699 return false;
700 }
701 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700702 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700703 }
704
705 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100706 public UserInfo getProfileParent(int userHandle) {
707 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700708 synchronized (mUsersLock) {
709 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700710 }
711 }
712
Fyodor Kupolov82402752015-10-28 14:54:51 -0700713 private UserInfo getProfileParentLU(int userHandle) {
714 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700715 if (profile == null) {
716 return null;
717 }
718 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800719 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700720 return null;
721 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700722 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100723 }
724 }
725
Fyodor Kupolov82402752015-10-28 14:54:51 -0700726 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100727 return user.id == profile.id ||
728 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
729 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000730 }
731
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000732 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000733 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100734 Intent intent = new Intent();
735 if (inQuietMode) {
736 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
737 } else {
738 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
739 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000740 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
741 intent.putExtra(Intent.EXTRA_USER, profileHandle);
742 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000743 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000744 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000745 }
746
747 @Override
748 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
749 checkManageUsersPermission("silence profile");
750 boolean changed = false;
751 UserInfo profile, parent;
752 synchronized (mPackagesLock) {
753 synchronized (mUsersLock) {
754 profile = getUserInfoLU(userHandle);
755 parent = getProfileParentLU(userHandle);
756
757 }
758 if (profile == null || !profile.isManagedProfile()) {
759 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
760 }
761 if (profile.isQuietModeEnabled() != enableQuietMode) {
762 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800763 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000764 changed = true;
765 }
766 }
767 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000768 long identity = Binder.clearCallingIdentity();
769 try {
770 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800771 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100772 LocalServices.getService(ActivityManagerInternal.class)
773 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000774 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800775 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000776 }
777 } catch (RemoteException e) {
778 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
779 } finally {
780 Binder.restoreCallingIdentity(identity);
781 }
782
783 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
784 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000785 }
786 }
787
788 @Override
789 public boolean isQuietModeEnabled(int userHandle) {
790 synchronized (mPackagesLock) {
791 UserInfo info;
792 synchronized (mUsersLock) {
793 info = getUserInfoLU(userHandle);
794 }
795 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000796 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000797 }
798 return info.isQuietModeEnabled();
799 }
800 }
801
Kenny Guya52dc3e2014-02-11 15:33:14 +0000802 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100803 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100804 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600805 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100806 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100807 // if the user is already unlocked, no need to show a profile challenge
808 setQuietModeEnabled(userHandle, false);
809 return true;
810 }
811
812 long identity = Binder.clearCallingIdentity();
813 try {
814 // otherwise, we show a profile challenge to trigger decryption of the user
815 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
816 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100817 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
818 // lock, confirm screenlock page will know and show personal challenge, and unlock
819 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100820 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
821 userHandle);
822 if (unlockIntent == null) {
823 return false;
824 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100825 final Intent callBackIntent = new Intent(
826 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100827 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100828 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100829 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100830 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
831 callBackIntent.setPackage(mContext.getPackageName());
832 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
834 mContext,
835 0,
836 callBackIntent,
837 PendingIntent.FLAG_CANCEL_CURRENT |
838 PendingIntent.FLAG_ONE_SHOT |
839 PendingIntent.FLAG_IMMUTABLE);
840 // After unlocking the challenge, it will disable quiet mode and run the original
841 // intentSender
842 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100843 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
844 mContext.startActivity(unlockIntent);
845 } finally {
846 Binder.restoreCallingIdentity(identity);
847 }
848 return false;
849 }
850
851 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100852 public void setUserEnabled(int userId) {
853 checkManageUsersPermission("enable user");
854 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700855 UserInfo info;
856 synchronized (mUsersLock) {
857 info = getUserInfoLU(userId);
858 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100859 if (info != null && !info.isEnabled()) {
860 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800861 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100862 }
863 }
864 }
865
Andrew Scull85a63bc2016-10-24 13:47:47 +0100866 /**
867 * Evicts a user's CE key by stopping and restarting the user.
868 *
869 * The key is evicted automatically by the user controller when the user has stopped.
870 */
871 @Override
872 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
873 checkManageUsersPermission("evict CE key");
874 final IActivityManager am = ActivityManagerNative.getDefault();
875 final long identity = Binder.clearCallingIdentity();
876 try {
877 am.restartUserInBackground(userId);
878 } catch (RemoteException re) {
879 throw re.rethrowAsRuntimeException();
880 } finally {
881 Binder.restoreCallingIdentity(identity);
882 }
883 }
884
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100885 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700886 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700887 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000888 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700889 return userWithName(getUserInfoLU(userId));
890 }
891 }
892
893 /**
894 * Returns a UserInfo object with the name filled in, for Owner, or the original
895 * if the name is already set.
896 */
897 private UserInfo userWithName(UserInfo orig) {
898 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
899 UserInfo withName = new UserInfo(orig);
900 withName.name = getOwnerName();
901 return withName;
902 } else {
903 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000904 }
905 }
906
907 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000908 public int getManagedProfileBadge(@UserIdInt int userId) {
909 int callingUserId = UserHandle.getCallingUserId();
910 if (callingUserId != userId && !hasManageUsersPermission()) {
911 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
912 throw new SecurityException(
913 "You need MANAGE_USERS permission to: check if specified user a " +
914 "managed profile outside your profile group");
915 }
916 }
917 synchronized (mUsersLock) {
918 UserInfo userInfo = getUserInfoLU(userId);
919 return userInfo != null ? userInfo.profileBadge : 0;
920 }
921 }
922
923 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000924 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000925 int callingUserId = UserHandle.getCallingUserId();
926 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700927 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700928 throw new SecurityException(
929 "You need MANAGE_USERS permission to: check if specified user a " +
930 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000931 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000932 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700933 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700934 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000935 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700936 }
937 }
938
Amith Yamasani71e6c692013-03-24 17:39:28 -0700939 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700940 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800941 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700942 return mLocalService.isUserUnlockingOrUnlocked(userId);
943 }
944
945 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800946 public boolean isUserUnlocked(int userId) {
947 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
948 return mLocalService.isUserUnlockingOrUnlocked(userId);
949 }
950
951 @Override
952 public boolean isUserRunning(int userId) {
953 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
954 return mLocalService.isUserRunning(userId);
955 }
956
957 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
958 int callingUserId = UserHandle.getCallingUserId();
959 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
960 hasManageUsersPermission()) {
961 return;
962 }
963 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
964 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
965 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
966 + "to: check " + name);
967 }
968 }
969
970 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700971 public boolean isDemoUser(int userId) {
972 int callingUserId = UserHandle.getCallingUserId();
973 if (callingUserId != userId && !hasManageUsersPermission()) {
974 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
975 + " is a demo user");
976 }
977 synchronized (mUsersLock) {
978 UserInfo userInfo = getUserInfoLU(userId);
979 return userInfo != null && userInfo.isDemo();
980 }
981 }
982
983 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700984 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700985 synchronized (mUsersLock) {
986 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700987 }
988 }
989
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700990 @Override
991 public boolean canHaveRestrictedProfile(int userId) {
992 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700993 synchronized (mUsersLock) {
994 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700995 if (userInfo == null || !userInfo.canHaveProfile()) {
996 return false;
997 }
998 if (!userInfo.isAdmin()) {
999 return false;
1000 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001001 // restricted profile can be created if there is no DO set and the admin user has no PO;
1002 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001003 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001004 }
1005
Amith Yamasani195263742012-08-21 15:40:12 -07001006 /*
1007 * Should be locked on mUsers before calling this.
1008 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001009 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001010 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001011 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001012 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001013 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1014 return null;
1015 }
Amith Yamasani12747872015-12-07 14:19:49 -08001016 return userData != null ? userData.info : null;
1017 }
1018
1019 private UserData getUserDataLU(int userId) {
1020 final UserData userData = mUsers.get(userId);
1021 // If it is partial and not in the process of being removed, return as unknown user.
1022 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1023 return null;
1024 }
1025 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001026 }
1027
Fyodor Kupolov82402752015-10-28 14:54:51 -07001028 /**
1029 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1030 * <p>No permissions checking or any addition checks are made</p>
1031 */
1032 private UserInfo getUserInfoNoChecks(int userId) {
1033 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001034 final UserData userData = mUsers.get(userId);
1035 return userData != null ? userData.info : null;
1036 }
1037 }
1038
1039 /**
1040 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1041 * <p>No permissions checking or any addition checks are made</p>
1042 */
1043 private UserData getUserDataNoChecks(int userId) {
1044 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001045 return mUsers.get(userId);
1046 }
1047 }
1048
Amith Yamasani236b2b52015-08-18 14:32:14 -07001049 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001050 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001051 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001052 }
1053
Amith Yamasani258848d2012-08-10 17:06:33 -07001054 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001055 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001056 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001057 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001058 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001059 UserData userData = getUserDataNoChecks(userId);
1060 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001061 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1062 return;
1063 }
Amith Yamasani12747872015-12-07 14:19:49 -08001064 if (name != null && !name.equals(userData.info.name)) {
1065 userData.info.name = name;
1066 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001067 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001068 }
1069 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001070 if (changed) {
1071 sendUserInfoChangedBroadcast(userId);
1072 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001073 }
1074
Amith Yamasani258848d2012-08-10 17:06:33 -07001075 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001076 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001077 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001078 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1079 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1080 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001081 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001082 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001083 }
1084
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001085
1086
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001087 private void sendUserInfoChangedBroadcast(int userId) {
1088 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1089 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1090 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001091 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001092 }
1093
Amith Yamasani258848d2012-08-10 17:06:33 -07001094 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001095 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001096 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001097 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001098 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1099 if (targetUserInfo == null || targetUserInfo.partial) {
1100 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001101 return null;
1102 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001103
1104 final int callingUserId = UserHandle.getCallingUserId();
1105 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1106 final int targetGroupId = targetUserInfo.profileGroupId;
1107 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1108 && callingGroupId == targetGroupId);
1109 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001110 checkManageUsersPermission("get the icon of a user who is not related");
1111 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001112
1113 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001114 return null;
1115 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001116 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001117 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001118
1119 try {
1120 return ParcelFileDescriptor.open(
1121 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1122 } catch (FileNotFoundException e) {
1123 Log.e(LOG_TAG, "Couldn't find icon file", e);
1124 }
1125 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001126 }
1127
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001128 public void makeInitialized(int userId) {
1129 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001130 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001131 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001132 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001133 userData = mUsers.get(userId);
1134 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001135 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001136 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001137 }
Amith Yamasani12747872015-12-07 14:19:49 -08001138 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1139 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001140 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001141 }
1142 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001143 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001144 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001145 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001146 }
1147
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001148 /**
1149 * If default guest restrictions haven't been initialized yet, add the basic
1150 * restrictions.
1151 */
1152 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001153 synchronized (mGuestRestrictions) {
1154 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001155 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001156 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001157 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1158 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1159 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001160 }
1161 }
1162
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001163 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301164 public Bundle getDefaultGuestRestrictions() {
1165 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001166 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301167 return new Bundle(mGuestRestrictions);
1168 }
1169 }
1170
1171 @Override
1172 public void setDefaultGuestRestrictions(Bundle restrictions) {
1173 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001174 synchronized (mGuestRestrictions) {
1175 mGuestRestrictions.clear();
1176 mGuestRestrictions.putAll(restrictions);
1177 }
1178 synchronized (mPackagesLock) {
1179 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301180 }
1181 }
1182
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001183 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001184 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001185 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001186 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1187 boolean isDeviceOwner, int cameraRestrictionScope) {
1188 final Bundle global = new Bundle();
1189 final Bundle local = new Bundle();
1190
1191 // Sort restrictions into local and global ensuring they don't overlap.
1192 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1193 cameraRestrictionScope, global, local);
1194
1195 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001196 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001197 // Update global and local restrictions if they were changed.
1198 globalChanged = updateRestrictionsIfNeededLR(
1199 userId, global, mDevicePolicyGlobalUserRestrictions);
1200 localChanged = updateRestrictionsIfNeededLR(
1201 userId, local, mDevicePolicyLocalUserRestrictions);
1202
1203 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001204 // Remember the global restriction owner userId to be able to make a distinction
1205 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001206 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001207 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001208 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001209 // When profile owner sets restrictions it passes null global bundle and we
1210 // reset global restriction owner userId.
1211 // This means this user used to have DO, but now the DO is gone and the user
1212 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001213 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001214 }
1215 }
1216 }
1217 if (DBG) {
1218 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1219 + " global=" + global + (globalChanged ? " (changed)" : "")
1220 + " local=" + local + (localChanged ? " (changed)" : "")
1221 );
1222 }
1223 // Don't call them within the mRestrictionsLock.
1224 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001225 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001226 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001227 }
1228 }
1229
1230 synchronized (mRestrictionsLock) {
1231 if (globalChanged) {
1232 applyUserRestrictionsForAllUsersLR();
1233 } else if (localChanged) {
1234 applyUserRestrictionsLR(userId);
1235 }
1236 }
1237 }
1238
Pavel Grafov6a40f092016-10-25 15:46:51 +01001239 /**
1240 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1241 * empty, record is removed from the array.
1242 * @return whether restrictions bundle is different from the old one.
1243 */
1244 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1245 SparseArray<Bundle> restrictionsArray) {
1246 final boolean changed =
1247 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1248 if (changed) {
1249 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1250 restrictionsArray.put(userId, restrictions);
1251 } else {
1252 restrictionsArray.delete(userId);
1253 }
1254 }
1255 return changed;
1256 }
1257
Makoto Onuki068c54a2015-10-13 14:34:03 -07001258 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001259 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001260 final Bundle baseRestrictions =
1261 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001262 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001263 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001264
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001265 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1266 // Common case first.
1267 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001268 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001269 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1270 UserRestrictionsUtils.merge(effective, global);
1271 UserRestrictionsUtils.merge(effective, local);
1272
Makoto Onuki068c54a2015-10-13 14:34:03 -07001273 return effective;
1274 }
1275
1276 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001277 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001278 if (DBG) {
1279 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1280 }
1281 mCachedEffectiveUserRestrictions.remove(userId);
1282 }
1283
1284 private Bundle getEffectiveUserRestrictions(int userId) {
1285 synchronized (mRestrictionsLock) {
1286 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1287 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001288 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001289 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1290 }
1291 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001292 }
1293 }
1294
Makoto Onuki068c54a2015-10-13 14:34:03 -07001295 /** @return a specific user restriction that's in effect currently. */
1296 @Override
1297 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001298 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1299 return false;
1300 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001301 Bundle restrictions = getEffectiveUserRestrictions(userId);
1302 return restrictions != null && restrictions.getBoolean(restrictionKey);
1303 }
1304
1305 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001306 * @hide
1307 *
1308 * Returns who set a user restriction on a user.
1309 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1310 * @param restrictionKey the string key representing the restriction
1311 * @param userId the id of the user for whom to retrieve the restrictions.
1312 * @return The source of user restriction. Any combination of
1313 * {@link UserManager#RESTRICTION_NOT_SET},
1314 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1315 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1316 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1317 */
1318 @Override
1319 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001320 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1321 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001322 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001323 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1324 result |= enforcingUsers.get(i).getUserRestrictionSource();
1325 }
1326 return result;
1327 }
1328
1329 @Override
1330 public List<EnforcingUser> getUserRestrictionSources(
1331 String restrictionKey, @UserIdInt int userId) {
1332 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001333
1334 // Shortcut for the most common case
1335 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001336 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001337 }
1338
Pavel Grafov6a40f092016-10-25 15:46:51 +01001339 final List<EnforcingUser> result = new ArrayList<>();
1340
1341 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001342 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001343 result.add(new EnforcingUser(
1344 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001345 }
1346
Pavel Grafov6a40f092016-10-25 15:46:51 +01001347 synchronized (mRestrictionsLock) {
1348 // Check if it is set by profile owner.
1349 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1350 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1351 result.add(getEnforcingUserLocked(userId));
1352 }
1353
1354 // Iterate over all users who enforce global restrictions.
1355 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1356 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1357 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1358 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1359 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001360 }
1361 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001362 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001363 return result;
1364 }
1365
Pavel Grafov6a40f092016-10-25 15:46:51 +01001366 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1367 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1368 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1369 return new EnforcingUser(userId, source);
1370 }
1371
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001372 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001373 * @return UserRestrictions that are in effect currently. This always returns a new
1374 * {@link Bundle}.
1375 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001376 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001377 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001378 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001379 }
1380
1381 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001382 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1383 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001384 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1385 return false;
1386 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001387 synchronized (mRestrictionsLock) {
1388 Bundle bundle = mBaseUserRestrictions.get(userId);
1389 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1390 }
1391 }
1392
1393 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001394 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001395 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001396 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1397 return;
1398 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001399 synchronized (mRestrictionsLock) {
1400 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1401 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001402 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1403 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001404 newRestrictions.putBoolean(key, value);
1405
Fyodor Kupolov82402752015-10-28 14:54:51 -07001406 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001407 }
1408 }
1409
Makoto Onuki068c54a2015-10-13 14:34:03 -07001410 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001411 * Optionally updating user restrictions, calculate the effective user restrictions and also
1412 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001413 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001414 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001415 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001416 * @param userId target user ID.
1417 */
1418 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001419 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001420 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001421 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1422 mAppliedUserRestrictions.get(userId));
1423
1424 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001425 if (newBaseRestrictions != null) {
1426 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001427 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1428
Pavel Grafov6a40f092016-10-25 15:46:51 +01001429 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001430 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001431 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001432
Pavel Grafov6a40f092016-10-25 15:46:51 +01001433 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001434 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001435 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001436 }
1437
Fyodor Kupolov82402752015-10-28 14:54:51 -07001438 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001439
Makoto Onuki759a7632015-10-28 16:43:10 -07001440 mCachedEffectiveUserRestrictions.put(userId, effective);
1441
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001442 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001443 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001444 debug("Applying user restrictions: userId=" + userId
1445 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001446 }
1447
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001449 mHandler.post(new Runnable() {
1450 @Override
1451 public void run() {
1452 try {
1453 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1454 } catch (RemoteException e) {
1455 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1456 }
1457 }
1458 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001459 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001460
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001461 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001462
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001463 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001464 }
1465
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001466 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001467 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001468 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1469 // actually, but we still need some kind of synchronization otherwise we might end up
1470 // calling listeners out-of-order, thus "LR".
1471
1472 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1473 return;
1474 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001475
1476 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1477 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1478
1479 mHandler.post(new Runnable() {
1480 @Override
1481 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001482 UserRestrictionsUtils.applyUserRestrictions(
1483 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001484
Makoto Onukid45a4a22015-11-02 17:17:38 -08001485 final UserRestrictionsListener[] listeners;
1486 synchronized (mUserRestrictionsListeners) {
1487 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1488 mUserRestrictionsListeners.toArray(listeners);
1489 }
1490 for (int i = 0; i < listeners.length; i++) {
1491 listeners[i].onUserRestrictionsChanged(userId,
1492 newRestrictionsFinal, prevRestrictionsFinal);
1493 }
1494 }
1495 });
1496 }
1497
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001498 // Package private for the inner class.
1499 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001500 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001501 }
1502
1503 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 // Package private for the inner class.
1505 void applyUserRestrictionsForAllUsersLR() {
1506 if (DBG) {
1507 debug("applyUserRestrictionsForAllUsersLR");
1508 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001509 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001510 mCachedEffectiveUserRestrictions.clear();
1511
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001512 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001513 // it on a handler.
1514 final Runnable r = new Runnable() {
1515 @Override
1516 public void run() {
1517 // Then get the list of running users.
1518 final int[] runningUsers;
1519 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001520 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001521 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001522 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001523 return;
1524 }
1525 // Then re-calculate the effective restrictions and apply, only for running users.
1526 // It's okay if a new user has started after the getRunningUserIds() call,
1527 // because we'll do the same thing (re-calculate the restrictions and apply)
1528 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001529 synchronized (mRestrictionsLock) {
1530 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001531 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001532 }
1533 }
1534 }
1535 };
1536 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001537 }
1538
Amith Yamasani258848d2012-08-10 17:06:33 -07001539 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001540 * Check if we've hit the limit of how many users can be created.
1541 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001542 private boolean isUserLimitReached() {
1543 int count;
1544 synchronized (mUsersLock) {
1545 count = getAliveUsersExcludingGuestsCountLU();
1546 }
1547 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001548 }
1549
1550 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001551 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001552 checkManageUsersPermission("check if more managed profiles can be added.");
1553 if (ActivityManager.isLowRamDeviceStatic()) {
1554 return false;
1555 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001556 if (!mContext.getPackageManager().hasSystemFeature(
1557 PackageManager.FEATURE_MANAGED_USERS)) {
1558 return false;
1559 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001560 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001561 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001562 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001563 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001564 return false;
1565 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001566 synchronized(mUsersLock) {
1567 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001568 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001569 return false;
1570 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001571 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1572 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001573 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001574 return usersCountAfterRemoving == 1
1575 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001576 }
1577 }
1578
Fyodor Kupolov82402752015-10-28 14:54:51 -07001579 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001580 int aliveUserCount = 0;
1581 final int totalUserCount = mUsers.size();
1582 // Skip over users being removed
1583 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001584 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001585 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001586 aliveUserCount++;
1587 }
1588 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001589 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001590 }
1591
1592 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001593 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001594 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1595 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1596 * permissions can make certain calls to the UserManager.
1597 *
1598 * @param message used as message if SecurityException is thrown
1599 * @throws SecurityException if the caller does not have enough privilege.
1600 */
1601 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1602 final int uid = Binder.getCallingUid();
1603 if (uid != Process.SYSTEM_UID && uid != 0
1604 && ActivityManager.checkComponentPermission(
1605 Manifest.permission.MANAGE_USERS,
1606 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1607 && ActivityManager.checkComponentPermission(
1608 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1609 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1610 throw new SecurityException(
1611 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1612 + message);
1613 }
1614 }
1615
1616 /**
1617 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001618 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001619 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001620 *
1621 * @param message used as message if SecurityException is thrown
1622 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001623 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001624 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001625 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001626 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001627 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1628 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001629 }
1630
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001631 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001632 * Enforces that only the system UID or root's UID or apps that have the
1633 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1634 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1635 * can make certain calls to the UserManager.
1636 *
1637 * @param message used as message if SecurityException is thrown
1638 * @throws SecurityException if the caller is not system or root
1639 * @see #hasManageOrCreateUsersPermission()
1640 */
1641 private static final void checkManageOrCreateUsersPermission(String message) {
1642 if (!hasManageOrCreateUsersPermission()) {
1643 throw new SecurityException(
1644 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1645 }
1646 }
1647
1648 /**
1649 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1650 * to create user/profiles other than what is allowed for
1651 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1652 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1653 */
1654 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1655 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1656 if (!hasManageOrCreateUsersPermission()) {
1657 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1658 + "permission to create an user with flags: " + creationFlags);
1659 }
1660 } else if (!hasManageUsersPermission()) {
1661 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1662 + " with flags: " + creationFlags);
1663 }
1664 }
1665
1666 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001667 * @return whether the calling UID is system UID or root's UID or the calling app has the
1668 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1669 */
1670 private static final boolean hasManageUsersPermission() {
1671 final int callingUid = Binder.getCallingUid();
1672 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1673 || callingUid == Process.ROOT_UID
1674 || ActivityManager.checkComponentPermission(
1675 android.Manifest.permission.MANAGE_USERS,
1676 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1677 }
1678
1679 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001680 * @return whether the calling UID is system UID or root's UID or the calling app has the
1681 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1682 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1683 */
1684 private static final boolean hasManageOrCreateUsersPermission() {
1685 final int callingUid = Binder.getCallingUid();
1686 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1687 || callingUid == Process.ROOT_UID
1688 || ActivityManager.checkComponentPermission(
1689 android.Manifest.permission.MANAGE_USERS,
1690 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1691 || ActivityManager.checkComponentPermission(
1692 android.Manifest.permission.CREATE_USERS,
1693 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1694 }
1695
1696 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001697 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1698 * UserManager.
1699 *
1700 * @param message used as message if SecurityException is thrown
1701 * @throws SecurityException if the caller is not system or root
1702 */
1703 private static void checkSystemOrRoot(String message) {
1704 final int uid = Binder.getCallingUid();
1705 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1706 throw new SecurityException("Only system may: " + message);
1707 }
1708 }
1709
Fyodor Kupolov82402752015-10-28 14:54:51 -07001710 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001711 try {
1712 File dir = new File(mUsersDir, Integer.toString(info.id));
1713 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001714 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001715 if (!dir.exists()) {
1716 dir.mkdir();
1717 FileUtils.setPermissions(
1718 dir.getPath(),
1719 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1720 -1, -1);
1721 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001722 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001723 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001724 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001725 info.iconPath = file.getAbsolutePath();
1726 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001727 try {
1728 os.close();
1729 } catch (IOException ioe) {
1730 // What the ... !
1731 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001732 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001733 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001734 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001735 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001736 }
1737
Amith Yamasani0b285492011-04-14 17:35:23 -07001738 /**
1739 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1740 * cache it elsewhere.
1741 * @return the array of user ids.
1742 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001743 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001744 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001745 return mUserIds;
1746 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001747 }
1748
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001749 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001750 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001751 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001752 return;
1753 }
1754 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001755 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001756 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001757 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001758 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001759 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001760 int type;
1761 while ((type = parser.next()) != XmlPullParser.START_TAG
1762 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001763 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001764 }
1765
1766 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001767 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001768 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001769 return;
1770 }
1771
Amith Yamasani2a003292012-08-14 18:25:45 -07001772 mNextSerialNumber = -1;
1773 if (parser.getName().equals(TAG_USERS)) {
1774 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1775 if (lastSerialNumber != null) {
1776 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1777 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001778 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1779 if (versionNumber != null) {
1780 mUserVersion = Integer.parseInt(versionNumber);
1781 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001782 }
1783
Pavel Grafov6a40f092016-10-25 15:46:51 +01001784 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1785 // currently), take care of it in case of upgrade.
1786 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001787
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001788 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301789 if (type == XmlPullParser.START_TAG) {
1790 final String name = parser.getName();
1791 if (name.equals(TAG_USER)) {
1792 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001793
Amith Yamasani12747872015-12-07 14:19:49 -08001794 UserData userData = readUserLP(Integer.parseInt(id));
1795
1796 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001797 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001798 mUsers.put(userData.info.id, userData);
1799 if (mNextSerialNumber < 0
1800 || mNextSerialNumber <= userData.info.id) {
1801 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001802 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301803 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001804 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301805 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001806 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1807 && type != XmlPullParser.END_TAG) {
1808 if (type == XmlPullParser.START_TAG) {
1809 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001810 synchronized (mGuestRestrictions) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001811 mGuestRestrictions.putAll(
1812 UserRestrictionsUtils.readRestrictions(parser));
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001813 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001814 }
1815 break;
1816 }
1817 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001818 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1819 // Legacy name, should only be encountered when upgrading from pre-O.
1820 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001821 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1822 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001823 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001824 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001825 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1826 // Should only happen when upgrading from pre-O (version < 7).
1827 oldDevicePolicyGlobalUserRestrictions =
1828 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001829 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001830 }
1831 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001832
Fyodor Kupolov82402752015-10-28 14:54:51 -07001833 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001834 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001835 } catch (IOException | XmlPullParserException e) {
1836 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001837 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001838 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001839 }
1840 }
1841
Amith Yamasani6f34b412012-10-22 18:19:27 -07001842 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001843 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001844 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001845 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001846 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001847 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001848 int userVersion = mUserVersion;
1849 if (userVersion < 1) {
1850 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001851 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1852 if ("Primary".equals(userData.info.name)) {
1853 userData.info.name =
1854 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1855 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001856 }
1857 userVersion = 1;
1858 }
1859
Amith Yamasanibc9625052012-11-15 14:39:18 -08001860 if (userVersion < 2) {
1861 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001862 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1863 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1864 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1865 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001866 }
1867 userVersion = 2;
1868 }
1869
Amith Yamasani350962c2013-08-06 11:18:53 -07001870
Amith Yamasani5e486f52013-08-07 11:06:44 -07001871 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001872 userVersion = 4;
1873 }
1874
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001875 if (userVersion < 5) {
1876 initDefaultGuestRestrictions();
1877 userVersion = 5;
1878 }
1879
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001880 if (userVersion < 6) {
1881 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001882 synchronized (mUsersLock) {
1883 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001884 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001885 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001886 if (!splitSystemUser && userData.info.isRestricted()
1887 && (userData.info.restrictedProfileParentId
1888 == UserInfo.NO_PROFILE_GROUP_ID)) {
1889 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1890 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001891 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001892 }
1893 }
1894 userVersion = 6;
1895 }
1896
Pavel Grafov6a40f092016-10-25 15:46:51 +01001897 if (userVersion < 7) {
1898 // Previously only one user could enforce global restrictions, now it is per-user.
1899 synchronized (mRestrictionsLock) {
1900 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1901 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1902 mDevicePolicyGlobalUserRestrictions.put(
1903 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1904 }
1905 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1906 // it from local to global bundle for all users who set it.
1907 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1908 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1909 );
1910 }
1911 userVersion = 7;
1912 }
1913
Amith Yamasani6f34b412012-10-22 18:19:27 -07001914 if (userVersion < USER_VERSION) {
1915 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1916 + USER_VERSION);
1917 } else {
1918 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001919
1920 if (originalVersion < mUserVersion) {
1921 writeUserListLP();
1922 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001923 }
1924 }
1925
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001926 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001927 int flags = UserInfo.FLAG_INITIALIZED;
1928 // In split system user mode, the admin and primary flags are assigned to the first human
1929 // user.
1930 if (!UserManager.isSplitSystemUser()) {
1931 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1932 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001933 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001934 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001935 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001936 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001937 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001938
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001939 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001940 try {
1941 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1942 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1943 for (String userRestriction : defaultFirstUserRestrictions) {
1944 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1945 restrictions.putBoolean(userRestriction, true);
1946 }
1947 }
1948 } catch (Resources.NotFoundException e) {
1949 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1950 }
1951
Pavel Grafov6a40f092016-10-25 15:46:51 +01001952 if (!restrictions.isEmpty()) {
1953 synchronized (mRestrictionsLock) {
1954 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1955 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001956 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001957
Fyodor Kupolov82402752015-10-28 14:54:51 -07001958 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001959 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001960
Amith Yamasani12747872015-12-07 14:19:49 -08001961 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001962 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001963 }
1964
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001965 private String getOwnerName() {
1966 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1967 }
1968
Amith Yamasani12747872015-12-07 14:19:49 -08001969 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001970 if (DBG) {
1971 debug("scheduleWriteUser");
1972 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001973 // No need to wrap it within a lock -- worst case, we'll just post the same message
1974 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001975 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1976 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001977 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1978 }
1979 }
1980
Amith Yamasani12747872015-12-07 14:19:49 -08001981 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001982 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001983 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001984 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001985 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001986 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001987 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001988 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001989 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001990 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001991 userFile.finishWrite(fos);
1992 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001993 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001994 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001995 }
1996 }
1997
1998 /*
Kenny Guy02c89902016-11-15 19:36:38 +00001999 * Writes the user file in this format:
2000 *
2001 * <user flags="20039023" id="0">
2002 * <name>Primary</name>
2003 * </user>
2004 */
2005 @VisibleForTesting
2006 void writeUserLP(UserData userData, OutputStream os)
2007 throws IOException, XmlPullParserException {
2008 // XmlSerializer serializer = XmlUtils.serializerInstance();
2009 final XmlSerializer serializer = new FastXmlSerializer();
2010 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2011 serializer.startDocument(null, true);
2012 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2013
2014 final UserInfo userInfo = userData.info;
2015 serializer.startTag(null, TAG_USER);
2016 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2017 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2018 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2019 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2020 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2021 Long.toString(userInfo.lastLoggedInTime));
2022 if (userInfo.lastLoggedInFingerprint != null) {
2023 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2024 userInfo.lastLoggedInFingerprint);
2025 }
2026 if (userInfo.iconPath != null) {
2027 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2028 }
2029 if (userInfo.partial) {
2030 serializer.attribute(null, ATTR_PARTIAL, "true");
2031 }
2032 if (userInfo.guestToRemove) {
2033 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2034 }
2035 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2036 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2037 Integer.toString(userInfo.profileGroupId));
2038 }
2039 serializer.attribute(null, ATTR_PROFILE_BADGE,
2040 Integer.toString(userInfo.profileBadge));
2041 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2042 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2043 Integer.toString(userInfo.restrictedProfileParentId));
2044 }
2045 // Write seed data
2046 if (userData.persistSeedData) {
2047 if (userData.seedAccountName != null) {
2048 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2049 }
2050 if (userData.seedAccountType != null) {
2051 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2052 }
2053 }
2054 if (userInfo.name != null) {
2055 serializer.startTag(null, TAG_NAME);
2056 serializer.text(userInfo.name);
2057 serializer.endTag(null, TAG_NAME);
2058 }
2059 synchronized (mRestrictionsLock) {
2060 UserRestrictionsUtils.writeRestrictions(serializer,
2061 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2062 UserRestrictionsUtils.writeRestrictions(serializer,
2063 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2064 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002065 UserRestrictionsUtils.writeRestrictions(serializer,
2066 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2067 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002068 }
2069
2070 if (userData.account != null) {
2071 serializer.startTag(null, TAG_ACCOUNT);
2072 serializer.text(userData.account);
2073 serializer.endTag(null, TAG_ACCOUNT);
2074 }
2075
2076 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2077 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2078 userData.seedAccountOptions.saveToXml(serializer);
2079 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2080 }
2081
2082 serializer.endTag(null, TAG_USER);
2083
2084 serializer.endDocument();
2085 }
2086
2087 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002088 * Writes the user list file in this format:
2089 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002090 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002091 * <user id="0"></user>
2092 * <user id="2"></user>
2093 * </users>
2094 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002095 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002096 if (DBG) {
2097 debug("writeUserList");
2098 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002099 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002100 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002101 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002102 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002103 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2104
2105 // XmlSerializer serializer = XmlUtils.serializerInstance();
2106 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002107 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002108 serializer.startDocument(null, true);
2109 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2110
2111 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002112 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002113 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002114
Adam Lesinskieddeb492014-09-08 17:50:03 -07002115 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002116 synchronized (mGuestRestrictions) {
2117 UserRestrictionsUtils
2118 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2119 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302120 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002121 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2122 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2123 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002124 int[] userIdsToWrite;
2125 synchronized (mUsersLock) {
2126 userIdsToWrite = new int[mUsers.size()];
2127 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002128 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002129 userIdsToWrite[i] = user.id;
2130 }
2131 }
2132 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002133 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002134 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002135 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002136 }
2137
2138 serializer.endTag(null, TAG_USERS);
2139
2140 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002141 userListFile.finishWrite(fos);
2142 } catch (Exception e) {
2143 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002144 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002145 }
2146 }
2147
Amith Yamasani12747872015-12-07 14:19:49 -08002148 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002149 FileInputStream fis = null;
2150 try {
2151 AtomicFile userFile =
2152 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2153 fis = userFile.openRead();
2154 return readUserLP(id, fis);
2155 } catch (IOException ioe) {
2156 Slog.e(LOG_TAG, "Error reading user list");
2157 } catch (XmlPullParserException pe) {
2158 Slog.e(LOG_TAG, "Error reading user list");
2159 } finally {
2160 IoUtils.closeQuietly(fis);
2161 }
2162 return null;
2163 }
2164
2165 @VisibleForTesting
2166 UserData readUserLP(int id, InputStream is) throws IOException,
2167 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002168 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002169 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002170 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002171 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002172 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002173 long creationTime = 0L;
2174 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002175 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002176 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002177 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002178 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002179 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002180 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002181 boolean persistSeedData = false;
2182 String seedAccountName = null;
2183 String seedAccountType = null;
2184 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002185 Bundle baseRestrictions = null;
2186 Bundle localRestrictions = null;
2187 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002188
Kenny Guy02c89902016-11-15 19:36:38 +00002189 XmlPullParser parser = Xml.newPullParser();
2190 parser.setInput(is, StandardCharsets.UTF_8.name());
2191 int type;
2192 while ((type = parser.next()) != XmlPullParser.START_TAG
2193 && type != XmlPullParser.END_DOCUMENT) {
2194 // Skip
2195 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002196
Kenny Guy02c89902016-11-15 19:36:38 +00002197 if (type != XmlPullParser.START_TAG) {
2198 Slog.e(LOG_TAG, "Unable to read user " + id);
2199 return null;
2200 }
2201
2202 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2203 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2204 if (storedId != id) {
2205 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002206 return null;
2207 }
Kenny Guy02c89902016-11-15 19:36:38 +00002208 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2209 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2210 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2211 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2212 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2213 lastLoggedInFingerprint = parser.getAttributeValue(null,
2214 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2215 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2216 UserInfo.NO_PROFILE_GROUP_ID);
2217 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2218 restrictedProfileParentId = readIntAttribute(parser,
2219 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2220 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2221 if ("true".equals(valueString)) {
2222 partial = true;
2223 }
2224 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2225 if ("true".equals(valueString)) {
2226 guestToRemove = true;
2227 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002228
Kenny Guy02c89902016-11-15 19:36:38 +00002229 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2230 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2231 if (seedAccountName != null || seedAccountType != null) {
2232 persistSeedData = true;
2233 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002234
Kenny Guy02c89902016-11-15 19:36:38 +00002235 int outerDepth = parser.getDepth();
2236 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2237 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2238 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2239 continue;
2240 }
2241 String tag = parser.getName();
2242 if (TAG_NAME.equals(tag)) {
2243 type = parser.next();
2244 if (type == XmlPullParser.TEXT) {
2245 name = parser.getText();
2246 }
2247 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002248 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002249 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002250 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2251 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2252 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002253 } else if (TAG_ACCOUNT.equals(tag)) {
2254 type = parser.next();
2255 if (type == XmlPullParser.TEXT) {
2256 account = parser.getText();
2257 }
2258 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2259 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002260 persistSeedData = true;
2261 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002262 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002263 }
Kenny Guy02c89902016-11-15 19:36:38 +00002264
2265 // Create the UserInfo object that gets passed around
2266 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2267 userInfo.serialNumber = serialNumber;
2268 userInfo.creationTime = creationTime;
2269 userInfo.lastLoggedInTime = lastLoggedInTime;
2270 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2271 userInfo.partial = partial;
2272 userInfo.guestToRemove = guestToRemove;
2273 userInfo.profileGroupId = profileGroupId;
2274 userInfo.profileBadge = profileBadge;
2275 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2276
2277 // Create the UserData object that's internal to this class
2278 UserData userData = new UserData();
2279 userData.info = userInfo;
2280 userData.account = account;
2281 userData.seedAccountName = seedAccountName;
2282 userData.seedAccountType = seedAccountType;
2283 userData.persistSeedData = persistSeedData;
2284 userData.seedAccountOptions = seedAccountOptions;
2285
2286 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002287 if (baseRestrictions != null) {
2288 mBaseUserRestrictions.put(id, baseRestrictions);
2289 }
2290 if (localRestrictions != null) {
2291 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2292 }
2293 if (globalRestrictions != null) {
2294 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2295 }
Kenny Guy02c89902016-11-15 19:36:38 +00002296 }
2297 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002298 }
2299
Amith Yamasani920ace02012-09-20 22:15:37 -07002300 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2301 String valueString = parser.getAttributeValue(null, attr);
2302 if (valueString == null) return defaultValue;
2303 try {
2304 return Integer.parseInt(valueString);
2305 } catch (NumberFormatException nfe) {
2306 return defaultValue;
2307 }
2308 }
2309
2310 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2311 String valueString = parser.getAttributeValue(null, attr);
2312 if (valueString == null) return defaultValue;
2313 try {
2314 return Long.parseLong(valueString);
2315 } catch (NumberFormatException nfe) {
2316 return defaultValue;
2317 }
2318 }
2319
Amith Yamasanib82add22013-07-09 11:24:44 -07002320 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002321 * Removes the app restrictions file for a specific package and user id, if it exists.
2322 */
2323 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2324 synchronized (mPackagesLock) {
2325 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002326 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002327 if (resFile.exists()) {
2328 resFile.delete();
2329 }
2330 }
2331 }
2332
Kenny Guya52dc3e2014-02-11 15:33:14 +00002333 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002334 public UserInfo createProfileForUser(String name, int flags, int userId,
2335 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002336 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002337 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002338 }
2339
Amith Yamasani258848d2012-08-10 17:06:33 -07002340 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002341 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2342 String[] disallowedPackages) {
2343 checkManageOrCreateUsersPermission(flags);
2344 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2345 }
2346
2347 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002348 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2349 checkManageOrCreateUsersPermission("Only the system can remove users");
2350 return removeUserUnchecked(userHandle);
2351 }
2352
2353 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002354 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002355 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002356 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002357 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002358
Jessica Hummelbe81c802014-04-22 15:49:22 +01002359 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002360 return createUserInternal(name, flags, parentId, null);
2361 }
2362
2363 private UserInfo createUserInternal(String name, int flags, int parentId,
2364 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002365 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2366 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2367 : UserManager.DISALLOW_ADD_USER;
2368 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2369 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002370 return null;
2371 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002372 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2373 }
2374
2375 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2376 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002377 DeviceStorageMonitorInternal dsm = LocalServices
2378 .getService(DeviceStorageMonitorInternal.class);
2379 if (dsm.isMemoryLow()) {
2380 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2381 return null;
2382 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002383 if (ActivityManager.isLowRamDeviceStatic()) {
2384 return null;
2385 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002386 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002387 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002388 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002389 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002390 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002391 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002392 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002393 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002394 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002395 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002396 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002397 if (parentId != UserHandle.USER_NULL) {
2398 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002399 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002400 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002401 if (parent == null) return null;
2402 }
2403 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2404 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2405 return null;
2406 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002407 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2408 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002409 // been reached, cannot add a user.
2410 return null;
2411 }
2412 // If we're adding a guest and there already exists one, bail.
2413 if (isGuest && findCurrentGuestUser() != null) {
2414 return null;
2415 }
2416 // In legacy mode, restricted profile's parent can only be the owner user
2417 if (isRestricted && !UserManager.isSplitSystemUser()
2418 && (parentId != UserHandle.USER_SYSTEM)) {
2419 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2420 return null;
2421 }
2422 if (isRestricted && UserManager.isSplitSystemUser()) {
2423 if (parent == null) {
2424 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2425 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002426 return null;
2427 }
Amith Yamasani12747872015-12-07 14:19:49 -08002428 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002429 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2430 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002431 return null;
2432 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002433 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002434 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2435 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002436 Log.e(LOG_TAG,
2437 "Ephemeral users are supported on split-system-user systems only.");
2438 return null;
2439 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002440 // In split system user mode, we assign the first human user the primary flag.
2441 // And if there is no device owner, we also assign the admin flag to primary user.
2442 if (UserManager.isSplitSystemUser()
2443 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2444 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002445 synchronized (mUsersLock) {
2446 if (!mIsDeviceManaged) {
2447 flags |= UserInfo.FLAG_ADMIN;
2448 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002449 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002450 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002451
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002452 userId = getNextAvailableId();
2453 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002454 boolean ephemeralGuests = Resources.getSystem()
2455 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002456
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002457 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002458 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2459 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2460 || (parent != null && parent.info.isEphemeral())) {
2461 flags |= UserInfo.FLAG_EPHEMERAL;
2462 }
2463
2464 userInfo = new UserInfo(userId, name, null, flags);
2465 userInfo.serialNumber = mNextSerialNumber++;
2466 long now = System.currentTimeMillis();
2467 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2468 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002469 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002470 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2471 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2472 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002473 userData = new UserData();
2474 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002475 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002476 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002477 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002478 writeUserListLP();
2479 if (parent != null) {
2480 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002481 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2482 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002483 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002484 }
Amith Yamasani12747872015-12-07 14:19:49 -08002485 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002486 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002487 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2488 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002489 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002490 }
Amith Yamasani12747872015-12-07 14:19:49 -08002491 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002492 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002493 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002494 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002495 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002496 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002497 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002498 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002499 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002500 userInfo.partial = false;
2501 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002502 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002503 }
2504 updateUserIds();
2505 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002506 if (isGuest) {
2507 synchronized (mGuestRestrictions) {
2508 restrictions.putAll(mGuestRestrictions);
2509 }
2510 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002511 synchronized (mRestrictionsLock) {
2512 mBaseUserRestrictions.append(userId, restrictions);
2513 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002514 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002515 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2516 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2517 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2518 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002519 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002520 } finally {
2521 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002522 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002523 return userInfo;
2524 }
2525
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002526 @VisibleForTesting
2527 UserData putUserInfo(UserInfo userInfo) {
2528 final UserData userData = new UserData();
2529 userData.info = userInfo;
2530 synchronized (mUsers) {
2531 mUsers.put(userInfo.id, userData);
2532 }
2533 return userData;
2534 }
2535
2536 @VisibleForTesting
2537 void removeUserInfo(int userId) {
2538 synchronized (mUsers) {
2539 mUsers.remove(userId);
2540 }
2541 }
2542
Amith Yamasani0b285492011-04-14 17:35:23 -07002543 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002544 * @hide
2545 */
Amith Yamasani12747872015-12-07 14:19:49 -08002546 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002547 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002548 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002549 final UserInfo user = createProfileForUser(
2550 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002551 if (user == null) {
2552 return null;
2553 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002554 long identity = Binder.clearCallingIdentity();
2555 try {
2556 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2557 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2558 // the putIntForUser() will fail.
2559 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2560 android.provider.Settings.Secure.LOCATION_MODE,
2561 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2562 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2563 } finally {
2564 Binder.restoreCallingIdentity(identity);
2565 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002566 return user;
2567 }
2568
2569 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002570 * Find the current guest user. If the Guest user is partial,
2571 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002572 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002573 private UserInfo findCurrentGuestUser() {
2574 synchronized (mUsersLock) {
2575 final int size = mUsers.size();
2576 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002577 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002578 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2579 return user;
2580 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002581 }
2582 }
2583 return null;
2584 }
2585
2586 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002587 * Mark this guest user for deletion to allow us to create another guest
2588 * and switch to that user before actually removing this guest.
2589 * @param userHandle the userid of the current guest
2590 * @return whether the user could be marked for deletion
2591 */
Amith Yamasani12747872015-12-07 14:19:49 -08002592 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002593 public boolean markGuestForDeletion(int userHandle) {
2594 checkManageUsersPermission("Only the system can remove users");
2595 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2596 UserManager.DISALLOW_REMOVE_USER, false)) {
2597 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2598 return false;
2599 }
2600
2601 long ident = Binder.clearCallingIdentity();
2602 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002603 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002604 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002605 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002606 userData = mUsers.get(userHandle);
2607 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002608 return false;
2609 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002610 }
Amith Yamasani12747872015-12-07 14:19:49 -08002611 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002612 return false;
2613 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002614 // We set this to a guest user that is to be removed. This is a temporary state
2615 // where we are allowed to add new Guest users, even if this one is still not
2616 // removed. This user will still show up in getUserInfo() calls.
2617 // If we don't get around to removing this Guest user, it will be purged on next
2618 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002619 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002620 // Mark it as disabled, so that it isn't returned any more when
2621 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002622 userData.info.flags |= UserInfo.FLAG_DISABLED;
2623 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002624 }
2625 } finally {
2626 Binder.restoreCallingIdentity(ident);
2627 }
2628 return true;
2629 }
2630
2631 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002632 * Removes a user and all data directories created for that user. This method should be called
2633 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002634 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002635 */
Amith Yamasani12747872015-12-07 14:19:49 -08002636 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002637 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002638 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002639 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002640
2641 final boolean isManagedProfile;
2642 synchronized (mUsersLock) {
2643 UserInfo userInfo = getUserInfoLU(userHandle);
2644 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2645 }
2646 String restriction = isManagedProfile
2647 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2648 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2649 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002650 return false;
2651 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002652 return removeUserUnchecked(userHandle);
2653 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002654
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002655 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002656 long ident = Binder.clearCallingIdentity();
2657 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002658 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002659 int currentUser = ActivityManager.getCurrentUser();
2660 if (currentUser == userHandle) {
2661 Log.w(LOG_TAG, "Current user cannot be removed");
2662 return false;
2663 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002664 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002665 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002666 userData = mUsers.get(userHandle);
2667 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002668 return false;
2669 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002670
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002671 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002672 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002673
Kenny Guyee58b4f2014-05-23 15:19:53 +01002674 try {
2675 mAppOpsService.removeUser(userHandle);
2676 } catch (RemoteException e) {
2677 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2678 }
2679 // Set this to a partially created user, so that the user will be purged
2680 // on next startup, in case the runtime stops now before stopping and
2681 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002682 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002683 // Mark it as disabled, so that it isn't returned any more when
2684 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002685 userData.info.flags |= UserInfo.FLAG_DISABLED;
2686 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002687 }
2688
Amith Yamasani12747872015-12-07 14:19:49 -08002689 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2690 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002691 // Send broadcast to notify system that the user removed was a
2692 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002693 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002694 }
2695
2696 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2697 int res;
2698 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002699 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002700 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002701 @Override
2702 public void userStopped(int userId) {
2703 finishRemoveUser(userId);
2704 }
2705 @Override
2706 public void userStopAborted(int userId) {
2707 }
2708 });
2709 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002710 return false;
2711 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002712 return res == ActivityManager.USER_OP_SUCCESS;
2713 } finally {
2714 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002715 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002716 }
2717
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002718 @VisibleForTesting
2719 void addRemovingUserIdLocked(int userId) {
2720 // We remember deleted user IDs to prevent them from being
2721 // reused during the current boot; they can still be reused
2722 // after a reboot or recycling of userIds.
2723 mRemovingUserIds.put(userId, true);
2724 mRecentlyRemovedIds.add(userId);
2725 // Keep LRU queue of recently removed IDs for recycling
2726 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2727 mRecentlyRemovedIds.removeFirst();
2728 }
2729 }
2730
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002731 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002732 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002733 // Let other services shutdown any activity and clean up their state before completely
2734 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002735 long ident = Binder.clearCallingIdentity();
2736 try {
2737 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2738 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002739 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2740 android.Manifest.permission.MANAGE_USERS,
2741
2742 new BroadcastReceiver() {
2743 @Override
2744 public void onReceive(Context context, Intent intent) {
2745 if (DBG) {
2746 Slog.i(LOG_TAG,
2747 "USER_REMOVED broadcast sent, cleaning up user data "
2748 + userHandle);
2749 }
2750 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002751 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002752 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002753 // Clean up any ActivityManager state
2754 LocalServices.getService(ActivityManagerInternal.class)
2755 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002756 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002757 }
2758 }.start();
2759 }
2760 },
2761
2762 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002763 } finally {
2764 Binder.restoreCallingIdentity(ident);
2765 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002766 }
2767
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002768 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002769 try {
2770 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2771 } catch (IllegalStateException e) {
2772 // This may be simply because the user was partially created.
2773 Slog.i(LOG_TAG,
2774 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2775 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002776
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002777 // Cleanup gatekeeper secure user id
2778 try {
2779 final IGateKeeperService gk = GateKeeper.getService();
2780 if (gk != null) {
2781 gk.clearSecureUserId(userHandle);
2782 }
2783 } catch (Exception ex) {
2784 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2785 }
2786
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002787 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002788 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002789
2790 // Clean up all data before removing metadata
2791 mPm.destroyUserData(userHandle,
2792 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2793
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002794 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002795 synchronized (mUsersLock) {
2796 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002797 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002798 }
2799 synchronized (mUserStates) {
2800 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002801 }
2802 synchronized (mRestrictionsLock) {
2803 mBaseUserRestrictions.remove(userHandle);
2804 mAppliedUserRestrictions.remove(userHandle);
2805 mCachedEffectiveUserRestrictions.remove(userHandle);
2806 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002807 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2808 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2809 applyUserRestrictionsForAllUsersLR();
2810 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002811 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002812 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002813 synchronized (mPackagesLock) {
2814 writeUserListLP();
2815 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002816 // Remove user file
2817 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2818 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002819 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002820 if (RELEASE_DELETED_USER_ID) {
2821 synchronized (mUsers) {
2822 mRemovingUserIds.delete(userHandle);
2823 }
2824 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002825 }
2826
Kenny Guyf8d3a232014-05-15 16:09:52 +01002827 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002828 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002829 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2830 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002831 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002832 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002833 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002834 }
2835
Amith Yamasani2a003292012-08-14 18:25:45 -07002836 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002837 public Bundle getApplicationRestrictions(String packageName) {
2838 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2839 }
2840
2841 @Override
2842 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002843 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002844 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002845 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002846 }
2847 synchronized (mPackagesLock) {
2848 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002849 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002850 }
2851 }
2852
2853 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002854 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002855 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002856 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002857 if (restrictions != null) {
2858 restrictions.setDefusable(true);
2859 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002860 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002861 if (restrictions == null || restrictions.isEmpty()) {
2862 cleanAppRestrictionsForPackage(packageName, userId);
2863 } else {
2864 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002865 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002866 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002867 }
Robin Lee66e5d962014-04-09 16:44:21 +01002868
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002869 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2870 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2871 changeIntent.setPackage(packageName);
2872 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2873 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002874 }
2875
2876 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002877 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002878 try {
2879 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002880 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002881 } catch (NameNotFoundException nnfe) {
2882 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002883 } finally {
2884 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002885 }
2886 }
2887
Fyodor Kupolov82402752015-10-28 14:54:51 -07002888 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002889 AtomicFile restrictionsFile =
2890 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2891 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002892 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002893 }
2894
2895 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002896 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002897 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002898 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002899 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002900 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002901 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002902
2903 FileInputStream fis = null;
2904 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002905 fis = restrictionsFile.openRead();
2906 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002907 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002908 XmlUtils.nextElement(parser);
2909 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002910 Slog.e(LOG_TAG, "Unable to read restrictions file "
2911 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002912 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002913 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002914 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2915 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002916 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002917 } catch (IOException|XmlPullParserException e) {
2918 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002919 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002920 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002921 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002922 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002923 }
2924
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002925 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2926 XmlPullParser parser) throws XmlPullParserException, IOException {
2927 int type = parser.getEventType();
2928 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2929 String key = parser.getAttributeValue(null, ATTR_KEY);
2930 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2931 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2932 if (multiple != null) {
2933 values.clear();
2934 int count = Integer.parseInt(multiple);
2935 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2936 if (type == XmlPullParser.START_TAG
2937 && parser.getName().equals(TAG_VALUE)) {
2938 values.add(parser.nextText().trim());
2939 count--;
2940 }
2941 }
2942 String [] valueStrings = new String[values.size()];
2943 values.toArray(valueStrings);
2944 restrictions.putStringArray(key, valueStrings);
2945 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2946 restrictions.putBundle(key, readBundleEntry(parser, values));
2947 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2948 final int outerDepth = parser.getDepth();
2949 ArrayList<Bundle> bundleList = new ArrayList<>();
2950 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2951 Bundle childBundle = readBundleEntry(parser, values);
2952 bundleList.add(childBundle);
2953 }
2954 restrictions.putParcelableArray(key,
2955 bundleList.toArray(new Bundle[bundleList.size()]));
2956 } else {
2957 String value = parser.nextText().trim();
2958 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2959 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2960 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2961 restrictions.putInt(key, Integer.parseInt(value));
2962 } else {
2963 restrictions.putString(key, value);
2964 }
2965 }
2966 }
2967 }
2968
2969 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2970 throws IOException, XmlPullParserException {
2971 Bundle childBundle = new Bundle();
2972 final int outerDepth = parser.getDepth();
2973 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2974 readEntry(childBundle, values, parser);
2975 }
2976 return childBundle;
2977 }
2978
Fyodor Kupolov82402752015-10-28 14:54:51 -07002979 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002980 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002981 AtomicFile restrictionsFile = new AtomicFile(
2982 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002983 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002984 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002985 }
2986
2987 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002988 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002989 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002990 try {
2991 fos = restrictionsFile.startWrite();
2992 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2993
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002994 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002995 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002996 serializer.startDocument(null, true);
2997 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2998
2999 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003000 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003001 serializer.endTag(null, TAG_RESTRICTIONS);
3002
3003 serializer.endDocument();
3004 restrictionsFile.finishWrite(fos);
3005 } catch (Exception e) {
3006 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003007 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3008 }
3009 }
3010
3011 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3012 throws IOException {
3013 for (String key : restrictions.keySet()) {
3014 Object value = restrictions.get(key);
3015 serializer.startTag(null, TAG_ENTRY);
3016 serializer.attribute(null, ATTR_KEY, key);
3017
3018 if (value instanceof Boolean) {
3019 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3020 serializer.text(value.toString());
3021 } else if (value instanceof Integer) {
3022 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3023 serializer.text(value.toString());
3024 } else if (value == null || value instanceof String) {
3025 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3026 serializer.text(value != null ? (String) value : "");
3027 } else if (value instanceof Bundle) {
3028 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3029 writeBundle((Bundle) value, serializer);
3030 } else if (value instanceof Parcelable[]) {
3031 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3032 Parcelable[] array = (Parcelable[]) value;
3033 for (Parcelable parcelable : array) {
3034 if (!(parcelable instanceof Bundle)) {
3035 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3036 }
3037 serializer.startTag(null, TAG_ENTRY);
3038 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3039 writeBundle((Bundle) parcelable, serializer);
3040 serializer.endTag(null, TAG_ENTRY);
3041 }
3042 } else {
3043 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3044 String[] values = (String[]) value;
3045 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3046 for (String choice : values) {
3047 serializer.startTag(null, TAG_VALUE);
3048 serializer.text(choice != null ? choice : "");
3049 serializer.endTag(null, TAG_VALUE);
3050 }
3051 }
3052 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003053 }
3054 }
3055
3056 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003057 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003058 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003059 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003060 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003061 }
3062 }
3063
3064 @Override
3065 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003066 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003067 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003068 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003069 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003070 }
3071 // Not found
3072 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003073 }
3074 }
3075
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003076 @Override
3077 public long getUserCreationTime(int userHandle) {
3078 int callingUserId = UserHandle.getCallingUserId();
3079 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003080 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003081 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003082 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003083 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003084 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003085 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003086 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003087 }
3088 }
3089 }
3090 if (userInfo == null) {
3091 throw new SecurityException("userHandle can only be the calling user or a managed "
3092 + "profile associated with this user");
3093 }
3094 return userInfo.creationTime;
3095 }
3096
Amith Yamasani0b285492011-04-14 17:35:23 -07003097 /**
3098 * Caches the list of user ids in an array, adjusting the array size when necessary.
3099 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003100 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003101 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003102 synchronized (mUsersLock) {
3103 final int userSize = mUsers.size();
3104 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003105 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003106 num++;
3107 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003108 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003109 final int[] newUsers = new int[num];
3110 int n = 0;
3111 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003112 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003113 newUsers[n++] = mUsers.keyAt(i);
3114 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003115 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003116 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003117 }
3118 }
3119
3120 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003121 * Called right before a user is started. This gives us a chance to prepare
3122 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003123 */
3124 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003125 UserInfo userInfo = getUserInfo(userId);
3126 if (userInfo == null) {
3127 return;
3128 }
3129 final int userSerial = userInfo.serialNumber;
3130 // Migrate only if build fingerprints mismatch
3131 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003132 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003133 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003134
3135 if (userId != UserHandle.USER_SYSTEM) {
3136 synchronized (mRestrictionsLock) {
3137 applyUserRestrictionsLR(userId);
3138 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003139 }
3140 }
3141
3142 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003143 * Called right before a user is unlocked. This gives us a chance to prepare
3144 * app storage.
3145 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003146 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003147 UserInfo userInfo = getUserInfo(userId);
3148 if (userInfo == null) {
3149 return;
3150 }
3151 final int userSerial = userInfo.serialNumber;
3152 // Migrate only if build fingerprints mismatch
3153 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003154 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003155 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003156 }
3157
3158 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003159 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003160 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003161 * @param userId the user that was just foregrounded
3162 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003163 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003164 UserData userData = getUserDataNoChecks(userId);
3165 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003166 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3167 return;
3168 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003169
3170 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003171 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003172 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003173 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003174 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3175 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003176 }
3177
3178 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003179 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003180 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003181 @VisibleForTesting
3182 int getNextAvailableId() {
3183 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003184 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003185 nextId = scanNextAvailableIdLocked();
3186 if (nextId >= 0) {
3187 return nextId;
3188 }
3189 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3190 // except most recently removed
3191 if (mRemovingUserIds.size() > 0) {
3192 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3193 mRemovingUserIds.clear();
3194 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3195 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003196 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003197 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003198 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003199 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003200 if (nextId < 0) {
3201 throw new IllegalStateException("No user id available!");
3202 }
3203 return nextId;
3204 }
3205
3206 private int scanNextAvailableIdLocked() {
3207 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3208 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3209 return i;
3210 }
3211 }
3212 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003213 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003214
Amith Yamasanifc95e702013-09-26 13:20:17 -07003215 private String packageToRestrictionsFileName(String packageName) {
3216 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3217 }
3218
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003219 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003220 * Enforce that serial number stored in user directory inode matches the
3221 * given expected value. Gracefully sets the serial number if currently
3222 * undefined.
3223 *
3224 * @throws IOException when problem extracting serial number, or serial
3225 * number is mismatched.
3226 */
3227 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003228 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3229 // When we're emulating FBE, the directory may have been chmod
3230 // 000'ed, meaning we can't read the serial number to enforce it;
3231 // instead of destroying the user, just log a warning.
3232 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3233 return;
3234 }
3235
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003236 final int foundSerial = getSerialNumber(file);
3237 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3238
3239 if (foundSerial == -1) {
3240 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3241 try {
3242 setSerialNumber(file, serialNumber);
3243 } catch (IOException e) {
3244 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3245 }
3246
3247 } else if (foundSerial != serialNumber) {
3248 throw new IOException("Found serial number " + foundSerial
3249 + " doesn't match expected " + serialNumber);
3250 }
3251 }
3252
3253 /**
3254 * Set serial number stored in user directory inode.
3255 *
3256 * @throws IOException if serial number was already set
3257 */
3258 private static void setSerialNumber(File file, int serialNumber)
3259 throws IOException {
3260 try {
3261 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3262 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3263 } catch (ErrnoException e) {
3264 throw e.rethrowAsIOException();
3265 }
3266 }
3267
3268 /**
3269 * Return serial number stored in user directory inode.
3270 *
3271 * @return parsed serial number, or -1 if not set
3272 */
3273 private static int getSerialNumber(File file) throws IOException {
3274 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003275 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3276 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003277 try {
3278 return Integer.parseInt(serial);
3279 } catch (NumberFormatException e) {
3280 throw new IOException("Bad serial number: " + serial);
3281 }
3282 } catch (ErrnoException e) {
3283 if (e.errno == OsConstants.ENODATA) {
3284 return -1;
3285 } else {
3286 throw e.rethrowAsIOException();
3287 }
3288 }
3289 }
3290
Amith Yamasani920ace02012-09-20 22:15:37 -07003291 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003292 public void setSeedAccountData(int userId, String accountName, String accountType,
3293 PersistableBundle accountOptions, boolean persist) {
3294 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3295 synchronized (mPackagesLock) {
3296 final UserData userData;
3297 synchronized (mUsersLock) {
3298 userData = getUserDataLU(userId);
3299 if (userData == null) {
3300 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3301 return;
3302 }
3303 userData.seedAccountName = accountName;
3304 userData.seedAccountType = accountType;
3305 userData.seedAccountOptions = accountOptions;
3306 userData.persistSeedData = persist;
3307 }
3308 if (persist) {
3309 writeUserLP(userData);
3310 }
3311 }
3312 }
3313
3314 @Override
3315 public String getSeedAccountName() throws RemoteException {
3316 checkManageUsersPermission("Cannot get seed account information");
3317 synchronized (mUsersLock) {
3318 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3319 return userData.seedAccountName;
3320 }
3321 }
3322
3323 @Override
3324 public String getSeedAccountType() throws RemoteException {
3325 checkManageUsersPermission("Cannot get seed account information");
3326 synchronized (mUsersLock) {
3327 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3328 return userData.seedAccountType;
3329 }
3330 }
3331
3332 @Override
3333 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3334 checkManageUsersPermission("Cannot get seed account information");
3335 synchronized (mUsersLock) {
3336 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3337 return userData.seedAccountOptions;
3338 }
3339 }
3340
3341 @Override
3342 public void clearSeedAccountData() throws RemoteException {
3343 checkManageUsersPermission("Cannot clear seed account information");
3344 synchronized (mPackagesLock) {
3345 UserData userData;
3346 synchronized (mUsersLock) {
3347 userData = getUserDataLU(UserHandle.getCallingUserId());
3348 if (userData == null) return;
3349 userData.clearSeedAccountData();
3350 }
3351 writeUserLP(userData);
3352 }
3353 }
3354
3355 @Override
3356 public boolean someUserHasSeedAccount(String accountName, String accountType)
3357 throws RemoteException {
3358 checkManageUsersPermission("Cannot check seed account information");
3359 synchronized (mUsersLock) {
3360 final int userSize = mUsers.size();
3361 for (int i = 0; i < userSize; i++) {
3362 final UserData data = mUsers.valueAt(i);
3363 if (data.info.isInitialized()) continue;
3364 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3365 continue;
3366 }
3367 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3368 continue;
3369 }
3370 return true;
3371 }
3372 }
3373 return false;
3374 }
3375
3376 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003377 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003378 FileDescriptor err, String[] args, ShellCallback callback,
3379 ResultReceiver resultReceiver) {
3380 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003381 }
3382
3383 int onShellCommand(Shell shell, String cmd) {
3384 if (cmd == null) {
3385 return shell.handleDefaultCommands(cmd);
3386 }
3387
3388 final PrintWriter pw = shell.getOutPrintWriter();
3389 try {
3390 switch(cmd) {
3391 case "list":
3392 return runList(pw);
3393 }
3394 } catch (RemoteException e) {
3395 pw.println("Remote exception: " + e);
3396 }
3397 return -1;
3398 }
3399
3400 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003401 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003402 final List<UserInfo> users = getUsers(false);
3403 if (users == null) {
3404 pw.println("Error: couldn't get users");
3405 return 1;
3406 } else {
3407 pw.println("Users:");
3408 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003409 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003410 pw.println("\t" + users.get(i).toString() + running);
3411 }
3412 return 0;
3413 }
3414 }
3415
3416 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003417 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3418 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3419 != PackageManager.PERMISSION_GRANTED) {
3420 pw.println("Permission Denial: can't dump UserManager from from pid="
3421 + Binder.getCallingPid()
3422 + ", uid=" + Binder.getCallingUid()
3423 + " without permission "
3424 + android.Manifest.permission.DUMP);
3425 return;
3426 }
3427
3428 long now = System.currentTimeMillis();
3429 StringBuilder sb = new StringBuilder();
3430 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003431 synchronized (mUsersLock) {
3432 pw.println("Users:");
3433 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003434 UserData userData = mUsers.valueAt(i);
3435 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003436 continue;
3437 }
Amith Yamasani12747872015-12-07 14:19:49 -08003438 UserInfo userInfo = userData.info;
3439 final int userId = userInfo.id;
3440 pw.print(" "); pw.print(userInfo);
3441 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003442 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003443 pw.print(" <removing> ");
3444 }
Amith Yamasani12747872015-12-07 14:19:49 -08003445 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003446 pw.print(" <partial>");
3447 }
3448 pw.println();
3449 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003450 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003451 pw.println("<unknown>");
3452 } else {
3453 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003454 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003455 sb.append(" ago");
3456 pw.println(sb);
3457 }
3458 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003459 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003460 pw.println("<unknown>");
3461 } else {
3462 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003463 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003464 sb.append(" ago");
3465 pw.println(sb);
3466 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003467 pw.print(" Last logged in fingerprint: ");
3468 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003469 pw.print(" Has profile owner: ");
3470 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003471 pw.println(" Restrictions:");
3472 synchronized (mRestrictionsLock) {
3473 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003474 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003475 pw.println(" Device policy global restrictions:");
3476 UserRestrictionsUtils.dumpRestrictions(
3477 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003478 pw.println(" Device policy local restrictions:");
3479 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003480 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003481 pw.println(" Effective restrictions:");
3482 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003483 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003484 }
Amith Yamasani12747872015-12-07 14:19:49 -08003485
3486 if (userData.account != null) {
3487 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003488 pw.println();
3489 }
Amith Yamasani12747872015-12-07 14:19:49 -08003490
3491 if (userData.seedAccountName != null) {
3492 pw.print(" Seed account name: " + userData.seedAccountName);
3493 pw.println();
3494 if (userData.seedAccountType != null) {
3495 pw.print(" account type: " + userData.seedAccountType);
3496 pw.println();
3497 }
3498 if (userData.seedAccountOptions != null) {
3499 pw.print(" account options exist");
3500 pw.println();
3501 }
3502 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003503 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003504 }
Amith Yamasani12747872015-12-07 14:19:49 -08003505 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003506 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003507 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003508 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003509 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003510 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003511 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003512 synchronized (mUsersLock) {
3513 pw.println();
3514 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003515 if (mRemovingUserIds.size() > 0) {
3516 pw.println();
3517 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3518 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003519 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003520 synchronized (mUserStates) {
3521 pw.println(" Started users state: " + mUserStates);
3522 }
Amith Yamasani12747872015-12-07 14:19:49 -08003523 // Dump some capabilities
3524 pw.println();
3525 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3526 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003527 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3528 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003529 }
3530 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003531
3532 final class MainHandler extends Handler {
3533
3534 @Override
3535 public void handleMessage(Message msg) {
3536 switch (msg.what) {
3537 case WRITE_USER_MSG:
3538 removeMessages(WRITE_USER_MSG, msg.obj);
3539 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003540 int userId = ((UserData) msg.obj).info.id;
3541 UserData userData = getUserDataNoChecks(userId);
3542 if (userData != null) {
3543 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003544 }
3545 }
3546 }
3547 }
3548 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003549
3550 /**
3551 * @param userId
3552 * @return whether the user has been initialized yet
3553 */
3554 boolean isInitialized(int userId) {
3555 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3556 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003557
3558 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003559 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003560 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3561 boolean isDeviceOwner, int cameraRestrictionScope) {
3562 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3563 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003564 }
3565
3566 @Override
3567 public Bundle getBaseUserRestrictions(int userId) {
3568 synchronized (mRestrictionsLock) {
3569 return mBaseUserRestrictions.get(userId);
3570 }
3571 }
3572
3573 @Override
3574 public void setBaseUserRestrictionsByDpmsForMigration(
3575 int userId, Bundle baseRestrictions) {
3576 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003577 if (updateRestrictionsIfNeededLR(
3578 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3579 invalidateEffectiveUserRestrictionsLR(userId);
3580 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003581 }
3582
Amith Yamasani12747872015-12-07 14:19:49 -08003583 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003584 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003585 if (userData != null) {
3586 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003587 } else {
3588 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3589 }
3590 }
3591 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003592
3593 @Override
3594 public boolean getUserRestriction(int userId, String key) {
3595 return getUserRestrictions(userId).getBoolean(key);
3596 }
3597
3598 @Override
3599 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3600 synchronized (mUserRestrictionsListeners) {
3601 mUserRestrictionsListeners.add(listener);
3602 }
3603 }
3604
3605 @Override
3606 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3607 synchronized (mUserRestrictionsListeners) {
3608 mUserRestrictionsListeners.remove(listener);
3609 }
3610 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003611
3612 @Override
3613 public void setDeviceManaged(boolean isManaged) {
3614 synchronized (mUsersLock) {
3615 mIsDeviceManaged = isManaged;
3616 }
3617 }
3618
3619 @Override
3620 public void setUserManaged(int userId, boolean isManaged) {
3621 synchronized (mUsersLock) {
3622 mIsUserManaged.put(userId, isManaged);
3623 }
3624 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003625
3626 @Override
3627 public void setUserIcon(int userId, Bitmap bitmap) {
3628 long ident = Binder.clearCallingIdentity();
3629 try {
3630 synchronized (mPackagesLock) {
3631 UserData userData = getUserDataNoChecks(userId);
3632 if (userData == null || userData.info.partial) {
3633 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3634 return;
3635 }
3636 writeBitmapLP(userData.info, bitmap);
3637 writeUserLP(userData);
3638 }
3639 sendUserInfoChangedBroadcast(userId);
3640 } finally {
3641 Binder.restoreCallingIdentity(ident);
3642 }
3643 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003644
3645 @Override
3646 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3647 synchronized (mUsersLock) {
3648 mForceEphemeralUsers = forceEphemeralUsers;
3649 }
3650 }
3651
3652 @Override
3653 public void removeAllUsers() {
3654 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3655 // Remove the non-system users straight away.
3656 removeNonSystemUsers();
3657 } else {
3658 // Switch to the system user first and then remove the other users.
3659 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3660 @Override
3661 public void onReceive(Context context, Intent intent) {
3662 int userId =
3663 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3664 if (userId != UserHandle.USER_SYSTEM) {
3665 return;
3666 }
3667 mContext.unregisterReceiver(this);
3668 removeNonSystemUsers();
3669 }
3670 };
3671 IntentFilter userSwitchedFilter = new IntentFilter();
3672 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3673 mContext.registerReceiver(
3674 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3675
3676 // Switch to the system user.
3677 ActivityManager am =
3678 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3679 am.switchUser(UserHandle.USER_SYSTEM);
3680 }
3681 }
phweisse9c44062016-02-10 12:57:38 +01003682
3683 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003684 public void onEphemeralUserStop(int userId) {
3685 synchronized (mUsersLock) {
3686 UserInfo userInfo = getUserInfoLU(userId);
3687 if (userInfo != null && userInfo.isEphemeral()) {
3688 // Do not allow switching back to the ephemeral user again as the user is going
3689 // to be deleted.
3690 userInfo.flags |= UserInfo.FLAG_DISABLED;
3691 if (userInfo.isGuest()) {
3692 // Indicate that the guest will be deleted after it stops.
3693 userInfo.guestToRemove = true;
3694 }
3695 }
3696 }
3697 }
3698
3699 @Override
phweisse9c44062016-02-10 12:57:38 +01003700 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003701 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003702 // Keep this in sync with UserManager.createUser
3703 if (user != null && !user.isAdmin()) {
3704 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3705 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3706 }
3707 return user;
3708 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003709
3710 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003711 public boolean removeUserEvenWhenDisallowed(int userId) {
3712 return removeUserUnchecked(userId);
3713 }
3714
3715 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003716 public boolean isUserRunning(int userId) {
3717 synchronized (mUserStates) {
3718 return mUserStates.get(userId, -1) >= 0;
3719 }
3720 }
3721
3722 @Override
3723 public void setUserState(int userId, int userState) {
3724 synchronized (mUserStates) {
3725 mUserStates.put(userId, userState);
3726 }
3727 }
3728
3729 @Override
3730 public void removeUserState(int userId) {
3731 synchronized (mUserStates) {
3732 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003733 }
3734 }
3735
3736 @Override
3737 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003738 synchronized (mUserStates) {
3739 int state = mUserStates.get(userId, -1);
3740 return (state == UserState.STATE_RUNNING_UNLOCKING)
3741 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003742 }
3743 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003744
3745 @Override
3746 public boolean isUserUnlocked(int userId) {
3747 synchronized (mUserStates) {
3748 int state = mUserStates.get(userId, -1);
3749 return state == UserState.STATE_RUNNING_UNLOCKED;
3750 }
3751 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003752 }
3753
3754 /* Remove all the users except of the system one. */
3755 private void removeNonSystemUsers() {
3756 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3757 synchronized (mUsersLock) {
3758 final int userSize = mUsers.size();
3759 for (int i = 0; i < userSize; i++) {
3760 UserInfo ui = mUsers.valueAt(i).info;
3761 if (ui.id != UserHandle.USER_SYSTEM) {
3762 usersToRemove.add(ui);
3763 }
3764 }
3765 }
3766 for (UserInfo ui: usersToRemove) {
3767 removeUser(ui.id);
3768 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003769 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003770
3771 private class Shell extends ShellCommand {
3772 @Override
3773 public int onCommand(String cmd) {
3774 return onShellCommand(this, cmd);
3775 }
3776
3777 @Override
3778 public void onHelp() {
3779 final PrintWriter pw = getOutPrintWriter();
3780 pw.println("User manager (user) commands:");
3781 pw.println(" help");
3782 pw.println(" Print this help text.");
3783 pw.println("");
3784 pw.println(" list");
3785 pw.println(" Prints all users on the system.");
3786 }
3787 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003788
3789 private static void debug(String message) {
3790 Log.d(LOG_TAG, message +
3791 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3792 }
Kenny Guy02c89902016-11-15 19:36:38 +00003793
3794 @VisibleForTesting
3795 static int getMaxManagedProfiles() {
3796 // Allow overriding max managed profiles on debuggable builds for testing
3797 // of multiple profiles.
3798 if (!Build.IS_DEBUGGABLE) {
3799 return MAX_MANAGED_PROFILES;
3800 } else {
3801 return SystemProperties.getInt("persist.sys.max_profiles",
3802 MAX_MANAGED_PROFILES);
3803 }
3804 }
3805
3806 @VisibleForTesting
3807 int getFreeProfileBadgeLU(int parentUserId) {
3808 int maxManagedProfiles = getMaxManagedProfiles();
3809 boolean[] usedBadges = new boolean[maxManagedProfiles];
3810 final int userSize = mUsers.size();
3811 for (int i = 0; i < userSize; i++) {
3812 UserInfo ui = mUsers.valueAt(i).info;
3813 // Check which badge indexes are already used by this profile group.
3814 if (ui.isManagedProfile()
3815 && ui.profileGroupId == parentUserId
3816 && !mRemovingUserIds.get(ui.id)
3817 && ui.profileBadge < maxManagedProfiles) {
3818 usedBadges[ui.profileBadge] = true;
3819 }
3820 }
3821 for (int i = 0; i < maxManagedProfiles; i++) {
3822 if (!usedBadges[i]) {
3823 return i;
3824 }
3825 }
3826 return 0;
3827 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003828
3829 /**
3830 * Checks if the given user has a managed profile associated with it.
3831 * @param userId The parent user
3832 * @return
3833 */
3834 boolean hasManagedProfile(int userId) {
3835 synchronized (mUsersLock) {
3836 UserInfo userInfo = getUserInfoLU(userId);
3837 final int userSize = mUsers.size();
3838 for (int i = 0; i < userSize; i++) {
3839 UserInfo profile = mUsers.valueAt(i).info;
3840 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3841 return true;
3842 }
3843 }
3844 return false;
3845 }
3846 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003847}