blob: 9b47beba232e1baefb7a9e0ef260989baeb72b63 [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;
Bart Searsc51e7252016-05-27 04:12:51 +000036import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.content.Context;
38import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010039import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010040import android.content.IntentSender;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000041import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070042import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080043import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
Kenny Guy02c89902016-11-15 19:36:38 +000067import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070069import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070070import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080071import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010072import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070073import android.security.GateKeeper;
74import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070075import android.system.ErrnoException;
76import android.system.Os;
77import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070078import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070079import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070080import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070081import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import android.util.Slog;
83import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080084import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000085import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070086import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087import android.util.Xml;
88
Makoto Onuki068c54a2015-10-13 14:34:03 -070089import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070090import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040091import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080092import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080093import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070094import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070095import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000096import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070097import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070098import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000099import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700100import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100101
Jeff Sharkey47f71082016-02-01 17:03:54 -0700102import libcore.io.IoUtils;
103import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800104
105import org.xmlpull.v1.XmlPullParser;
106import org.xmlpull.v1.XmlPullParserException;
107import org.xmlpull.v1.XmlSerializer;
108
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109import java.io.BufferedOutputStream;
110import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700111import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114import java.io.FileOutputStream;
Kenny Guy02c89902016-11-15 19:36:38 +0000115import java.io.InputStream;
116import java.io.OutputStream;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700118import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100119import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120import java.util.ArrayList;
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";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100165 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800166 private static final String TAG_ENTRY = "entry";
167 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800168 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800169 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700170 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800171 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700173 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
174 private static final String ATTR_TYPE_STRING = "s";
175 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700176 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700177 private static final String ATTR_TYPE_BUNDLE = "B";
178 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700179
Amith Yamasani0b285492011-04-14 17:35:23 -0700180 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700181 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700182 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100183 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700184
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800185 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700186 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800187
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700188 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
189 UserInfo.FLAG_MANAGED_PROFILE
190 | UserInfo.FLAG_EPHEMERAL
191 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700192 | UserInfo.FLAG_GUEST
193 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700194
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700195 @VisibleForTesting
196 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700197 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700198 @VisibleForTesting
199 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
200
201 // Max size of the queue of recently removed users
202 @VisibleForTesting
203 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700204
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700205 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700206
Amith Yamasani920ace02012-09-20 22:15:37 -0700207 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
208
Nicolas Prevotb8186812015-08-06 15:00:03 +0100209 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700210 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000211 @VisibleForTesting
212 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700213
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800214 static final int WRITE_USER_MSG = 1;
215 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530216
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700217 private static final String XATTR_SERIAL = "user.serial";
218
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800219 // Tron counters
220 private static final String TRON_GUEST_CREATED = "users_guest_created";
221 private static final String TRON_USER_CREATED = "users_user_created";
222
Dianne Hackborn4428e172012-08-24 17:43:05 -0700223 private final Context mContext;
224 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700225 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700226 // Short-term lock for internal state, when interaction/sync with PM is not required
227 private final Object mUsersLock = new Object();
228 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700229
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800230 private final Handler mHandler;
231
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700232 private final File mUsersDir;
233 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800235 private static final IBinder mUserRestriconToken = new Binder();
236
Makoto Onuki068c54a2015-10-13 14:34:03 -0700237 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800238 * User-related information that is used for persisting to flash. Only UserInfo is
239 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800240 */
Kenny Guy02c89902016-11-15 19:36:38 +0000241 @VisibleForTesting
242 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800243 // Basic user information and properties
244 UserInfo info;
245 // Account name used when there is a strong association between a user and an account
246 String account;
247 // Account information for seeding into a newly created user. This could also be
248 // used for login validation for an existing user, for updating their credentials.
249 // In the latter case, data may not need to be persisted as it is only valid for the
250 // current login session.
251 String seedAccountName;
252 String seedAccountType;
253 PersistableBundle seedAccountOptions;
254 // Whether to perist the seed account information to be available after a boot
255 boolean persistSeedData;
256
257 void clearSeedAccountData() {
258 seedAccountName = null;
259 seedAccountType = null;
260 seedAccountOptions = null;
261 persistSeedData = false;
262 }
263 }
264
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800265 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800266 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800267
268 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700269 * User restrictions set via UserManager. This doesn't include restrictions set by
270 * device owner / profile owners.
271 *
272 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
273 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
274 * maybe shared between {@link #mBaseUserRestrictions} and
275 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
276 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700277 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700278 */
279 @GuardedBy("mRestrictionsLock")
280 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
281
282 /**
283 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
284 * with device / profile owner restrictions. We'll initialize it lazily; use
285 * {@link #getEffectiveUserRestrictions} to access it.
286 *
287 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
288 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
289 * maybe shared between {@link #mBaseUserRestrictions} and
290 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
291 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700292 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700293 */
294 @GuardedBy("mRestrictionsLock")
295 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
296
Makoto Onuki4f160732015-10-27 17:15:38 -0700297 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800298 * User restrictions that have already been applied in
299 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
300 * that have changed since the last
301 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700302 */
303 @GuardedBy("mRestrictionsLock")
304 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
305
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800306 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800307 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
308 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800309 */
310 @GuardedBy("mRestrictionsLock")
311 private Bundle mDevicePolicyGlobalUserRestrictions;
312
313 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100314 * Id of the user that set global restrictions.
315 */
316 @GuardedBy("mRestrictionsLock")
317 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
318
319 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800320 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
321 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800322 */
323 @GuardedBy("mRestrictionsLock")
324 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
325
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800326 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530327 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800328
329 /**
330 * Set of user IDs being actively removed. Removed IDs linger in this set
331 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700332 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800333 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700334 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800335 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700336
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700337 /**
338 * Queue of recently removed userIds. Used for recycling of userIds
339 */
340 @GuardedBy("mUsersLock")
341 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
342
Fyodor Kupolov82402752015-10-28 14:54:51 -0700343 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700344 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800345 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700346 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700347 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700348
Jason Monk62062992014-05-06 09:55:28 -0400349 private IAppOpsService mAppOpsService;
350
Makoto Onuki068c54a2015-10-13 14:34:03 -0700351 private final LocalService mLocalService;
352
Makoto Onukie7927da2015-11-25 10:05:17 -0800353 @GuardedBy("mUsersLock")
354 private boolean mIsDeviceManaged;
355
356 @GuardedBy("mUsersLock")
357 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
358
Makoto Onukid45a4a22015-11-02 17:17:38 -0800359 @GuardedBy("mUserRestrictionsListeners")
360 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
361 new ArrayList<>();
362
Clara Bayarria1771112015-12-18 16:29:18 +0000363 private final LockPatternUtils mLockPatternUtils;
364
Ricky Waib1dd80b2016-06-07 18:00:55 +0100365 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
366 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
367
368 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
369 @Override
370 public void onReceive(Context context, Intent intent) {
371 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
372 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
373 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
374 setQuietModeEnabled(userHandle, false);
375 if (target != null) {
376 try {
377 mContext.startIntentSender(target, null, 0, 0, 0);
378 } catch (IntentSender.SendIntentException e) {
379 /* ignore */
380 }
381 }
382 }
383 }
384 };
385
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100386 /**
387 * Whether all users should be created ephemeral.
388 */
389 @GuardedBy("mUsersLock")
390 private boolean mForceEphemeralUsers;
391
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000392 @GuardedBy("mUserStates")
393 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700394
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700396
Dianne Hackborn4428e172012-08-24 17:43:05 -0700397 public static UserManagerService getInstance() {
398 synchronized (UserManagerService.class) {
399 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700401 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700402
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700403 public static class LifeCycle extends SystemService {
404
405 private UserManagerService mUms;
406
407 /**
408 * @param context
409 */
410 public LifeCycle(Context context) {
411 super(context);
412 }
413
414 @Override
415 public void onStart() {
416 mUms = UserManagerService.getInstance();
417 publishBinderService(Context.USER_SERVICE, mUms);
418 }
419
420 @Override
421 public void onBootPhase(int phase) {
422 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
423 mUms.cleanupPartialUsers();
424 }
425 }
426 }
427
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700428 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800429 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700430 UserManagerService(Context context) {
431 this(context, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700432 }
433
Dianne Hackborn4428e172012-08-24 17:43:05 -0700434 /**
435 * Called by package manager to create the service. This is closely
436 * associated with the package manager, and the given lock is the
437 * package manager's own lock.
438 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800439 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
440 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700441 }
442
Dianne Hackborn4428e172012-08-24 17:43:05 -0700443 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800444 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700445 mContext = context;
446 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700447 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800448 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800449 synchronized (mPackagesLock) {
450 mUsersDir = new File(dataDir, USER_INFO_DIR);
451 mUsersDir.mkdirs();
452 // Make zeroth user directory, for services to migrate their files to that location
453 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
454 userZeroDir.mkdirs();
455 FileUtils.setPermissions(mUsersDir.toString(),
456 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
457 -1, -1);
458 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
459 initDefaultGuestRestrictions();
460 readUserListLP();
461 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700462 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700463 mLocalService = new LocalService();
464 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000465 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000466 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700467 }
468
469 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400470 mAppOpsService = IAppOpsService.Stub.asInterface(
471 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800472
473 synchronized (mRestrictionsLock) {
474 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400475 }
Samuel Tand9453b82016-03-14 15:57:02 -0700476
477 UserInfo currentGuestUser = findCurrentGuestUser();
478 if (currentGuestUser != null && !hasUserRestriction(
479 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
480 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
481 // to it, in case this guest was created in a previous version where this
482 // user restriction was not a default guest restriction.
483 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
484 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700485
Ricky Waib1dd80b2016-06-07 18:00:55 +0100486 mContext.registerReceiver(mDisableQuietModeCallback,
487 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
488 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700489 }
490
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700491 void cleanupPartialUsers() {
492 // Prune out any partially created, partially removed and ephemeral users.
493 ArrayList<UserInfo> partials = new ArrayList<>();
494 synchronized (mUsersLock) {
495 final int userSize = mUsers.size();
496 for (int i = 0; i < userSize; i++) {
497 UserInfo ui = mUsers.valueAt(i).info;
498 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
499 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700500 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700501 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700502 }
503 }
504 }
505 final int partialsSize = partials.size();
506 for (int i = 0; i < partialsSize; i++) {
507 UserInfo ui = partials.get(i);
508 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
509 + " (name=" + ui.name + ")");
510 removeUserState(ui.id);
511 }
512 }
513
Amith Yamasani258848d2012-08-10 17:06:33 -0700514 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800515 public String getUserAccount(int userId) {
516 checkManageUserAndAcrossUsersFullPermission("get user account");
517 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800518 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800519 }
520 }
521
522 @Override
523 public void setUserAccount(int userId, String accountName) {
524 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800525 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800526 synchronized (mPackagesLock) {
527 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800528 final UserData userData = mUsers.get(userId);
529 if (userData == null) {
530 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
531 return;
532 }
533 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800534 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800535 userData.account = accountName;
536 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800537 }
538 }
539
540 if (userToUpdate != null) {
541 writeUserLP(userToUpdate);
542 }
543 }
544 }
545
546 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700547 public UserInfo getPrimaryUser() {
548 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700549 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700550 final int userSize = mUsers.size();
551 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800552 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800553 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700554 return ui;
555 }
556 }
557 }
558 return null;
559 }
560
561 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700562 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700563 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700564 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700565 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700566 final int userSize = mUsers.size();
567 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800568 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700569 if (ui.partial) {
570 continue;
571 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800572 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700573 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700574 }
Amith Yamasani13593602012-03-22 16:16:17 -0700575 }
576 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700577 }
Amith Yamasani13593602012-03-22 16:16:17 -0700578 }
579
Amith Yamasani258848d2012-08-10 17:06:33 -0700580 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100581 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700582 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800583 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700584 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700585 } else {
586 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800587 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700588 final long ident = Binder.clearCallingIdentity();
589 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700590 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700591 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100592 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700593 } finally {
594 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000595 }
596 }
597
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700598 @Override
599 public int[] getProfileIds(int userId, boolean enabledOnly) {
600 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700601 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700602 }
603 final long ident = Binder.clearCallingIdentity();
604 try {
605 synchronized (mUsersLock) {
606 return getProfileIdsLU(userId, enabledOnly).toArray();
607 }
608 } finally {
609 Binder.restoreCallingIdentity(ident);
610 }
611 }
612
Amith Yamasanibe465322014-04-24 13:45:17 -0700613 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700614 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700615 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
616 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
617 for (int i = 0; i < profileIds.size(); i++) {
618 int profileId = profileIds.get(i);
619 UserInfo userInfo = mUsers.get(profileId).info;
620 // If full info is not required - clear PII data to prevent 3P apps from reading it
621 if (!fullInfo) {
622 userInfo = new UserInfo(userInfo);
623 userInfo.name = null;
624 userInfo.iconPath = null;
625 } else {
626 userInfo = userWithName(userInfo);
627 }
628 users.add(userInfo);
629 }
630 return users;
631 }
632
633 /**
634 * Assume permissions already checked and caller's identity cleared
635 */
636 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700637 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700638 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700639 if (user == null) {
640 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700641 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700642 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700643 final int userSize = mUsers.size();
644 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800645 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700646 if (!isProfileOf(user, profile)) {
647 continue;
648 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100649 if (enabledOnly && !profile.isEnabled()) {
650 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700651 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700652 if (mRemovingUserIds.get(profile.id)) {
653 continue;
654 }
Tony Mak80189cd2016-04-05 17:21:42 +0100655 if (profile.partial) {
656 continue;
657 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700658 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700659 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700660 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700661 }
662
Jessica Hummelbe81c802014-04-22 15:49:22 +0100663 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700664 public int getCredentialOwnerProfile(int userHandle) {
665 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000666 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700667 synchronized (mUsersLock) {
668 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700669 if (profileParent != null) {
670 return profileParent.id;
671 }
672 }
673 }
674
675 return userHandle;
676 }
677
678 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700679 public boolean isSameProfileGroup(int userId, int otherUserId) {
680 if (userId == otherUserId) return true;
681 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700682 return isSameProfileGroupNoChecks(userId, otherUserId);
683 }
684
685 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700686 synchronized (mUsersLock) {
687 UserInfo userInfo = getUserInfoLU(userId);
688 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
689 return false;
690 }
691 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
692 if (otherUserInfo == null
693 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
694 return false;
695 }
696 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700697 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700698 }
699
700 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100701 public UserInfo getProfileParent(int userHandle) {
702 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700703 synchronized (mUsersLock) {
704 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700705 }
706 }
707
Fyodor Kupolov82402752015-10-28 14:54:51 -0700708 private UserInfo getProfileParentLU(int userHandle) {
709 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700710 if (profile == null) {
711 return null;
712 }
713 int parentUserId = profile.profileGroupId;
714 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
715 return null;
716 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700717 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100718 }
719 }
720
Fyodor Kupolov82402752015-10-28 14:54:51 -0700721 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100722 return user.id == profile.id ||
723 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
724 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000725 }
726
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000727 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000728 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100729 Intent intent = new Intent();
730 if (inQuietMode) {
731 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
732 } else {
733 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
734 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000735 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
736 intent.putExtra(Intent.EXTRA_USER, profileHandle);
737 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000738 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000739 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000740 }
741
742 @Override
743 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
744 checkManageUsersPermission("silence profile");
745 boolean changed = false;
746 UserInfo profile, parent;
747 synchronized (mPackagesLock) {
748 synchronized (mUsersLock) {
749 profile = getUserInfoLU(userHandle);
750 parent = getProfileParentLU(userHandle);
751
752 }
753 if (profile == null || !profile.isManagedProfile()) {
754 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
755 }
756 if (profile.isQuietModeEnabled() != enableQuietMode) {
757 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800758 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000759 changed = true;
760 }
761 }
762 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000763 long identity = Binder.clearCallingIdentity();
764 try {
765 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800766 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100767 LocalServices.getService(ActivityManagerInternal.class)
768 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000769 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800770 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000771 }
772 } catch (RemoteException e) {
773 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
774 } finally {
775 Binder.restoreCallingIdentity(identity);
776 }
777
778 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
779 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000780 }
781 }
782
783 @Override
784 public boolean isQuietModeEnabled(int userHandle) {
785 synchronized (mPackagesLock) {
786 UserInfo info;
787 synchronized (mUsersLock) {
788 info = getUserInfoLU(userHandle);
789 }
790 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000791 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000792 }
793 return info.isQuietModeEnabled();
794 }
795 }
796
Kenny Guya52dc3e2014-02-11 15:33:14 +0000797 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100798 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100799 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600800 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100801 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100802 // if the user is already unlocked, no need to show a profile challenge
803 setQuietModeEnabled(userHandle, false);
804 return true;
805 }
806
807 long identity = Binder.clearCallingIdentity();
808 try {
809 // otherwise, we show a profile challenge to trigger decryption of the user
810 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
811 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100812 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
813 // lock, confirm screenlock page will know and show personal challenge, and unlock
814 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100815 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
816 userHandle);
817 if (unlockIntent == null) {
818 return false;
819 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100820 final Intent callBackIntent = new Intent(
821 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100822 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100823 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100824 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100825 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
826 callBackIntent.setPackage(mContext.getPackageName());
827 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
828 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
829 mContext,
830 0,
831 callBackIntent,
832 PendingIntent.FLAG_CANCEL_CURRENT |
833 PendingIntent.FLAG_ONE_SHOT |
834 PendingIntent.FLAG_IMMUTABLE);
835 // After unlocking the challenge, it will disable quiet mode and run the original
836 // intentSender
837 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100838 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
839 mContext.startActivity(unlockIntent);
840 } finally {
841 Binder.restoreCallingIdentity(identity);
842 }
843 return false;
844 }
845
846 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100847 public void setUserEnabled(int userId) {
848 checkManageUsersPermission("enable user");
849 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700850 UserInfo info;
851 synchronized (mUsersLock) {
852 info = getUserInfoLU(userId);
853 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100854 if (info != null && !info.isEnabled()) {
855 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800856 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100857 }
858 }
859 }
860
Andrew Scull85a63bc2016-10-24 13:47:47 +0100861 /**
862 * Evicts a user's CE key by stopping and restarting the user.
863 *
864 * The key is evicted automatically by the user controller when the user has stopped.
865 */
866 @Override
867 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
868 checkManageUsersPermission("evict CE key");
869 final IActivityManager am = ActivityManagerNative.getDefault();
870 final long identity = Binder.clearCallingIdentity();
871 try {
872 am.restartUserInBackground(userId);
873 } catch (RemoteException re) {
874 throw re.rethrowAsRuntimeException();
875 } finally {
876 Binder.restoreCallingIdentity(identity);
877 }
878 }
879
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100880 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700881 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700882 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000883 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700884 return userWithName(getUserInfoLU(userId));
885 }
886 }
887
888 /**
889 * Returns a UserInfo object with the name filled in, for Owner, or the original
890 * if the name is already set.
891 */
892 private UserInfo userWithName(UserInfo orig) {
893 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
894 UserInfo withName = new UserInfo(orig);
895 withName.name = getOwnerName();
896 return withName;
897 } else {
898 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000899 }
900 }
901
902 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000903 public int getManagedProfileBadge(@UserIdInt int userId) {
904 int callingUserId = UserHandle.getCallingUserId();
905 if (callingUserId != userId && !hasManageUsersPermission()) {
906 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
907 throw new SecurityException(
908 "You need MANAGE_USERS permission to: check if specified user a " +
909 "managed profile outside your profile group");
910 }
911 }
912 synchronized (mUsersLock) {
913 UserInfo userInfo = getUserInfoLU(userId);
914 return userInfo != null ? userInfo.profileBadge : 0;
915 }
916 }
917
918 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000919 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000920 int callingUserId = UserHandle.getCallingUserId();
921 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700922 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700923 throw new SecurityException(
924 "You need MANAGE_USERS permission to: check if specified user a " +
925 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000926 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000927 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700928 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700929 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000930 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700931 }
932 }
933
Amith Yamasani71e6c692013-03-24 17:39:28 -0700934 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700935 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800936 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700937 return mLocalService.isUserUnlockingOrUnlocked(userId);
938 }
939
940 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800941 public boolean isUserUnlocked(int userId) {
942 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
943 return mLocalService.isUserUnlockingOrUnlocked(userId);
944 }
945
946 @Override
947 public boolean isUserRunning(int userId) {
948 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
949 return mLocalService.isUserRunning(userId);
950 }
951
952 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
953 int callingUserId = UserHandle.getCallingUserId();
954 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
955 hasManageUsersPermission()) {
956 return;
957 }
958 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
959 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
960 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
961 + "to: check " + name);
962 }
963 }
964
965 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700966 public boolean isDemoUser(int userId) {
967 int callingUserId = UserHandle.getCallingUserId();
968 if (callingUserId != userId && !hasManageUsersPermission()) {
969 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
970 + " is a demo user");
971 }
972 synchronized (mUsersLock) {
973 UserInfo userInfo = getUserInfoLU(userId);
974 return userInfo != null && userInfo.isDemo();
975 }
976 }
977
978 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700979 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700980 synchronized (mUsersLock) {
981 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700982 }
983 }
984
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700985 @Override
986 public boolean canHaveRestrictedProfile(int userId) {
987 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700988 synchronized (mUsersLock) {
989 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700990 if (userInfo == null || !userInfo.canHaveProfile()) {
991 return false;
992 }
993 if (!userInfo.isAdmin()) {
994 return false;
995 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800996 // restricted profile can be created if there is no DO set and the admin user has no PO;
997 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700998 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700999 }
1000
Amith Yamasani195263742012-08-21 15:40:12 -07001001 /*
1002 * Should be locked on mUsers before calling this.
1003 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001004 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001005 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001006 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001007 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001008 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1009 return null;
1010 }
Amith Yamasani12747872015-12-07 14:19:49 -08001011 return userData != null ? userData.info : null;
1012 }
1013
1014 private UserData getUserDataLU(int userId) {
1015 final UserData userData = mUsers.get(userId);
1016 // If it is partial and not in the process of being removed, return as unknown user.
1017 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1018 return null;
1019 }
1020 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001021 }
1022
Fyodor Kupolov82402752015-10-28 14:54:51 -07001023 /**
1024 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1025 * <p>No permissions checking or any addition checks are made</p>
1026 */
1027 private UserInfo getUserInfoNoChecks(int userId) {
1028 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001029 final UserData userData = mUsers.get(userId);
1030 return userData != null ? userData.info : null;
1031 }
1032 }
1033
1034 /**
1035 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1036 * <p>No permissions checking or any addition checks are made</p>
1037 */
1038 private UserData getUserDataNoChecks(int userId) {
1039 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001040 return mUsers.get(userId);
1041 }
1042 }
1043
Amith Yamasani236b2b52015-08-18 14:32:14 -07001044 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001045 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001046 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001047 }
1048
Amith Yamasani258848d2012-08-10 17:06:33 -07001049 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001050 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001051 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001052 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001053 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001054 UserData userData = getUserDataNoChecks(userId);
1055 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001056 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1057 return;
1058 }
Amith Yamasani12747872015-12-07 14:19:49 -08001059 if (name != null && !name.equals(userData.info.name)) {
1060 userData.info.name = name;
1061 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001062 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001063 }
1064 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001065 if (changed) {
1066 sendUserInfoChangedBroadcast(userId);
1067 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001068 }
1069
Amith Yamasani258848d2012-08-10 17:06:33 -07001070 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001071 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001072 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001073 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1074 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1075 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001076 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001077 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001078 }
1079
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001080
1081
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001082 private void sendUserInfoChangedBroadcast(int userId) {
1083 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1084 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1085 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001086 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001087 }
1088
Amith Yamasani258848d2012-08-10 17:06:33 -07001089 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001090 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001091 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001092 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001093 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1094 if (targetUserInfo == null || targetUserInfo.partial) {
1095 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001096 return null;
1097 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001098
1099 final int callingUserId = UserHandle.getCallingUserId();
1100 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1101 final int targetGroupId = targetUserInfo.profileGroupId;
1102 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1103 && callingGroupId == targetGroupId);
1104 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001105 checkManageUsersPermission("get the icon of a user who is not related");
1106 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001107
1108 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001109 return null;
1110 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001111 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001112 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001113
1114 try {
1115 return ParcelFileDescriptor.open(
1116 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1117 } catch (FileNotFoundException e) {
1118 Log.e(LOG_TAG, "Couldn't find icon file", e);
1119 }
1120 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001121 }
1122
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001123 public void makeInitialized(int userId) {
1124 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001125 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001126 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001127 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001128 userData = mUsers.get(userId);
1129 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001130 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001131 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001132 }
Amith Yamasani12747872015-12-07 14:19:49 -08001133 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1134 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001135 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001136 }
1137 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001138 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001139 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001140 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001141 }
1142
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001143 /**
1144 * If default guest restrictions haven't been initialized yet, add the basic
1145 * restrictions.
1146 */
1147 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001148 synchronized (mGuestRestrictions) {
1149 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001150 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001151 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001152 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1153 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1154 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001155 }
1156 }
1157
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001158 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301159 public Bundle getDefaultGuestRestrictions() {
1160 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001161 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301162 return new Bundle(mGuestRestrictions);
1163 }
1164 }
1165
1166 @Override
1167 public void setDefaultGuestRestrictions(Bundle restrictions) {
1168 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001169 synchronized (mGuestRestrictions) {
1170 mGuestRestrictions.clear();
1171 mGuestRestrictions.putAll(restrictions);
1172 }
1173 synchronized (mPackagesLock) {
1174 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301175 }
1176 }
1177
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001178 /**
1179 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1180 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001181 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001182 @Nullable Bundle global) {
1183 Preconditions.checkNotNull(local);
1184 boolean globalChanged = false;
1185 boolean localChanged;
1186 synchronized (mRestrictionsLock) {
1187 if (global != null) {
1188 // Update global.
1189 globalChanged = !UserRestrictionsUtils.areEqual(
1190 mDevicePolicyGlobalUserRestrictions, global);
1191 if (globalChanged) {
1192 mDevicePolicyGlobalUserRestrictions = global;
1193 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001194 // Remember the global restriction owner userId to be able to make a distinction
1195 // in getUserRestrictionSource on who set local policies.
1196 mGlobalRestrictionOwnerUserId = userId;
1197 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001198 if (mGlobalRestrictionOwnerUserId == userId) {
1199 // When profile owner sets restrictions it passes null global bundle and we
1200 // reset global restriction owner userId.
1201 // This means this user used to have DO, but now the DO is gone and the user
1202 // instead has PO.
1203 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1204 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001205 }
1206 {
1207 // Update local.
1208 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1209 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1210 if (localChanged) {
1211 mDevicePolicyLocalUserRestrictions.put(userId, local);
1212 }
1213 }
1214 }
1215 if (DBG) {
1216 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1217 + " global=" + global + (globalChanged ? " (changed)" : "")
1218 + " local=" + local + (localChanged ? " (changed)" : "")
1219 );
1220 }
1221 // Don't call them within the mRestrictionsLock.
1222 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001223 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001224 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001225 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001226 if (globalChanged) {
1227 writeUserListLP();
1228 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001229 }
1230
1231 synchronized (mRestrictionsLock) {
1232 if (globalChanged) {
1233 applyUserRestrictionsForAllUsersLR();
1234 } else if (localChanged) {
1235 applyUserRestrictionsLR(userId);
1236 }
1237 }
1238 }
1239
Makoto Onuki068c54a2015-10-13 14:34:03 -07001240 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001241 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001242 final Bundle baseRestrictions =
1243 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1244 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1245 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001246
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001247 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1248 // Common case first.
1249 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001250 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001251 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1252 UserRestrictionsUtils.merge(effective, global);
1253 UserRestrictionsUtils.merge(effective, local);
1254
Makoto Onuki068c54a2015-10-13 14:34:03 -07001255 return effective;
1256 }
1257
1258 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001259 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001260 if (DBG) {
1261 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1262 }
1263 mCachedEffectiveUserRestrictions.remove(userId);
1264 }
1265
1266 private Bundle getEffectiveUserRestrictions(int userId) {
1267 synchronized (mRestrictionsLock) {
1268 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1269 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001270 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001271 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1272 }
1273 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001274 }
1275 }
1276
Makoto Onuki068c54a2015-10-13 14:34:03 -07001277 /** @return a specific user restriction that's in effect currently. */
1278 @Override
1279 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001280 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1281 return false;
1282 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001283 Bundle restrictions = getEffectiveUserRestrictions(userId);
1284 return restrictions != null && restrictions.getBoolean(restrictionKey);
1285 }
1286
1287 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001288 * @hide
1289 *
1290 * Returns who set a user restriction on a user.
1291 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1292 * @param restrictionKey the string key representing the restriction
1293 * @param userId the id of the user for whom to retrieve the restrictions.
1294 * @return The source of user restriction. Any combination of
1295 * {@link UserManager#RESTRICTION_NOT_SET},
1296 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1297 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1298 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1299 */
1300 @Override
1301 public int getUserRestrictionSource(String restrictionKey, int userId) {
1302 checkManageUsersPermission("getUserRestrictionSource");
1303 int result = UserManager.RESTRICTION_NOT_SET;
1304
1305 // Shortcut for the most common case
1306 if (!hasUserRestriction(restrictionKey, userId)) {
1307 return result;
1308 }
1309
1310 if (hasBaseUserRestriction(restrictionKey, userId)) {
1311 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1312 }
1313
1314 synchronized(mRestrictionsLock) {
1315 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1316 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1317 && localRestrictions.getBoolean(restrictionKey)) {
1318 // Local restrictions may have been set by device owner the userId of which is
1319 // stored in mGlobalRestrictionOwnerUserId.
1320 if (mGlobalRestrictionOwnerUserId == userId) {
1321 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1322 } else {
1323 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1324 }
1325 }
1326 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1327 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1328 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1329 }
1330 }
1331
1332 return result;
1333 }
1334
1335 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001336 * @return UserRestrictions that are in effect currently. This always returns a new
1337 * {@link Bundle}.
1338 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001339 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001340 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001341 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001342 }
1343
1344 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001345 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1346 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001347 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1348 return false;
1349 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001350 synchronized (mRestrictionsLock) {
1351 Bundle bundle = mBaseUserRestrictions.get(userId);
1352 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1353 }
1354 }
1355
1356 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001357 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001358 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001359 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1360 return;
1361 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001362 synchronized (mRestrictionsLock) {
1363 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1364 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001365 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1366 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001367 newRestrictions.putBoolean(key, value);
1368
Fyodor Kupolov82402752015-10-28 14:54:51 -07001369 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001370 }
1371 }
1372
Makoto Onuki068c54a2015-10-13 14:34:03 -07001373 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001374 * Optionally updating user restrictions, calculate the effective user restrictions and also
1375 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001376 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001377 * @param newRestrictions User restrictions to set.
1378 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001379 * @param userId target user ID.
1380 */
1381 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001382 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001383 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001384
1385 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1386 mAppliedUserRestrictions.get(userId));
1387
1388 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001389 if (newRestrictions != null) {
1390 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001391 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1392
1393 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001394 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1395 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001396
1397 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1398 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001399 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001400 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001401 }
1402
Fyodor Kupolov82402752015-10-28 14:54:51 -07001403 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001404
Makoto Onuki759a7632015-10-28 16:43:10 -07001405 mCachedEffectiveUserRestrictions.put(userId, effective);
1406
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001407 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001408 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001409 debug("Applying user restrictions: userId=" + userId
1410 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001411 }
1412
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001413 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001414 mHandler.post(new Runnable() {
1415 @Override
1416 public void run() {
1417 try {
1418 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1419 } catch (RemoteException e) {
1420 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1421 }
1422 }
1423 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001424 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001425
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001426 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001427
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001428 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001429 }
1430
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001431 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001432 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001433 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1434 // actually, but we still need some kind of synchronization otherwise we might end up
1435 // calling listeners out-of-order, thus "LR".
1436
1437 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1438 return;
1439 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001440
1441 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1442 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1443
1444 mHandler.post(new Runnable() {
1445 @Override
1446 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001447 UserRestrictionsUtils.applyUserRestrictions(
1448 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449
Makoto Onukid45a4a22015-11-02 17:17:38 -08001450 final UserRestrictionsListener[] listeners;
1451 synchronized (mUserRestrictionsListeners) {
1452 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1453 mUserRestrictionsListeners.toArray(listeners);
1454 }
1455 for (int i = 0; i < listeners.length; i++) {
1456 listeners[i].onUserRestrictionsChanged(userId,
1457 newRestrictionsFinal, prevRestrictionsFinal);
1458 }
1459 }
1460 });
1461 }
1462
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001463 // Package private for the inner class.
1464 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001465 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001466 }
1467
1468 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001469 // Package private for the inner class.
1470 void applyUserRestrictionsForAllUsersLR() {
1471 if (DBG) {
1472 debug("applyUserRestrictionsForAllUsersLR");
1473 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001474 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001475 mCachedEffectiveUserRestrictions.clear();
1476
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001477 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001478 // it on a handler.
1479 final Runnable r = new Runnable() {
1480 @Override
1481 public void run() {
1482 // Then get the list of running users.
1483 final int[] runningUsers;
1484 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001485 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001486 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001487 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001488 return;
1489 }
1490 // Then re-calculate the effective restrictions and apply, only for running users.
1491 // It's okay if a new user has started after the getRunningUserIds() call,
1492 // because we'll do the same thing (re-calculate the restrictions and apply)
1493 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001494 synchronized (mRestrictionsLock) {
1495 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001496 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001497 }
1498 }
1499 }
1500 };
1501 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001502 }
1503
Amith Yamasani258848d2012-08-10 17:06:33 -07001504 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001505 * Check if we've hit the limit of how many users can be created.
1506 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001507 private boolean isUserLimitReached() {
1508 int count;
1509 synchronized (mUsersLock) {
1510 count = getAliveUsersExcludingGuestsCountLU();
1511 }
1512 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001513 }
1514
1515 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001516 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001517 checkManageUsersPermission("check if more managed profiles can be added.");
1518 if (ActivityManager.isLowRamDeviceStatic()) {
1519 return false;
1520 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001521 if (!mContext.getPackageManager().hasSystemFeature(
1522 PackageManager.FEATURE_MANAGED_USERS)) {
1523 return false;
1524 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001525 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001526 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1527 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001528 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001529 return false;
1530 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001531 synchronized(mUsersLock) {
1532 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001533 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001534 return false;
1535 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001536 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1537 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001538 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001539 return usersCountAfterRemoving == 1
1540 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001541 }
1542 }
1543
Fyodor Kupolov82402752015-10-28 14:54:51 -07001544 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001545 int aliveUserCount = 0;
1546 final int totalUserCount = mUsers.size();
1547 // Skip over users being removed
1548 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001549 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001550 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001551 aliveUserCount++;
1552 }
1553 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001554 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001555 }
1556
1557 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001558 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001559 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1560 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1561 * permissions can make certain calls to the UserManager.
1562 *
1563 * @param message used as message if SecurityException is thrown
1564 * @throws SecurityException if the caller does not have enough privilege.
1565 */
1566 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1567 final int uid = Binder.getCallingUid();
1568 if (uid != Process.SYSTEM_UID && uid != 0
1569 && ActivityManager.checkComponentPermission(
1570 Manifest.permission.MANAGE_USERS,
1571 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1572 && ActivityManager.checkComponentPermission(
1573 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1574 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1575 throw new SecurityException(
1576 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1577 + message);
1578 }
1579 }
1580
1581 /**
1582 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001583 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001584 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001585 *
1586 * @param message used as message if SecurityException is thrown
1587 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001588 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001589 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001590 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001591 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001592 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1593 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001594 }
1595
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001596 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001597 * Enforces that only the system UID or root's UID or apps that have the
1598 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1599 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1600 * can make certain calls to the UserManager.
1601 *
1602 * @param message used as message if SecurityException is thrown
1603 * @throws SecurityException if the caller is not system or root
1604 * @see #hasManageOrCreateUsersPermission()
1605 */
1606 private static final void checkManageOrCreateUsersPermission(String message) {
1607 if (!hasManageOrCreateUsersPermission()) {
1608 throw new SecurityException(
1609 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1610 }
1611 }
1612
1613 /**
1614 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1615 * to create user/profiles other than what is allowed for
1616 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1617 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1618 */
1619 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1620 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1621 if (!hasManageOrCreateUsersPermission()) {
1622 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1623 + "permission to create an user with flags: " + creationFlags);
1624 }
1625 } else if (!hasManageUsersPermission()) {
1626 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1627 + " with flags: " + creationFlags);
1628 }
1629 }
1630
1631 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001632 * @return whether the calling UID is system UID or root's UID or the calling app has the
1633 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1634 */
1635 private static final boolean hasManageUsersPermission() {
1636 final int callingUid = Binder.getCallingUid();
1637 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1638 || callingUid == Process.ROOT_UID
1639 || ActivityManager.checkComponentPermission(
1640 android.Manifest.permission.MANAGE_USERS,
1641 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1642 }
1643
1644 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001645 * @return whether the calling UID is system UID or root's UID or the calling app has the
1646 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1647 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1648 */
1649 private static final boolean hasManageOrCreateUsersPermission() {
1650 final int callingUid = Binder.getCallingUid();
1651 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1652 || callingUid == Process.ROOT_UID
1653 || ActivityManager.checkComponentPermission(
1654 android.Manifest.permission.MANAGE_USERS,
1655 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1656 || ActivityManager.checkComponentPermission(
1657 android.Manifest.permission.CREATE_USERS,
1658 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1659 }
1660
1661 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001662 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1663 * UserManager.
1664 *
1665 * @param message used as message if SecurityException is thrown
1666 * @throws SecurityException if the caller is not system or root
1667 */
1668 private static void checkSystemOrRoot(String message) {
1669 final int uid = Binder.getCallingUid();
1670 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1671 throw new SecurityException("Only system may: " + message);
1672 }
1673 }
1674
Fyodor Kupolov82402752015-10-28 14:54:51 -07001675 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001676 try {
1677 File dir = new File(mUsersDir, Integer.toString(info.id));
1678 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001679 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001680 if (!dir.exists()) {
1681 dir.mkdir();
1682 FileUtils.setPermissions(
1683 dir.getPath(),
1684 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1685 -1, -1);
1686 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001687 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001688 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001689 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001690 info.iconPath = file.getAbsolutePath();
1691 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001692 try {
1693 os.close();
1694 } catch (IOException ioe) {
1695 // What the ... !
1696 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001697 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001698 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001699 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001700 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001701 }
1702
Amith Yamasani0b285492011-04-14 17:35:23 -07001703 /**
1704 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1705 * cache it elsewhere.
1706 * @return the array of user ids.
1707 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001708 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001709 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001710 return mUserIds;
1711 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001712 }
1713
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001714 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001715 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001716 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001717 return;
1718 }
1719 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001720 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001721 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001722 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001723 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001724 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001725 int type;
1726 while ((type = parser.next()) != XmlPullParser.START_TAG
1727 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001728 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001729 }
1730
1731 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001732 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001733 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001734 return;
1735 }
1736
Amith Yamasani2a003292012-08-14 18:25:45 -07001737 mNextSerialNumber = -1;
1738 if (parser.getName().equals(TAG_USERS)) {
1739 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1740 if (lastSerialNumber != null) {
1741 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1742 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001743 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1744 if (versionNumber != null) {
1745 mUserVersion = Integer.parseInt(versionNumber);
1746 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001747 }
1748
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001749 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1750
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001751 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301752 if (type == XmlPullParser.START_TAG) {
1753 final String name = parser.getName();
1754 if (name.equals(TAG_USER)) {
1755 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001756
Amith Yamasani12747872015-12-07 14:19:49 -08001757 UserData userData = readUserLP(Integer.parseInt(id));
1758
1759 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001760 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001761 mUsers.put(userData.info.id, userData);
1762 if (mNextSerialNumber < 0
1763 || mNextSerialNumber <= userData.info.id) {
1764 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001765 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301766 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001767 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301768 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001769 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1770 && type != XmlPullParser.END_TAG) {
1771 if (type == XmlPullParser.START_TAG) {
1772 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001773 synchronized (mGuestRestrictions) {
1774 UserRestrictionsUtils
1775 .readRestrictions(parser, mGuestRestrictions);
1776 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001777 }
1778 break;
1779 }
1780 }
Makoto Onuki82de3002016-09-30 09:58:15 -07001781 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1782 UserRestrictionsUtils.readRestrictions(parser,
1783 newDevicePolicyGlobalUserRestrictions);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001784 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1785 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1786 if (ownerUserId != null) {
1787 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1788 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001789 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001790 }
1791 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001792 synchronized (mRestrictionsLock) {
1793 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1794 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001795 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001796 upgradeIfNecessaryLP();
1797 } catch (IOException | XmlPullParserException e) {
1798 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001799 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001800 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001801 }
1802 }
1803
Amith Yamasani6f34b412012-10-22 18:19:27 -07001804 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001805 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001806 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001807 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001808 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001809 int userVersion = mUserVersion;
1810 if (userVersion < 1) {
1811 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001812 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1813 if ("Primary".equals(userData.info.name)) {
1814 userData.info.name =
1815 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1816 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001817 }
1818 userVersion = 1;
1819 }
1820
Amith Yamasanibc9625052012-11-15 14:39:18 -08001821 if (userVersion < 2) {
1822 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001823 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1824 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1825 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1826 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001827 }
1828 userVersion = 2;
1829 }
1830
Amith Yamasani350962c2013-08-06 11:18:53 -07001831
Amith Yamasani5e486f52013-08-07 11:06:44 -07001832 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001833 userVersion = 4;
1834 }
1835
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001836 if (userVersion < 5) {
1837 initDefaultGuestRestrictions();
1838 userVersion = 5;
1839 }
1840
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001841 if (userVersion < 6) {
1842 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001843 synchronized (mUsersLock) {
1844 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001845 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001846 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001847 if (!splitSystemUser && userData.info.isRestricted()
1848 && (userData.info.restrictedProfileParentId
1849 == UserInfo.NO_PROFILE_GROUP_ID)) {
1850 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1851 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001852 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001853 }
1854 }
1855 userVersion = 6;
1856 }
1857
Amith Yamasani6f34b412012-10-22 18:19:27 -07001858 if (userVersion < USER_VERSION) {
1859 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1860 + USER_VERSION);
1861 } else {
1862 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001863
1864 if (originalVersion < mUserVersion) {
1865 writeUserListLP();
1866 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001867 }
1868 }
1869
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001870 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001871 int flags = UserInfo.FLAG_INITIALIZED;
1872 // In split system user mode, the admin and primary flags are assigned to the first human
1873 // user.
1874 if (!UserManager.isSplitSystemUser()) {
1875 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1876 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001877 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001878 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001879 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001880 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001881 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001882
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001883 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001884 try {
1885 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1886 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1887 for (String userRestriction : defaultFirstUserRestrictions) {
1888 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1889 restrictions.putBoolean(userRestriction, true);
1890 }
1891 }
1892 } catch (Resources.NotFoundException e) {
1893 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1894 }
1895
Makoto Onuki068c54a2015-10-13 14:34:03 -07001896 synchronized (mRestrictionsLock) {
1897 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1898 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001899
Fyodor Kupolov82402752015-10-28 14:54:51 -07001900 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001901 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001902
Amith Yamasani12747872015-12-07 14:19:49 -08001903 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001904 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001905 }
1906
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001907 private String getOwnerName() {
1908 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1909 }
1910
Amith Yamasani12747872015-12-07 14:19:49 -08001911 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001912 if (DBG) {
1913 debug("scheduleWriteUser");
1914 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001915 // No need to wrap it within a lock -- worst case, we'll just post the same message
1916 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001917 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1918 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001919 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1920 }
1921 }
1922
Amith Yamasani12747872015-12-07 14:19:49 -08001923 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001924 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001925 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001926 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001927 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001928 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001929 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001930 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001931 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001932 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001933 userFile.finishWrite(fos);
1934 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001935 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001936 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001937 }
1938 }
1939
1940 /*
Kenny Guy02c89902016-11-15 19:36:38 +00001941 * Writes the user file in this format:
1942 *
1943 * <user flags="20039023" id="0">
1944 * <name>Primary</name>
1945 * </user>
1946 */
1947 @VisibleForTesting
1948 void writeUserLP(UserData userData, OutputStream os)
1949 throws IOException, XmlPullParserException {
1950 // XmlSerializer serializer = XmlUtils.serializerInstance();
1951 final XmlSerializer serializer = new FastXmlSerializer();
1952 serializer.setOutput(os, StandardCharsets.UTF_8.name());
1953 serializer.startDocument(null, true);
1954 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1955
1956 final UserInfo userInfo = userData.info;
1957 serializer.startTag(null, TAG_USER);
1958 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
1959 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
1960 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
1961 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1962 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1963 Long.toString(userInfo.lastLoggedInTime));
1964 if (userInfo.lastLoggedInFingerprint != null) {
1965 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1966 userInfo.lastLoggedInFingerprint);
1967 }
1968 if (userInfo.iconPath != null) {
1969 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1970 }
1971 if (userInfo.partial) {
1972 serializer.attribute(null, ATTR_PARTIAL, "true");
1973 }
1974 if (userInfo.guestToRemove) {
1975 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1976 }
1977 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1978 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1979 Integer.toString(userInfo.profileGroupId));
1980 }
1981 serializer.attribute(null, ATTR_PROFILE_BADGE,
1982 Integer.toString(userInfo.profileBadge));
1983 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1984 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1985 Integer.toString(userInfo.restrictedProfileParentId));
1986 }
1987 // Write seed data
1988 if (userData.persistSeedData) {
1989 if (userData.seedAccountName != null) {
1990 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1991 }
1992 if (userData.seedAccountType != null) {
1993 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1994 }
1995 }
1996 if (userInfo.name != null) {
1997 serializer.startTag(null, TAG_NAME);
1998 serializer.text(userInfo.name);
1999 serializer.endTag(null, TAG_NAME);
2000 }
2001 synchronized (mRestrictionsLock) {
2002 UserRestrictionsUtils.writeRestrictions(serializer,
2003 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2004 UserRestrictionsUtils.writeRestrictions(serializer,
2005 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2006 TAG_DEVICE_POLICY_RESTRICTIONS);
2007 }
2008
2009 if (userData.account != null) {
2010 serializer.startTag(null, TAG_ACCOUNT);
2011 serializer.text(userData.account);
2012 serializer.endTag(null, TAG_ACCOUNT);
2013 }
2014
2015 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2016 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2017 userData.seedAccountOptions.saveToXml(serializer);
2018 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2019 }
2020
2021 serializer.endTag(null, TAG_USER);
2022
2023 serializer.endDocument();
2024 }
2025
2026 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002027 * Writes the user list file in this format:
2028 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002029 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002030 * <user id="0"></user>
2031 * <user id="2"></user>
2032 * </users>
2033 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002034 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002035 if (DBG) {
2036 debug("writeUserList");
2037 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002038 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002039 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002040 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002041 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002042 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2043
2044 // XmlSerializer serializer = XmlUtils.serializerInstance();
2045 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002046 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002047 serializer.startDocument(null, true);
2048 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2049
2050 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002051 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002052 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002053
Adam Lesinskieddeb492014-09-08 17:50:03 -07002054 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002055 synchronized (mGuestRestrictions) {
2056 UserRestrictionsUtils
2057 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2058 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302059 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002060 synchronized (mRestrictionsLock) {
2061 UserRestrictionsUtils.writeRestrictions(serializer,
2062 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
2063 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002064 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
2065 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
2066 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002067 int[] userIdsToWrite;
2068 synchronized (mUsersLock) {
2069 userIdsToWrite = new int[mUsers.size()];
2070 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002071 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002072 userIdsToWrite[i] = user.id;
2073 }
2074 }
2075 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002076 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002077 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002078 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002079 }
2080
2081 serializer.endTag(null, TAG_USERS);
2082
2083 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002084 userListFile.finishWrite(fos);
2085 } catch (Exception e) {
2086 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002087 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002088 }
2089 }
2090
Amith Yamasani12747872015-12-07 14:19:49 -08002091 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002092 FileInputStream fis = null;
2093 try {
2094 AtomicFile userFile =
2095 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2096 fis = userFile.openRead();
2097 return readUserLP(id, fis);
2098 } catch (IOException ioe) {
2099 Slog.e(LOG_TAG, "Error reading user list");
2100 } catch (XmlPullParserException pe) {
2101 Slog.e(LOG_TAG, "Error reading user list");
2102 } finally {
2103 IoUtils.closeQuietly(fis);
2104 }
2105 return null;
2106 }
2107
2108 @VisibleForTesting
2109 UserData readUserLP(int id, InputStream is) throws IOException,
2110 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002111 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002112 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002113 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002114 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002115 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002116 long creationTime = 0L;
2117 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002118 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002119 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002120 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002121 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002122 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002123 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002124 boolean persistSeedData = false;
2125 String seedAccountName = null;
2126 String seedAccountType = null;
2127 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002128 Bundle baseRestrictions = new Bundle();
2129 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002130
Kenny Guy02c89902016-11-15 19:36:38 +00002131 XmlPullParser parser = Xml.newPullParser();
2132 parser.setInput(is, StandardCharsets.UTF_8.name());
2133 int type;
2134 while ((type = parser.next()) != XmlPullParser.START_TAG
2135 && type != XmlPullParser.END_DOCUMENT) {
2136 // Skip
2137 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002138
Kenny Guy02c89902016-11-15 19:36:38 +00002139 if (type != XmlPullParser.START_TAG) {
2140 Slog.e(LOG_TAG, "Unable to read user " + id);
2141 return null;
2142 }
2143
2144 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2145 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2146 if (storedId != id) {
2147 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002148 return null;
2149 }
Kenny Guy02c89902016-11-15 19:36:38 +00002150 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2151 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2152 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2153 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2154 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2155 lastLoggedInFingerprint = parser.getAttributeValue(null,
2156 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2157 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2158 UserInfo.NO_PROFILE_GROUP_ID);
2159 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2160 restrictedProfileParentId = readIntAttribute(parser,
2161 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2162 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2163 if ("true".equals(valueString)) {
2164 partial = true;
2165 }
2166 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2167 if ("true".equals(valueString)) {
2168 guestToRemove = true;
2169 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002170
Kenny Guy02c89902016-11-15 19:36:38 +00002171 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2172 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2173 if (seedAccountName != null || seedAccountType != null) {
2174 persistSeedData = true;
2175 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002176
Kenny Guy02c89902016-11-15 19:36:38 +00002177 int outerDepth = parser.getDepth();
2178 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2179 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2180 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2181 continue;
2182 }
2183 String tag = parser.getName();
2184 if (TAG_NAME.equals(tag)) {
2185 type = parser.next();
2186 if (type == XmlPullParser.TEXT) {
2187 name = parser.getText();
2188 }
2189 } else if (TAG_RESTRICTIONS.equals(tag)) {
2190 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2191 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2192 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
2193 } else if (TAG_ACCOUNT.equals(tag)) {
2194 type = parser.next();
2195 if (type == XmlPullParser.TEXT) {
2196 account = parser.getText();
2197 }
2198 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2199 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002200 persistSeedData = true;
2201 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002202 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002203 }
Kenny Guy02c89902016-11-15 19:36:38 +00002204
2205 // Create the UserInfo object that gets passed around
2206 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2207 userInfo.serialNumber = serialNumber;
2208 userInfo.creationTime = creationTime;
2209 userInfo.lastLoggedInTime = lastLoggedInTime;
2210 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2211 userInfo.partial = partial;
2212 userInfo.guestToRemove = guestToRemove;
2213 userInfo.profileGroupId = profileGroupId;
2214 userInfo.profileBadge = profileBadge;
2215 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2216
2217 // Create the UserData object that's internal to this class
2218 UserData userData = new UserData();
2219 userData.info = userInfo;
2220 userData.account = account;
2221 userData.seedAccountName = seedAccountName;
2222 userData.seedAccountType = seedAccountType;
2223 userData.persistSeedData = persistSeedData;
2224 userData.seedAccountOptions = seedAccountOptions;
2225
2226 synchronized (mRestrictionsLock) {
2227 mBaseUserRestrictions.put(id, baseRestrictions);
2228 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2229 }
2230 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002231 }
2232
Amith Yamasani920ace02012-09-20 22:15:37 -07002233 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2234 String valueString = parser.getAttributeValue(null, attr);
2235 if (valueString == null) return defaultValue;
2236 try {
2237 return Integer.parseInt(valueString);
2238 } catch (NumberFormatException nfe) {
2239 return defaultValue;
2240 }
2241 }
2242
2243 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2244 String valueString = parser.getAttributeValue(null, attr);
2245 if (valueString == null) return defaultValue;
2246 try {
2247 return Long.parseLong(valueString);
2248 } catch (NumberFormatException nfe) {
2249 return defaultValue;
2250 }
2251 }
2252
Amith Yamasanib82add22013-07-09 11:24:44 -07002253 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002254 * Removes the app restrictions file for a specific package and user id, if it exists.
2255 */
2256 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2257 synchronized (mPackagesLock) {
2258 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002259 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002260 if (resFile.exists()) {
2261 resFile.delete();
2262 }
2263 }
2264 }
2265
Kenny Guya52dc3e2014-02-11 15:33:14 +00002266 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002267 public UserInfo createProfileForUser(String name, int flags, int userId,
2268 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002269 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002270 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002271 }
2272
Amith Yamasani258848d2012-08-10 17:06:33 -07002273 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002274 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2275 String[] disallowedPackages) {
2276 checkManageOrCreateUsersPermission(flags);
2277 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2278 }
2279
2280 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002281 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002282 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002283 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002284 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002285
Jessica Hummelbe81c802014-04-22 15:49:22 +01002286 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002287 return createUserInternal(name, flags, parentId, null);
2288 }
2289
2290 private UserInfo createUserInternal(String name, int flags, int parentId,
2291 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002292 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2293 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2294 : UserManager.DISALLOW_ADD_USER;
2295 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2296 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002297 return null;
2298 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002299 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2300 }
2301
2302 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2303 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002304 DeviceStorageMonitorInternal dsm = LocalServices
2305 .getService(DeviceStorageMonitorInternal.class);
2306 if (dsm.isMemoryLow()) {
2307 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2308 return null;
2309 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002310 if (ActivityManager.isLowRamDeviceStatic()) {
2311 return null;
2312 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002313 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002314 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002315 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002316 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002317 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002318 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002319 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002320 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002321 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002322 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002323 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002324 if (parentId != UserHandle.USER_NULL) {
2325 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002326 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002327 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002328 if (parent == null) return null;
2329 }
2330 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2331 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2332 return null;
2333 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002334 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2335 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002336 // been reached, cannot add a user.
2337 return null;
2338 }
2339 // If we're adding a guest and there already exists one, bail.
2340 if (isGuest && findCurrentGuestUser() != null) {
2341 return null;
2342 }
2343 // In legacy mode, restricted profile's parent can only be the owner user
2344 if (isRestricted && !UserManager.isSplitSystemUser()
2345 && (parentId != UserHandle.USER_SYSTEM)) {
2346 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2347 return null;
2348 }
2349 if (isRestricted && UserManager.isSplitSystemUser()) {
2350 if (parent == null) {
2351 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2352 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002353 return null;
2354 }
Amith Yamasani12747872015-12-07 14:19:49 -08002355 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002356 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2357 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002358 return null;
2359 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002360 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002361 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2362 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002363 Log.e(LOG_TAG,
2364 "Ephemeral users are supported on split-system-user systems only.");
2365 return null;
2366 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002367 // In split system user mode, we assign the first human user the primary flag.
2368 // And if there is no device owner, we also assign the admin flag to primary user.
2369 if (UserManager.isSplitSystemUser()
2370 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2371 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002372 synchronized (mUsersLock) {
2373 if (!mIsDeviceManaged) {
2374 flags |= UserInfo.FLAG_ADMIN;
2375 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002376 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002377 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002378
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002379 userId = getNextAvailableId();
2380 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002381 boolean ephemeralGuests = Resources.getSystem()
2382 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002383
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002384 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002385 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2386 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2387 || (parent != null && parent.info.isEphemeral())) {
2388 flags |= UserInfo.FLAG_EPHEMERAL;
2389 }
2390
2391 userInfo = new UserInfo(userId, name, null, flags);
2392 userInfo.serialNumber = mNextSerialNumber++;
2393 long now = System.currentTimeMillis();
2394 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2395 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002396 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002397 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2398 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2399 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002400 userData = new UserData();
2401 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002402 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002403 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002404 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002405 writeUserListLP();
2406 if (parent != null) {
2407 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002408 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2409 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002410 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002411 }
Amith Yamasani12747872015-12-07 14:19:49 -08002412 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002413 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002414 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2415 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002416 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002417 }
Amith Yamasani12747872015-12-07 14:19:49 -08002418 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002419 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002420 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002421 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002422 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002423 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002424 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002425 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002426 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002427 userInfo.partial = false;
2428 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002429 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002430 }
2431 updateUserIds();
2432 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002433 if (isGuest) {
2434 synchronized (mGuestRestrictions) {
2435 restrictions.putAll(mGuestRestrictions);
2436 }
2437 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002438 synchronized (mRestrictionsLock) {
2439 mBaseUserRestrictions.append(userId, restrictions);
2440 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002441 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002442 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2443 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2444 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2445 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002446 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002447 } finally {
2448 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002449 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002450 return userInfo;
2451 }
2452
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002453 @VisibleForTesting
2454 UserData putUserInfo(UserInfo userInfo) {
2455 final UserData userData = new UserData();
2456 userData.info = userInfo;
2457 synchronized (mUsers) {
2458 mUsers.put(userInfo.id, userData);
2459 }
2460 return userData;
2461 }
2462
2463 @VisibleForTesting
2464 void removeUserInfo(int userId) {
2465 synchronized (mUsers) {
2466 mUsers.remove(userId);
2467 }
2468 }
2469
Amith Yamasani0b285492011-04-14 17:35:23 -07002470 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002471 * @hide
2472 */
Amith Yamasani12747872015-12-07 14:19:49 -08002473 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002474 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002475 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002476 final UserInfo user = createProfileForUser(
2477 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002478 if (user == null) {
2479 return null;
2480 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002481 long identity = Binder.clearCallingIdentity();
2482 try {
2483 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2484 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2485 // the putIntForUser() will fail.
2486 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2487 android.provider.Settings.Secure.LOCATION_MODE,
2488 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2489 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2490 } finally {
2491 Binder.restoreCallingIdentity(identity);
2492 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002493 return user;
2494 }
2495
2496 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002497 * Find the current guest user. If the Guest user is partial,
2498 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002499 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002500 private UserInfo findCurrentGuestUser() {
2501 synchronized (mUsersLock) {
2502 final int size = mUsers.size();
2503 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002504 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002505 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2506 return user;
2507 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002508 }
2509 }
2510 return null;
2511 }
2512
2513 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002514 * Mark this guest user for deletion to allow us to create another guest
2515 * and switch to that user before actually removing this guest.
2516 * @param userHandle the userid of the current guest
2517 * @return whether the user could be marked for deletion
2518 */
Amith Yamasani12747872015-12-07 14:19:49 -08002519 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002520 public boolean markGuestForDeletion(int userHandle) {
2521 checkManageUsersPermission("Only the system can remove users");
2522 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2523 UserManager.DISALLOW_REMOVE_USER, false)) {
2524 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2525 return false;
2526 }
2527
2528 long ident = Binder.clearCallingIdentity();
2529 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002530 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002531 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002532 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002533 userData = mUsers.get(userHandle);
2534 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002535 return false;
2536 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002537 }
Amith Yamasani12747872015-12-07 14:19:49 -08002538 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002539 return false;
2540 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002541 // We set this to a guest user that is to be removed. This is a temporary state
2542 // where we are allowed to add new Guest users, even if this one is still not
2543 // removed. This user will still show up in getUserInfo() calls.
2544 // If we don't get around to removing this Guest user, it will be purged on next
2545 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002546 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002547 // Mark it as disabled, so that it isn't returned any more when
2548 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002549 userData.info.flags |= UserInfo.FLAG_DISABLED;
2550 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002551 }
2552 } finally {
2553 Binder.restoreCallingIdentity(ident);
2554 }
2555 return true;
2556 }
2557
2558 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002559 * Removes a user and all data directories created for that user. This method should be called
2560 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002561 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002562 */
Amith Yamasani12747872015-12-07 14:19:49 -08002563 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002564 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002565 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002566 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002567
2568 final boolean isManagedProfile;
2569 synchronized (mUsersLock) {
2570 UserInfo userInfo = getUserInfoLU(userHandle);
2571 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2572 }
2573 String restriction = isManagedProfile
2574 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2575 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2576 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002577 return false;
2578 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002579 return removeUserUnchecked(userHandle);
2580 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002581
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002582 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002583 long ident = Binder.clearCallingIdentity();
2584 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002585 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002586 int currentUser = ActivityManager.getCurrentUser();
2587 if (currentUser == userHandle) {
2588 Log.w(LOG_TAG, "Current user cannot be removed");
2589 return false;
2590 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002591 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002592 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002593 userData = mUsers.get(userHandle);
2594 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002595 return false;
2596 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002597
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002598 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002599 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002600
Kenny Guyee58b4f2014-05-23 15:19:53 +01002601 try {
2602 mAppOpsService.removeUser(userHandle);
2603 } catch (RemoteException e) {
2604 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2605 }
2606 // Set this to a partially created user, so that the user will be purged
2607 // on next startup, in case the runtime stops now before stopping and
2608 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002609 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002610 // Mark it as disabled, so that it isn't returned any more when
2611 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002612 userData.info.flags |= UserInfo.FLAG_DISABLED;
2613 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002614 }
2615
Amith Yamasani12747872015-12-07 14:19:49 -08002616 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2617 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002618 // Send broadcast to notify system that the user removed was a
2619 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002620 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002621 }
2622
2623 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2624 int res;
2625 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002626 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002627 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002628 @Override
2629 public void userStopped(int userId) {
2630 finishRemoveUser(userId);
2631 }
2632 @Override
2633 public void userStopAborted(int userId) {
2634 }
2635 });
2636 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002637 return false;
2638 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002639 return res == ActivityManager.USER_OP_SUCCESS;
2640 } finally {
2641 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002642 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002643 }
2644
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002645 @VisibleForTesting
2646 void addRemovingUserIdLocked(int userId) {
2647 // We remember deleted user IDs to prevent them from being
2648 // reused during the current boot; they can still be reused
2649 // after a reboot or recycling of userIds.
2650 mRemovingUserIds.put(userId, true);
2651 mRecentlyRemovedIds.add(userId);
2652 // Keep LRU queue of recently removed IDs for recycling
2653 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2654 mRecentlyRemovedIds.removeFirst();
2655 }
2656 }
2657
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002658 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002659 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002660 // Let other services shutdown any activity and clean up their state before completely
2661 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002662 long ident = Binder.clearCallingIdentity();
2663 try {
2664 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2665 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002666 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2667 android.Manifest.permission.MANAGE_USERS,
2668
2669 new BroadcastReceiver() {
2670 @Override
2671 public void onReceive(Context context, Intent intent) {
2672 if (DBG) {
2673 Slog.i(LOG_TAG,
2674 "USER_REMOVED broadcast sent, cleaning up user data "
2675 + userHandle);
2676 }
2677 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002678 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002679 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002680 // Clean up any ActivityManager state
2681 LocalServices.getService(ActivityManagerInternal.class)
2682 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002683 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002684 }
2685 }.start();
2686 }
2687 },
2688
2689 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002690 } finally {
2691 Binder.restoreCallingIdentity(ident);
2692 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002693 }
2694
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002695 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002696 try {
2697 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2698 } catch (IllegalStateException e) {
2699 // This may be simply because the user was partially created.
2700 Slog.i(LOG_TAG,
2701 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2702 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002703
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002704 // Cleanup gatekeeper secure user id
2705 try {
2706 final IGateKeeperService gk = GateKeeper.getService();
2707 if (gk != null) {
2708 gk.clearSecureUserId(userHandle);
2709 }
2710 } catch (Exception ex) {
2711 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2712 }
2713
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002714 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002715 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002716
2717 // Clean up all data before removing metadata
2718 mPm.destroyUserData(userHandle,
2719 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2720
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002721 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002722 synchronized (mUsersLock) {
2723 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002724 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002725 }
2726 synchronized (mUserStates) {
2727 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002728 }
2729 synchronized (mRestrictionsLock) {
2730 mBaseUserRestrictions.remove(userHandle);
2731 mAppliedUserRestrictions.remove(userHandle);
2732 mCachedEffectiveUserRestrictions.remove(userHandle);
2733 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002734 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002735 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002736 synchronized (mPackagesLock) {
2737 writeUserListLP();
2738 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002739 // Remove user file
2740 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2741 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002742 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002743 if (RELEASE_DELETED_USER_ID) {
2744 synchronized (mUsers) {
2745 mRemovingUserIds.delete(userHandle);
2746 }
2747 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002748 }
2749
Kenny Guyf8d3a232014-05-15 16:09:52 +01002750 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002751 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002752 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2753 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002754 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002755 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002756 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002757 }
2758
Amith Yamasani2a003292012-08-14 18:25:45 -07002759 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002760 public Bundle getApplicationRestrictions(String packageName) {
2761 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2762 }
2763
2764 @Override
2765 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002766 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002767 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002768 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002769 }
2770 synchronized (mPackagesLock) {
2771 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002772 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002773 }
2774 }
2775
2776 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002777 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002778 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002779 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002780 if (restrictions != null) {
2781 restrictions.setDefusable(true);
2782 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002783 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002784 if (restrictions == null || restrictions.isEmpty()) {
2785 cleanAppRestrictionsForPackage(packageName, userId);
2786 } else {
2787 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002788 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002789 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002790 }
Robin Lee66e5d962014-04-09 16:44:21 +01002791
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002792 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2793 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2794 changeIntent.setPackage(packageName);
2795 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2796 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002797 }
2798
2799 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002800 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002801 try {
2802 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002803 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002804 } catch (NameNotFoundException nnfe) {
2805 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002806 } finally {
2807 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002808 }
2809 }
2810
Fyodor Kupolov82402752015-10-28 14:54:51 -07002811 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002812 AtomicFile restrictionsFile =
2813 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2814 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002815 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002816 }
2817
2818 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002819 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002820 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002821 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002822 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002823 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002824 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002825
2826 FileInputStream fis = null;
2827 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002828 fis = restrictionsFile.openRead();
2829 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002830 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002831 XmlUtils.nextElement(parser);
2832 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002833 Slog.e(LOG_TAG, "Unable to read restrictions file "
2834 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002835 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002836 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002837 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2838 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002839 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002840 } catch (IOException|XmlPullParserException e) {
2841 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002842 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002843 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002844 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002845 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002846 }
2847
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002848 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2849 XmlPullParser parser) throws XmlPullParserException, IOException {
2850 int type = parser.getEventType();
2851 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2852 String key = parser.getAttributeValue(null, ATTR_KEY);
2853 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2854 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2855 if (multiple != null) {
2856 values.clear();
2857 int count = Integer.parseInt(multiple);
2858 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2859 if (type == XmlPullParser.START_TAG
2860 && parser.getName().equals(TAG_VALUE)) {
2861 values.add(parser.nextText().trim());
2862 count--;
2863 }
2864 }
2865 String [] valueStrings = new String[values.size()];
2866 values.toArray(valueStrings);
2867 restrictions.putStringArray(key, valueStrings);
2868 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2869 restrictions.putBundle(key, readBundleEntry(parser, values));
2870 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2871 final int outerDepth = parser.getDepth();
2872 ArrayList<Bundle> bundleList = new ArrayList<>();
2873 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2874 Bundle childBundle = readBundleEntry(parser, values);
2875 bundleList.add(childBundle);
2876 }
2877 restrictions.putParcelableArray(key,
2878 bundleList.toArray(new Bundle[bundleList.size()]));
2879 } else {
2880 String value = parser.nextText().trim();
2881 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2882 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2883 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2884 restrictions.putInt(key, Integer.parseInt(value));
2885 } else {
2886 restrictions.putString(key, value);
2887 }
2888 }
2889 }
2890 }
2891
2892 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2893 throws IOException, XmlPullParserException {
2894 Bundle childBundle = new Bundle();
2895 final int outerDepth = parser.getDepth();
2896 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2897 readEntry(childBundle, values, parser);
2898 }
2899 return childBundle;
2900 }
2901
Fyodor Kupolov82402752015-10-28 14:54:51 -07002902 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002903 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002904 AtomicFile restrictionsFile = new AtomicFile(
2905 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002906 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002907 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002908 }
2909
2910 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002911 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002912 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002913 try {
2914 fos = restrictionsFile.startWrite();
2915 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2916
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002917 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002918 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002919 serializer.startDocument(null, true);
2920 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2921
2922 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002923 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002924 serializer.endTag(null, TAG_RESTRICTIONS);
2925
2926 serializer.endDocument();
2927 restrictionsFile.finishWrite(fos);
2928 } catch (Exception e) {
2929 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002930 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2931 }
2932 }
2933
2934 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2935 throws IOException {
2936 for (String key : restrictions.keySet()) {
2937 Object value = restrictions.get(key);
2938 serializer.startTag(null, TAG_ENTRY);
2939 serializer.attribute(null, ATTR_KEY, key);
2940
2941 if (value instanceof Boolean) {
2942 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2943 serializer.text(value.toString());
2944 } else if (value instanceof Integer) {
2945 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2946 serializer.text(value.toString());
2947 } else if (value == null || value instanceof String) {
2948 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2949 serializer.text(value != null ? (String) value : "");
2950 } else if (value instanceof Bundle) {
2951 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2952 writeBundle((Bundle) value, serializer);
2953 } else if (value instanceof Parcelable[]) {
2954 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2955 Parcelable[] array = (Parcelable[]) value;
2956 for (Parcelable parcelable : array) {
2957 if (!(parcelable instanceof Bundle)) {
2958 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2959 }
2960 serializer.startTag(null, TAG_ENTRY);
2961 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2962 writeBundle((Bundle) parcelable, serializer);
2963 serializer.endTag(null, TAG_ENTRY);
2964 }
2965 } else {
2966 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2967 String[] values = (String[]) value;
2968 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2969 for (String choice : values) {
2970 serializer.startTag(null, TAG_VALUE);
2971 serializer.text(choice != null ? choice : "");
2972 serializer.endTag(null, TAG_VALUE);
2973 }
2974 }
2975 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002976 }
2977 }
2978
2979 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002980 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002981 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002982 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002983 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002984 }
2985 }
2986
2987 @Override
2988 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002989 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002990 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002991 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002992 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002993 }
2994 // Not found
2995 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002996 }
2997 }
2998
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002999 @Override
3000 public long getUserCreationTime(int userHandle) {
3001 int callingUserId = UserHandle.getCallingUserId();
3002 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003003 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003004 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003005 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003006 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003007 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003008 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003009 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003010 }
3011 }
3012 }
3013 if (userInfo == null) {
3014 throw new SecurityException("userHandle can only be the calling user or a managed "
3015 + "profile associated with this user");
3016 }
3017 return userInfo.creationTime;
3018 }
3019
Amith Yamasani0b285492011-04-14 17:35:23 -07003020 /**
3021 * Caches the list of user ids in an array, adjusting the array size when necessary.
3022 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003023 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003024 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003025 synchronized (mUsersLock) {
3026 final int userSize = mUsers.size();
3027 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003028 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003029 num++;
3030 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003031 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003032 final int[] newUsers = new int[num];
3033 int n = 0;
3034 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003035 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003036 newUsers[n++] = mUsers.keyAt(i);
3037 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003038 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003039 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003040 }
3041 }
3042
3043 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003044 * Called right before a user is started. This gives us a chance to prepare
3045 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003046 */
3047 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003048 UserInfo userInfo = getUserInfo(userId);
3049 if (userInfo == null) {
3050 return;
3051 }
3052 final int userSerial = userInfo.serialNumber;
3053 // Migrate only if build fingerprints mismatch
3054 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003055 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003056 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003057
3058 if (userId != UserHandle.USER_SYSTEM) {
3059 synchronized (mRestrictionsLock) {
3060 applyUserRestrictionsLR(userId);
3061 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003062 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003063
3064 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003065 }
3066
3067 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003068 * Called right before a user is unlocked. This gives us a chance to prepare
3069 * app storage.
3070 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003071 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003072 UserInfo userInfo = getUserInfo(userId);
3073 if (userInfo == null) {
3074 return;
3075 }
3076 final int userSerial = userInfo.serialNumber;
3077 // Migrate only if build fingerprints mismatch
3078 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003079 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003080 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003081 }
3082
3083 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003084 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003085 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003086 * @param userId the user that was just foregrounded
3087 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003088 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003089 UserData userData = getUserDataNoChecks(userId);
3090 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003091 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3092 return;
3093 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003094
3095 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003096 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003097 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003098 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003099 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3100 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003101 }
3102
Amith Yamasanieb437d42016-04-29 09:31:25 -07003103 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07003104 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07003105 String demoLauncher =
3106 mContext.getResources().getString(
3107 com.android.internal.R.string.config_demoModeLauncherComponent);
3108 if (!TextUtils.isEmpty(demoLauncher)) {
3109 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07003110 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00003111 try {
3112 final IPackageManager iPm = AppGlobals.getPackageManager();
3113 iPm.setComponentEnabledSetting(componentToEnable,
3114 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3115 /* userId= */ userId);
3116 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3117 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3118 /* userId= */ userId, null);
3119 } catch (RemoteException re) {
3120 // Internal, shouldn't happen
3121 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003122 }
3123 }
3124 }
3125
Amith Yamasani920ace02012-09-20 22:15:37 -07003126 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003127 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003128 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003129 @VisibleForTesting
3130 int getNextAvailableId() {
3131 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003132 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003133 nextId = scanNextAvailableIdLocked();
3134 if (nextId >= 0) {
3135 return nextId;
3136 }
3137 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3138 // except most recently removed
3139 if (mRemovingUserIds.size() > 0) {
3140 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3141 mRemovingUserIds.clear();
3142 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3143 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003144 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003145 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003146 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003147 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003148 if (nextId < 0) {
3149 throw new IllegalStateException("No user id available!");
3150 }
3151 return nextId;
3152 }
3153
3154 private int scanNextAvailableIdLocked() {
3155 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3156 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3157 return i;
3158 }
3159 }
3160 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003161 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003162
Amith Yamasanifc95e702013-09-26 13:20:17 -07003163 private String packageToRestrictionsFileName(String packageName) {
3164 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3165 }
3166
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003167 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003168 * Enforce that serial number stored in user directory inode matches the
3169 * given expected value. Gracefully sets the serial number if currently
3170 * undefined.
3171 *
3172 * @throws IOException when problem extracting serial number, or serial
3173 * number is mismatched.
3174 */
3175 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003176 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3177 // When we're emulating FBE, the directory may have been chmod
3178 // 000'ed, meaning we can't read the serial number to enforce it;
3179 // instead of destroying the user, just log a warning.
3180 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3181 return;
3182 }
3183
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003184 final int foundSerial = getSerialNumber(file);
3185 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3186
3187 if (foundSerial == -1) {
3188 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3189 try {
3190 setSerialNumber(file, serialNumber);
3191 } catch (IOException e) {
3192 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3193 }
3194
3195 } else if (foundSerial != serialNumber) {
3196 throw new IOException("Found serial number " + foundSerial
3197 + " doesn't match expected " + serialNumber);
3198 }
3199 }
3200
3201 /**
3202 * Set serial number stored in user directory inode.
3203 *
3204 * @throws IOException if serial number was already set
3205 */
3206 private static void setSerialNumber(File file, int serialNumber)
3207 throws IOException {
3208 try {
3209 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3210 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3211 } catch (ErrnoException e) {
3212 throw e.rethrowAsIOException();
3213 }
3214 }
3215
3216 /**
3217 * Return serial number stored in user directory inode.
3218 *
3219 * @return parsed serial number, or -1 if not set
3220 */
3221 private static int getSerialNumber(File file) throws IOException {
3222 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003223 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3224 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003225 try {
3226 return Integer.parseInt(serial);
3227 } catch (NumberFormatException e) {
3228 throw new IOException("Bad serial number: " + serial);
3229 }
3230 } catch (ErrnoException e) {
3231 if (e.errno == OsConstants.ENODATA) {
3232 return -1;
3233 } else {
3234 throw e.rethrowAsIOException();
3235 }
3236 }
3237 }
3238
Amith Yamasani920ace02012-09-20 22:15:37 -07003239 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003240 public void setSeedAccountData(int userId, String accountName, String accountType,
3241 PersistableBundle accountOptions, boolean persist) {
3242 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3243 synchronized (mPackagesLock) {
3244 final UserData userData;
3245 synchronized (mUsersLock) {
3246 userData = getUserDataLU(userId);
3247 if (userData == null) {
3248 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3249 return;
3250 }
3251 userData.seedAccountName = accountName;
3252 userData.seedAccountType = accountType;
3253 userData.seedAccountOptions = accountOptions;
3254 userData.persistSeedData = persist;
3255 }
3256 if (persist) {
3257 writeUserLP(userData);
3258 }
3259 }
3260 }
3261
3262 @Override
3263 public String getSeedAccountName() throws RemoteException {
3264 checkManageUsersPermission("Cannot get seed account information");
3265 synchronized (mUsersLock) {
3266 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3267 return userData.seedAccountName;
3268 }
3269 }
3270
3271 @Override
3272 public String getSeedAccountType() throws RemoteException {
3273 checkManageUsersPermission("Cannot get seed account information");
3274 synchronized (mUsersLock) {
3275 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3276 return userData.seedAccountType;
3277 }
3278 }
3279
3280 @Override
3281 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3282 checkManageUsersPermission("Cannot get seed account information");
3283 synchronized (mUsersLock) {
3284 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3285 return userData.seedAccountOptions;
3286 }
3287 }
3288
3289 @Override
3290 public void clearSeedAccountData() throws RemoteException {
3291 checkManageUsersPermission("Cannot clear seed account information");
3292 synchronized (mPackagesLock) {
3293 UserData userData;
3294 synchronized (mUsersLock) {
3295 userData = getUserDataLU(UserHandle.getCallingUserId());
3296 if (userData == null) return;
3297 userData.clearSeedAccountData();
3298 }
3299 writeUserLP(userData);
3300 }
3301 }
3302
3303 @Override
3304 public boolean someUserHasSeedAccount(String accountName, String accountType)
3305 throws RemoteException {
3306 checkManageUsersPermission("Cannot check seed account information");
3307 synchronized (mUsersLock) {
3308 final int userSize = mUsers.size();
3309 for (int i = 0; i < userSize; i++) {
3310 final UserData data = mUsers.valueAt(i);
3311 if (data.info.isInitialized()) continue;
3312 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3313 continue;
3314 }
3315 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3316 continue;
3317 }
3318 return true;
3319 }
3320 }
3321 return false;
3322 }
3323
3324 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003325 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003326 FileDescriptor err, String[] args, ShellCallback callback,
3327 ResultReceiver resultReceiver) {
3328 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003329 }
3330
3331 int onShellCommand(Shell shell, String cmd) {
3332 if (cmd == null) {
3333 return shell.handleDefaultCommands(cmd);
3334 }
3335
3336 final PrintWriter pw = shell.getOutPrintWriter();
3337 try {
3338 switch(cmd) {
3339 case "list":
3340 return runList(pw);
3341 }
3342 } catch (RemoteException e) {
3343 pw.println("Remote exception: " + e);
3344 }
3345 return -1;
3346 }
3347
3348 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003349 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003350 final List<UserInfo> users = getUsers(false);
3351 if (users == null) {
3352 pw.println("Error: couldn't get users");
3353 return 1;
3354 } else {
3355 pw.println("Users:");
3356 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003357 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003358 pw.println("\t" + users.get(i).toString() + running);
3359 }
3360 return 0;
3361 }
3362 }
3363
3364 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003365 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3366 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3367 != PackageManager.PERMISSION_GRANTED) {
3368 pw.println("Permission Denial: can't dump UserManager from from pid="
3369 + Binder.getCallingPid()
3370 + ", uid=" + Binder.getCallingUid()
3371 + " without permission "
3372 + android.Manifest.permission.DUMP);
3373 return;
3374 }
3375
3376 long now = System.currentTimeMillis();
3377 StringBuilder sb = new StringBuilder();
3378 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003379 synchronized (mUsersLock) {
3380 pw.println("Users:");
3381 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003382 UserData userData = mUsers.valueAt(i);
3383 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003384 continue;
3385 }
Amith Yamasani12747872015-12-07 14:19:49 -08003386 UserInfo userInfo = userData.info;
3387 final int userId = userInfo.id;
3388 pw.print(" "); pw.print(userInfo);
3389 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003390 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003391 pw.print(" <removing> ");
3392 }
Amith Yamasani12747872015-12-07 14:19:49 -08003393 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003394 pw.print(" <partial>");
3395 }
3396 pw.println();
3397 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003398 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003399 pw.println("<unknown>");
3400 } else {
3401 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003402 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003403 sb.append(" ago");
3404 pw.println(sb);
3405 }
3406 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003407 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003408 pw.println("<unknown>");
3409 } else {
3410 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003411 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003412 sb.append(" ago");
3413 pw.println(sb);
3414 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003415 pw.print(" Last logged in fingerprint: ");
3416 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003417 pw.print(" Has profile owner: ");
3418 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003419 pw.println(" Restrictions:");
3420 synchronized (mRestrictionsLock) {
3421 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003422 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003423 pw.println(" Device policy local restrictions:");
3424 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003425 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003426 pw.println(" Effective restrictions:");
3427 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003428 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003429 }
Amith Yamasani12747872015-12-07 14:19:49 -08003430
3431 if (userData.account != null) {
3432 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003433 pw.println();
3434 }
Amith Yamasani12747872015-12-07 14:19:49 -08003435
3436 if (userData.seedAccountName != null) {
3437 pw.print(" Seed account name: " + userData.seedAccountName);
3438 pw.println();
3439 if (userData.seedAccountType != null) {
3440 pw.print(" account type: " + userData.seedAccountType);
3441 pw.println();
3442 }
3443 if (userData.seedAccountOptions != null) {
3444 pw.print(" account options exist");
3445 pw.println();
3446 }
3447 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003448 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003449 }
Amith Yamasani12747872015-12-07 14:19:49 -08003450 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003451 pw.println(" Device policy global restrictions:");
3452 synchronized (mRestrictionsLock) {
3453 UserRestrictionsUtils
3454 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3455 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003456 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003457 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3458 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003459 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003460 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003461 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003462 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003463 synchronized (mUsersLock) {
3464 pw.println();
3465 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003466 if (mRemovingUserIds.size() > 0) {
3467 pw.println();
3468 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3469 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003470 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003471 synchronized (mUserStates) {
3472 pw.println(" Started users state: " + mUserStates);
3473 }
Amith Yamasani12747872015-12-07 14:19:49 -08003474 // Dump some capabilities
3475 pw.println();
3476 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3477 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003478 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3479 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003480 }
3481 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003482
3483 final class MainHandler extends Handler {
3484
3485 @Override
3486 public void handleMessage(Message msg) {
3487 switch (msg.what) {
3488 case WRITE_USER_MSG:
3489 removeMessages(WRITE_USER_MSG, msg.obj);
3490 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003491 int userId = ((UserData) msg.obj).info.id;
3492 UserData userData = getUserDataNoChecks(userId);
3493 if (userData != null) {
3494 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003495 }
3496 }
3497 }
3498 }
3499 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003500
3501 /**
3502 * @param userId
3503 * @return whether the user has been initialized yet
3504 */
3505 boolean isInitialized(int userId) {
3506 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3507 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003508
3509 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003510 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003511 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3512 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003513 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003514 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003515 }
3516
3517 @Override
3518 public Bundle getBaseUserRestrictions(int userId) {
3519 synchronized (mRestrictionsLock) {
3520 return mBaseUserRestrictions.get(userId);
3521 }
3522 }
3523
3524 @Override
3525 public void setBaseUserRestrictionsByDpmsForMigration(
3526 int userId, Bundle baseRestrictions) {
3527 synchronized (mRestrictionsLock) {
3528 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003529 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003530 }
3531
Amith Yamasani12747872015-12-07 14:19:49 -08003532 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003533 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003534 if (userData != null) {
3535 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003536 } else {
3537 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3538 }
3539 }
3540 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003541
3542 @Override
3543 public boolean getUserRestriction(int userId, String key) {
3544 return getUserRestrictions(userId).getBoolean(key);
3545 }
3546
3547 @Override
3548 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3549 synchronized (mUserRestrictionsListeners) {
3550 mUserRestrictionsListeners.add(listener);
3551 }
3552 }
3553
3554 @Override
3555 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3556 synchronized (mUserRestrictionsListeners) {
3557 mUserRestrictionsListeners.remove(listener);
3558 }
3559 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003560
3561 @Override
3562 public void setDeviceManaged(boolean isManaged) {
3563 synchronized (mUsersLock) {
3564 mIsDeviceManaged = isManaged;
3565 }
3566 }
3567
3568 @Override
3569 public void setUserManaged(int userId, boolean isManaged) {
3570 synchronized (mUsersLock) {
3571 mIsUserManaged.put(userId, isManaged);
3572 }
3573 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003574
3575 @Override
3576 public void setUserIcon(int userId, Bitmap bitmap) {
3577 long ident = Binder.clearCallingIdentity();
3578 try {
3579 synchronized (mPackagesLock) {
3580 UserData userData = getUserDataNoChecks(userId);
3581 if (userData == null || userData.info.partial) {
3582 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3583 return;
3584 }
3585 writeBitmapLP(userData.info, bitmap);
3586 writeUserLP(userData);
3587 }
3588 sendUserInfoChangedBroadcast(userId);
3589 } finally {
3590 Binder.restoreCallingIdentity(ident);
3591 }
3592 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003593
3594 @Override
3595 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3596 synchronized (mUsersLock) {
3597 mForceEphemeralUsers = forceEphemeralUsers;
3598 }
3599 }
3600
3601 @Override
3602 public void removeAllUsers() {
3603 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3604 // Remove the non-system users straight away.
3605 removeNonSystemUsers();
3606 } else {
3607 // Switch to the system user first and then remove the other users.
3608 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3609 @Override
3610 public void onReceive(Context context, Intent intent) {
3611 int userId =
3612 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3613 if (userId != UserHandle.USER_SYSTEM) {
3614 return;
3615 }
3616 mContext.unregisterReceiver(this);
3617 removeNonSystemUsers();
3618 }
3619 };
3620 IntentFilter userSwitchedFilter = new IntentFilter();
3621 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3622 mContext.registerReceiver(
3623 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3624
3625 // Switch to the system user.
3626 ActivityManager am =
3627 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3628 am.switchUser(UserHandle.USER_SYSTEM);
3629 }
3630 }
phweisse9c44062016-02-10 12:57:38 +01003631
3632 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003633 public void onEphemeralUserStop(int userId) {
3634 synchronized (mUsersLock) {
3635 UserInfo userInfo = getUserInfoLU(userId);
3636 if (userInfo != null && userInfo.isEphemeral()) {
3637 // Do not allow switching back to the ephemeral user again as the user is going
3638 // to be deleted.
3639 userInfo.flags |= UserInfo.FLAG_DISABLED;
3640 if (userInfo.isGuest()) {
3641 // Indicate that the guest will be deleted after it stops.
3642 userInfo.guestToRemove = true;
3643 }
3644 }
3645 }
3646 }
3647
3648 @Override
phweisse9c44062016-02-10 12:57:38 +01003649 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003650 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003651 // Keep this in sync with UserManager.createUser
3652 if (user != null && !user.isAdmin()) {
3653 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3654 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3655 }
3656 return user;
3657 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003658
3659 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003660 public boolean removeUserEvenWhenDisallowed(int userId) {
3661 return removeUserUnchecked(userId);
3662 }
3663
3664 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003665 public boolean isUserRunning(int userId) {
3666 synchronized (mUserStates) {
3667 return mUserStates.get(userId, -1) >= 0;
3668 }
3669 }
3670
3671 @Override
3672 public void setUserState(int userId, int userState) {
3673 synchronized (mUserStates) {
3674 mUserStates.put(userId, userState);
3675 }
3676 }
3677
3678 @Override
3679 public void removeUserState(int userId) {
3680 synchronized (mUserStates) {
3681 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003682 }
3683 }
3684
3685 @Override
3686 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003687 synchronized (mUserStates) {
3688 int state = mUserStates.get(userId, -1);
3689 return (state == UserState.STATE_RUNNING_UNLOCKING)
3690 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003691 }
3692 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003693
3694 @Override
3695 public boolean isUserUnlocked(int userId) {
3696 synchronized (mUserStates) {
3697 int state = mUserStates.get(userId, -1);
3698 return state == UserState.STATE_RUNNING_UNLOCKED;
3699 }
3700 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003701 }
3702
3703 /* Remove all the users except of the system one. */
3704 private void removeNonSystemUsers() {
3705 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3706 synchronized (mUsersLock) {
3707 final int userSize = mUsers.size();
3708 for (int i = 0; i < userSize; i++) {
3709 UserInfo ui = mUsers.valueAt(i).info;
3710 if (ui.id != UserHandle.USER_SYSTEM) {
3711 usersToRemove.add(ui);
3712 }
3713 }
3714 }
3715 for (UserInfo ui: usersToRemove) {
3716 removeUser(ui.id);
3717 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003718 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003719
3720 private class Shell extends ShellCommand {
3721 @Override
3722 public int onCommand(String cmd) {
3723 return onShellCommand(this, cmd);
3724 }
3725
3726 @Override
3727 public void onHelp() {
3728 final PrintWriter pw = getOutPrintWriter();
3729 pw.println("User manager (user) commands:");
3730 pw.println(" help");
3731 pw.println(" Print this help text.");
3732 pw.println("");
3733 pw.println(" list");
3734 pw.println(" Prints all users on the system.");
3735 }
3736 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003737
3738 private static void debug(String message) {
3739 Log.d(LOG_TAG, message +
3740 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3741 }
Kenny Guy02c89902016-11-15 19:36:38 +00003742
3743 @VisibleForTesting
3744 static int getMaxManagedProfiles() {
3745 // Allow overriding max managed profiles on debuggable builds for testing
3746 // of multiple profiles.
3747 if (!Build.IS_DEBUGGABLE) {
3748 return MAX_MANAGED_PROFILES;
3749 } else {
3750 return SystemProperties.getInt("persist.sys.max_profiles",
3751 MAX_MANAGED_PROFILES);
3752 }
3753 }
3754
3755 @VisibleForTesting
3756 int getFreeProfileBadgeLU(int parentUserId) {
3757 int maxManagedProfiles = getMaxManagedProfiles();
3758 boolean[] usedBadges = new boolean[maxManagedProfiles];
3759 final int userSize = mUsers.size();
3760 for (int i = 0; i < userSize; i++) {
3761 UserInfo ui = mUsers.valueAt(i).info;
3762 // Check which badge indexes are already used by this profile group.
3763 if (ui.isManagedProfile()
3764 && ui.profileGroupId == parentUserId
3765 && !mRemovingUserIds.get(ui.id)
3766 && ui.profileBadge < maxManagedProfiles) {
3767 usedBadges[ui.profileBadge] = true;
3768 }
3769 }
3770 for (int i = 0; i < maxManagedProfiles; i++) {
3771 if (!usedBadges[i]) {
3772 return i;
3773 }
3774 }
3775 return 0;
3776 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003777
3778 /**
3779 * Checks if the given user has a managed profile associated with it.
3780 * @param userId The parent user
3781 * @return
3782 */
3783 boolean hasManagedProfile(int userId) {
3784 synchronized (mUsersLock) {
3785 UserInfo userInfo = getUserInfoLU(userId);
3786 final int userSize = mUsers.size();
3787 for (int i = 0; i < userSize; i++) {
3788 UserInfo profile = mUsers.valueAt(i).info;
3789 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3790 return true;
3791 }
3792 }
3793 return false;
3794 }
3795 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003796}