blob: 05228ec50e5d4753ae46bef549d88cc42c4afda2 [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;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000029import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000035import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000040import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070041import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080042import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010044import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070045import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060047import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080048import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080049import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.os.Environment;
51import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080053import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080055import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010056import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080058import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070060import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010062import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Kenny Guy02c89902016-11-15 19:36:38 +000066import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070068import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080070import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010071import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070072import android.security.GateKeeper;
73import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070074import android.system.ErrnoException;
75import android.system.Os;
76import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070077import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080092import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070093import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070094import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000095import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070096import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070097import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000098import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070099import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100100
Jeff Sharkey47f71082016-02-01 17:03:54 -0700101import libcore.io.IoUtils;
102import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800103
104import org.xmlpull.v1.XmlPullParser;
105import org.xmlpull.v1.XmlPullParserException;
106import org.xmlpull.v1.XmlSerializer;
107
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108import java.io.BufferedOutputStream;
109import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700110import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.FileOutputStream;
Kenny Guy02c89902016-11-15 19:36:38 +0000114import java.io.InputStream;
115import java.io.OutputStream;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700117import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100118import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.util.ArrayList;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700120import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121import java.util.List;
122
Makoto Onuki068c54a2015-10-13 14:34:03 -0700123/**
124 * Service for {@link UserManager}.
125 *
126 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700127 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800128 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700129 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
130 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
131 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700132 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700133public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700134
Amith Yamasani2a003292012-08-14 18:25:45 -0700135 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800136 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800137 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700138 // Can be used for manual testing of id recycling
139 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700140
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800142 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700144 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700146 private static final String ATTR_CREATION_TIME = "created";
147 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600148 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700149 private static final String ATTR_SERIAL_NO = "serialNumber";
150 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700151 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700152 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700153 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100154 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000155 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700156 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800157 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
158 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530159 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700160 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800162 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800163 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100164 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800165 private static final String TAG_ENTRY = "entry";
166 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800167 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800168 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700169 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800170 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700172 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
173 private static final String ATTR_TYPE_STRING = "s";
174 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700175 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700176 private static final String ATTR_TYPE_BUNDLE = "B";
177 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700178
Amith Yamasani0b285492011-04-14 17:35:23 -0700179 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700180 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700181 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100182 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800184 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700185 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800186
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700187 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
188 UserInfo.FLAG_MANAGED_PROFILE
189 | UserInfo.FLAG_EPHEMERAL
190 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700191 | UserInfo.FLAG_GUEST
192 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700193
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700194 @VisibleForTesting
195 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700196 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700197 @VisibleForTesting
198 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
199
200 // Max size of the queue of recently removed users
201 @VisibleForTesting
202 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700203
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700204 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700205
Amith Yamasani920ace02012-09-20 22:15:37 -0700206 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
207
Nicolas Prevotb8186812015-08-06 15:00:03 +0100208 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700209 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000210 @VisibleForTesting
211 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700212
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800213 static final int WRITE_USER_MSG = 1;
214 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530215
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700216 private static final String XATTR_SERIAL = "user.serial";
217
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800218 // Tron counters
219 private static final String TRON_GUEST_CREATED = "users_guest_created";
220 private static final String TRON_USER_CREATED = "users_user_created";
221
Dianne Hackborn4428e172012-08-24 17:43:05 -0700222 private final Context mContext;
223 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700224 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700225 // Short-term lock for internal state, when interaction/sync with PM is not required
226 private final Object mUsersLock = new Object();
227 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700228
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800229 private final Handler mHandler;
230
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700231 private final File mUsersDir;
232 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700233
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800234 private static final IBinder mUserRestriconToken = new Binder();
235
Makoto Onuki068c54a2015-10-13 14:34:03 -0700236 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800237 * User-related information that is used for persisting to flash. Only UserInfo is
238 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800239 */
Kenny Guy02c89902016-11-15 19:36:38 +0000240 @VisibleForTesting
241 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800242 // Basic user information and properties
243 UserInfo info;
244 // Account name used when there is a strong association between a user and an account
245 String account;
246 // Account information for seeding into a newly created user. This could also be
247 // used for login validation for an existing user, for updating their credentials.
248 // In the latter case, data may not need to be persisted as it is only valid for the
249 // current login session.
250 String seedAccountName;
251 String seedAccountType;
252 PersistableBundle seedAccountOptions;
253 // Whether to perist the seed account information to be available after a boot
254 boolean persistSeedData;
255
256 void clearSeedAccountData() {
257 seedAccountName = null;
258 seedAccountType = null;
259 seedAccountOptions = null;
260 persistSeedData = false;
261 }
262 }
263
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800264 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800265 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800266
267 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700268 * User restrictions set via UserManager. This doesn't include restrictions set by
269 * device owner / profile owners.
270 *
271 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
272 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
273 * maybe shared between {@link #mBaseUserRestrictions} and
274 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
275 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700276 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700277 */
278 @GuardedBy("mRestrictionsLock")
279 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
280
281 /**
282 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
283 * with device / profile owner restrictions. We'll initialize it lazily; use
284 * {@link #getEffectiveUserRestrictions} to access it.
285 *
286 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
287 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
288 * maybe shared between {@link #mBaseUserRestrictions} and
289 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
290 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700291 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700292 */
293 @GuardedBy("mRestrictionsLock")
294 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
295
Makoto Onuki4f160732015-10-27 17:15:38 -0700296 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800297 * User restrictions that have already been applied in
298 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
299 * that have changed since the last
300 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700301 */
302 @GuardedBy("mRestrictionsLock")
303 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
304
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800305 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800306 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
307 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800308 */
309 @GuardedBy("mRestrictionsLock")
310 private Bundle mDevicePolicyGlobalUserRestrictions;
311
312 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100313 * Id of the user that set global restrictions.
314 */
315 @GuardedBy("mRestrictionsLock")
316 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
317
318 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800319 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
320 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800321 */
322 @GuardedBy("mRestrictionsLock")
323 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
324
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800325 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530326 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800327
328 /**
329 * Set of user IDs being actively removed. Removed IDs linger in this set
330 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700331 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800332 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700333 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800334 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700335
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700336 /**
337 * Queue of recently removed userIds. Used for recycling of userIds
338 */
339 @GuardedBy("mUsersLock")
340 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
341
Fyodor Kupolov82402752015-10-28 14:54:51 -0700342 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700343 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800344 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700345 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700346 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700347
Jason Monk62062992014-05-06 09:55:28 -0400348 private IAppOpsService mAppOpsService;
349
Makoto Onuki068c54a2015-10-13 14:34:03 -0700350 private final LocalService mLocalService;
351
Makoto Onukie7927da2015-11-25 10:05:17 -0800352 @GuardedBy("mUsersLock")
353 private boolean mIsDeviceManaged;
354
355 @GuardedBy("mUsersLock")
356 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
357
Makoto Onukid45a4a22015-11-02 17:17:38 -0800358 @GuardedBy("mUserRestrictionsListeners")
359 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
360 new ArrayList<>();
361
Clara Bayarria1771112015-12-18 16:29:18 +0000362 private final LockPatternUtils mLockPatternUtils;
363
Ricky Waib1dd80b2016-06-07 18:00:55 +0100364 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
365 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
366
367 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
368 @Override
369 public void onReceive(Context context, Intent intent) {
370 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
371 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
372 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
373 setQuietModeEnabled(userHandle, false);
374 if (target != null) {
375 try {
376 mContext.startIntentSender(target, null, 0, 0, 0);
377 } catch (IntentSender.SendIntentException e) {
378 /* ignore */
379 }
380 }
381 }
382 }
383 };
384
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100385 /**
386 * Whether all users should be created ephemeral.
387 */
388 @GuardedBy("mUsersLock")
389 private boolean mForceEphemeralUsers;
390
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000391 @GuardedBy("mUserStates")
392 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700393
Amith Yamasani258848d2012-08-10 17:06:33 -0700394 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700395
Dianne Hackborn4428e172012-08-24 17:43:05 -0700396 public static UserManagerService getInstance() {
397 synchronized (UserManagerService.class) {
398 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700399 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700401
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700402 public static class LifeCycle extends SystemService {
403
404 private UserManagerService mUms;
405
406 /**
407 * @param context
408 */
409 public LifeCycle(Context context) {
410 super(context);
411 }
412
413 @Override
414 public void onStart() {
415 mUms = UserManagerService.getInstance();
416 publishBinderService(Context.USER_SERVICE, mUms);
417 }
418
419 @Override
420 public void onBootPhase(int phase) {
421 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
422 mUms.cleanupPartialUsers();
423 }
424 }
425 }
426
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700427 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800428 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700429 UserManagerService(Context context) {
430 this(context, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700431 }
432
Dianne Hackborn4428e172012-08-24 17:43:05 -0700433 /**
434 * Called by package manager to create the service. This is closely
435 * associated with the package manager, and the given lock is the
436 * package manager's own lock.
437 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800438 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
439 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700440 }
441
Dianne Hackborn4428e172012-08-24 17:43:05 -0700442 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800443 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700444 mContext = context;
445 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700446 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800447 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800448 synchronized (mPackagesLock) {
449 mUsersDir = new File(dataDir, USER_INFO_DIR);
450 mUsersDir.mkdirs();
451 // Make zeroth user directory, for services to migrate their files to that location
452 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
453 userZeroDir.mkdirs();
454 FileUtils.setPermissions(mUsersDir.toString(),
455 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
456 -1, -1);
457 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
458 initDefaultGuestRestrictions();
459 readUserListLP();
460 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700461 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700462 mLocalService = new LocalService();
463 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000464 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000465 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700466 }
467
468 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400469 mAppOpsService = IAppOpsService.Stub.asInterface(
470 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800471
472 synchronized (mRestrictionsLock) {
473 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400474 }
Samuel Tand9453b82016-03-14 15:57:02 -0700475
476 UserInfo currentGuestUser = findCurrentGuestUser();
477 if (currentGuestUser != null && !hasUserRestriction(
478 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
479 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
480 // to it, in case this guest was created in a previous version where this
481 // user restriction was not a default guest restriction.
482 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
483 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700484
Ricky Waib1dd80b2016-06-07 18:00:55 +0100485 mContext.registerReceiver(mDisableQuietModeCallback,
486 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
487 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700488 }
489
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700490 void cleanupPartialUsers() {
491 // Prune out any partially created, partially removed and ephemeral users.
492 ArrayList<UserInfo> partials = new ArrayList<>();
493 synchronized (mUsersLock) {
494 final int userSize = mUsers.size();
495 for (int i = 0; i < userSize; i++) {
496 UserInfo ui = mUsers.valueAt(i).info;
497 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
498 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700499 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700500 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700501 }
502 }
503 }
504 final int partialsSize = partials.size();
505 for (int i = 0; i < partialsSize; i++) {
506 UserInfo ui = partials.get(i);
507 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
508 + " (name=" + ui.name + ")");
509 removeUserState(ui.id);
510 }
511 }
512
Amith Yamasani258848d2012-08-10 17:06:33 -0700513 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800514 public String getUserAccount(int userId) {
515 checkManageUserAndAcrossUsersFullPermission("get user account");
516 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800517 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800518 }
519 }
520
521 @Override
522 public void setUserAccount(int userId, String accountName) {
523 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800524 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800525 synchronized (mPackagesLock) {
526 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800527 final UserData userData = mUsers.get(userId);
528 if (userData == null) {
529 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
530 return;
531 }
532 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800533 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800534 userData.account = accountName;
535 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800536 }
537 }
538
539 if (userToUpdate != null) {
540 writeUserLP(userToUpdate);
541 }
542 }
543 }
544
545 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700546 public UserInfo getPrimaryUser() {
547 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700549 final int userSize = mUsers.size();
550 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800551 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800552 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700553 return ui;
554 }
555 }
556 }
557 return null;
558 }
559
560 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700561 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700562 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700564 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700565 final int userSize = mUsers.size();
566 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800567 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700568 if (ui.partial) {
569 continue;
570 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800571 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700572 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700573 }
Amith Yamasani13593602012-03-22 16:16:17 -0700574 }
575 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700576 }
Amith Yamasani13593602012-03-22 16:16:17 -0700577 }
578
Amith Yamasani258848d2012-08-10 17:06:33 -0700579 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100580 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700581 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800582 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700583 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700584 } else {
585 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800586 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 final long ident = Binder.clearCallingIdentity();
588 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700589 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700590 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100591 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700592 } finally {
593 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000594 }
595 }
596
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700597 @Override
598 public int[] getProfileIds(int userId, boolean enabledOnly) {
599 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700600 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700601 }
602 final long ident = Binder.clearCallingIdentity();
603 try {
604 synchronized (mUsersLock) {
605 return getProfileIdsLU(userId, enabledOnly).toArray();
606 }
607 } finally {
608 Binder.restoreCallingIdentity(ident);
609 }
610 }
611
Amith Yamasanibe465322014-04-24 13:45:17 -0700612 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700613 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700614 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
615 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
616 for (int i = 0; i < profileIds.size(); i++) {
617 int profileId = profileIds.get(i);
618 UserInfo userInfo = mUsers.get(profileId).info;
619 // If full info is not required - clear PII data to prevent 3P apps from reading it
620 if (!fullInfo) {
621 userInfo = new UserInfo(userInfo);
622 userInfo.name = null;
623 userInfo.iconPath = null;
624 } else {
625 userInfo = userWithName(userInfo);
626 }
627 users.add(userInfo);
628 }
629 return users;
630 }
631
632 /**
633 * Assume permissions already checked and caller's identity cleared
634 */
635 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700636 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700637 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700638 if (user == null) {
639 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700640 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700641 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700642 final int userSize = mUsers.size();
643 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800644 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700645 if (!isProfileOf(user, profile)) {
646 continue;
647 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100648 if (enabledOnly && !profile.isEnabled()) {
649 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700650 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700651 if (mRemovingUserIds.get(profile.id)) {
652 continue;
653 }
Tony Mak80189cd2016-04-05 17:21:42 +0100654 if (profile.partial) {
655 continue;
656 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700657 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700658 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700659 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700660 }
661
Jessica Hummelbe81c802014-04-22 15:49:22 +0100662 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700663 public int getCredentialOwnerProfile(int userHandle) {
664 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000665 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700666 synchronized (mUsersLock) {
667 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700668 if (profileParent != null) {
669 return profileParent.id;
670 }
671 }
672 }
673
674 return userHandle;
675 }
676
677 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700678 public boolean isSameProfileGroup(int userId, int otherUserId) {
679 if (userId == otherUserId) return true;
680 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700681 return isSameProfileGroupNoChecks(userId, otherUserId);
682 }
683
684 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700685 synchronized (mUsersLock) {
686 UserInfo userInfo = getUserInfoLU(userId);
687 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
688 return false;
689 }
690 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
691 if (otherUserInfo == null
692 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
693 return false;
694 }
695 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700696 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700697 }
698
699 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100700 public UserInfo getProfileParent(int userHandle) {
701 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700702 synchronized (mUsersLock) {
703 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700704 }
705 }
706
Fyodor Kupolov82402752015-10-28 14:54:51 -0700707 private UserInfo getProfileParentLU(int userHandle) {
708 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700709 if (profile == null) {
710 return null;
711 }
712 int parentUserId = profile.profileGroupId;
713 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
714 return null;
715 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700716 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100717 }
718 }
719
Fyodor Kupolov82402752015-10-28 14:54:51 -0700720 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100721 return user.id == profile.id ||
722 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
723 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000724 }
725
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000726 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000727 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100728 Intent intent = new Intent();
729 if (inQuietMode) {
730 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
731 } else {
732 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
733 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000734 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
735 intent.putExtra(Intent.EXTRA_USER, profileHandle);
736 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000737 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000738 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000739 }
740
741 @Override
742 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
743 checkManageUsersPermission("silence profile");
744 boolean changed = false;
745 UserInfo profile, parent;
746 synchronized (mPackagesLock) {
747 synchronized (mUsersLock) {
748 profile = getUserInfoLU(userHandle);
749 parent = getProfileParentLU(userHandle);
750
751 }
752 if (profile == null || !profile.isManagedProfile()) {
753 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
754 }
755 if (profile.isQuietModeEnabled() != enableQuietMode) {
756 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800757 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000758 changed = true;
759 }
760 }
761 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000762 long identity = Binder.clearCallingIdentity();
763 try {
764 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800765 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100766 LocalServices.getService(ActivityManagerInternal.class)
767 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000768 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800769 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000770 }
771 } catch (RemoteException e) {
772 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
773 } finally {
774 Binder.restoreCallingIdentity(identity);
775 }
776
777 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
778 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000779 }
780 }
781
782 @Override
783 public boolean isQuietModeEnabled(int userHandle) {
784 synchronized (mPackagesLock) {
785 UserInfo info;
786 synchronized (mUsersLock) {
787 info = getUserInfoLU(userHandle);
788 }
789 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000790 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000791 }
792 return info.isQuietModeEnabled();
793 }
794 }
795
Kenny Guya52dc3e2014-02-11 15:33:14 +0000796 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100797 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100798 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600799 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100800 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100801 // if the user is already unlocked, no need to show a profile challenge
802 setQuietModeEnabled(userHandle, false);
803 return true;
804 }
805
806 long identity = Binder.clearCallingIdentity();
807 try {
808 // otherwise, we show a profile challenge to trigger decryption of the user
809 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
810 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100811 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
812 // lock, confirm screenlock page will know and show personal challenge, and unlock
813 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100814 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
815 userHandle);
816 if (unlockIntent == null) {
817 return false;
818 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100819 final Intent callBackIntent = new Intent(
820 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100821 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100822 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100823 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100824 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
825 callBackIntent.setPackage(mContext.getPackageName());
826 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
827 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
828 mContext,
829 0,
830 callBackIntent,
831 PendingIntent.FLAG_CANCEL_CURRENT |
832 PendingIntent.FLAG_ONE_SHOT |
833 PendingIntent.FLAG_IMMUTABLE);
834 // After unlocking the challenge, it will disable quiet mode and run the original
835 // intentSender
836 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100837 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
838 mContext.startActivity(unlockIntent);
839 } finally {
840 Binder.restoreCallingIdentity(identity);
841 }
842 return false;
843 }
844
845 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100846 public void setUserEnabled(int userId) {
847 checkManageUsersPermission("enable user");
848 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700849 UserInfo info;
850 synchronized (mUsersLock) {
851 info = getUserInfoLU(userId);
852 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100853 if (info != null && !info.isEnabled()) {
854 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800855 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100856 }
857 }
858 }
859
860 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700861 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700862 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000863 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700864 return userWithName(getUserInfoLU(userId));
865 }
866 }
867
868 /**
869 * Returns a UserInfo object with the name filled in, for Owner, or the original
870 * if the name is already set.
871 */
872 private UserInfo userWithName(UserInfo orig) {
873 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
874 UserInfo withName = new UserInfo(orig);
875 withName.name = getOwnerName();
876 return withName;
877 } else {
878 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000879 }
880 }
881
882 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000883 public int getManagedProfileBadge(@UserIdInt int userId) {
884 int callingUserId = UserHandle.getCallingUserId();
885 if (callingUserId != userId && !hasManageUsersPermission()) {
886 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
887 throw new SecurityException(
888 "You need MANAGE_USERS permission to: check if specified user a " +
889 "managed profile outside your profile group");
890 }
891 }
892 synchronized (mUsersLock) {
893 UserInfo userInfo = getUserInfoLU(userId);
894 return userInfo != null ? userInfo.profileBadge : 0;
895 }
896 }
897
898 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000899 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000900 int callingUserId = UserHandle.getCallingUserId();
901 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700902 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700903 throw new SecurityException(
904 "You need MANAGE_USERS permission to: check if specified user a " +
905 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000906 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000907 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700908 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700909 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000910 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700911 }
912 }
913
Amith Yamasani71e6c692013-03-24 17:39:28 -0700914 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700915 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800916 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700917 return mLocalService.isUserUnlockingOrUnlocked(userId);
918 }
919
920 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800921 public boolean isUserUnlocked(int userId) {
922 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
923 return mLocalService.isUserUnlockingOrUnlocked(userId);
924 }
925
926 @Override
927 public boolean isUserRunning(int userId) {
928 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
929 return mLocalService.isUserRunning(userId);
930 }
931
932 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
933 int callingUserId = UserHandle.getCallingUserId();
934 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
935 hasManageUsersPermission()) {
936 return;
937 }
938 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
939 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
940 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
941 + "to: check " + name);
942 }
943 }
944
945 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700946 public boolean isDemoUser(int userId) {
947 int callingUserId = UserHandle.getCallingUserId();
948 if (callingUserId != userId && !hasManageUsersPermission()) {
949 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
950 + " is a demo user");
951 }
952 synchronized (mUsersLock) {
953 UserInfo userInfo = getUserInfoLU(userId);
954 return userInfo != null && userInfo.isDemo();
955 }
956 }
957
958 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700959 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700960 synchronized (mUsersLock) {
961 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700962 }
963 }
964
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700965 @Override
966 public boolean canHaveRestrictedProfile(int userId) {
967 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700968 synchronized (mUsersLock) {
969 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700970 if (userInfo == null || !userInfo.canHaveProfile()) {
971 return false;
972 }
973 if (!userInfo.isAdmin()) {
974 return false;
975 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800976 // restricted profile can be created if there is no DO set and the admin user has no PO;
977 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700978 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700979 }
980
Amith Yamasani195263742012-08-21 15:40:12 -0700981 /*
982 * Should be locked on mUsers before calling this.
983 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700984 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800985 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700986 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800987 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700988 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
989 return null;
990 }
Amith Yamasani12747872015-12-07 14:19:49 -0800991 return userData != null ? userData.info : null;
992 }
993
994 private UserData getUserDataLU(int userId) {
995 final UserData userData = mUsers.get(userId);
996 // If it is partial and not in the process of being removed, return as unknown user.
997 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
998 return null;
999 }
1000 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001001 }
1002
Fyodor Kupolov82402752015-10-28 14:54:51 -07001003 /**
1004 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1005 * <p>No permissions checking or any addition checks are made</p>
1006 */
1007 private UserInfo getUserInfoNoChecks(int userId) {
1008 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001009 final UserData userData = mUsers.get(userId);
1010 return userData != null ? userData.info : null;
1011 }
1012 }
1013
1014 /**
1015 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1016 * <p>No permissions checking or any addition checks are made</p>
1017 */
1018 private UserData getUserDataNoChecks(int userId) {
1019 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001020 return mUsers.get(userId);
1021 }
1022 }
1023
Amith Yamasani236b2b52015-08-18 14:32:14 -07001024 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001025 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001026 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001027 }
1028
Amith Yamasani258848d2012-08-10 17:06:33 -07001029 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001030 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001031 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001032 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001033 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001034 UserData userData = getUserDataNoChecks(userId);
1035 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001036 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1037 return;
1038 }
Amith Yamasani12747872015-12-07 14:19:49 -08001039 if (name != null && !name.equals(userData.info.name)) {
1040 userData.info.name = name;
1041 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001042 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001043 }
1044 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001045 if (changed) {
1046 sendUserInfoChangedBroadcast(userId);
1047 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001048 }
1049
Amith Yamasani258848d2012-08-10 17:06:33 -07001050 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001051 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001052 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001053 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1054 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1055 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001056 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001057 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001058 }
1059
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001060
1061
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001062 private void sendUserInfoChangedBroadcast(int userId) {
1063 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1064 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1065 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001066 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001067 }
1068
Amith Yamasani258848d2012-08-10 17:06:33 -07001069 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001070 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001071 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001072 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001073 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1074 if (targetUserInfo == null || targetUserInfo.partial) {
1075 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001076 return null;
1077 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001078
1079 final int callingUserId = UserHandle.getCallingUserId();
1080 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1081 final int targetGroupId = targetUserInfo.profileGroupId;
1082 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1083 && callingGroupId == targetGroupId);
1084 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001085 checkManageUsersPermission("get the icon of a user who is not related");
1086 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001087
1088 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001089 return null;
1090 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001091 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001092 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001093
1094 try {
1095 return ParcelFileDescriptor.open(
1096 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1097 } catch (FileNotFoundException e) {
1098 Log.e(LOG_TAG, "Couldn't find icon file", e);
1099 }
1100 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001101 }
1102
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001103 public void makeInitialized(int userId) {
1104 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001105 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001106 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001107 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001108 userData = mUsers.get(userId);
1109 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001110 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001111 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001112 }
Amith Yamasani12747872015-12-07 14:19:49 -08001113 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1114 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001115 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001116 }
1117 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001118 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001119 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001120 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001121 }
1122
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001123 /**
1124 * If default guest restrictions haven't been initialized yet, add the basic
1125 * restrictions.
1126 */
1127 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001128 synchronized (mGuestRestrictions) {
1129 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001130 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001131 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001132 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1133 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1134 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001135 }
1136 }
1137
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001138 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301139 public Bundle getDefaultGuestRestrictions() {
1140 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001141 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301142 return new Bundle(mGuestRestrictions);
1143 }
1144 }
1145
1146 @Override
1147 public void setDefaultGuestRestrictions(Bundle restrictions) {
1148 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001149 synchronized (mGuestRestrictions) {
1150 mGuestRestrictions.clear();
1151 mGuestRestrictions.putAll(restrictions);
1152 }
1153 synchronized (mPackagesLock) {
1154 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301155 }
1156 }
1157
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001158 /**
1159 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1160 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001161 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001162 @Nullable Bundle global) {
1163 Preconditions.checkNotNull(local);
1164 boolean globalChanged = false;
1165 boolean localChanged;
1166 synchronized (mRestrictionsLock) {
1167 if (global != null) {
1168 // Update global.
1169 globalChanged = !UserRestrictionsUtils.areEqual(
1170 mDevicePolicyGlobalUserRestrictions, global);
1171 if (globalChanged) {
1172 mDevicePolicyGlobalUserRestrictions = global;
1173 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001174 // Remember the global restriction owner userId to be able to make a distinction
1175 // in getUserRestrictionSource on who set local policies.
1176 mGlobalRestrictionOwnerUserId = userId;
1177 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001178 if (mGlobalRestrictionOwnerUserId == userId) {
1179 // When profile owner sets restrictions it passes null global bundle and we
1180 // reset global restriction owner userId.
1181 // This means this user used to have DO, but now the DO is gone and the user
1182 // instead has PO.
1183 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1184 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001185 }
1186 {
1187 // Update local.
1188 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1189 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1190 if (localChanged) {
1191 mDevicePolicyLocalUserRestrictions.put(userId, local);
1192 }
1193 }
1194 }
1195 if (DBG) {
1196 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1197 + " global=" + global + (globalChanged ? " (changed)" : "")
1198 + " local=" + local + (localChanged ? " (changed)" : "")
1199 );
1200 }
1201 // Don't call them within the mRestrictionsLock.
1202 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001203 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001204 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001205 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001206 if (globalChanged) {
1207 writeUserListLP();
1208 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001209 }
1210
1211 synchronized (mRestrictionsLock) {
1212 if (globalChanged) {
1213 applyUserRestrictionsForAllUsersLR();
1214 } else if (localChanged) {
1215 applyUserRestrictionsLR(userId);
1216 }
1217 }
1218 }
1219
Makoto Onuki068c54a2015-10-13 14:34:03 -07001220 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001221 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001222 final Bundle baseRestrictions =
1223 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1224 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1225 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001226
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001227 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1228 // Common case first.
1229 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001230 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001231 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1232 UserRestrictionsUtils.merge(effective, global);
1233 UserRestrictionsUtils.merge(effective, local);
1234
Makoto Onuki068c54a2015-10-13 14:34:03 -07001235 return effective;
1236 }
1237
1238 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001239 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001240 if (DBG) {
1241 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1242 }
1243 mCachedEffectiveUserRestrictions.remove(userId);
1244 }
1245
1246 private Bundle getEffectiveUserRestrictions(int userId) {
1247 synchronized (mRestrictionsLock) {
1248 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1249 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001250 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001251 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1252 }
1253 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001254 }
1255 }
1256
Makoto Onuki068c54a2015-10-13 14:34:03 -07001257 /** @return a specific user restriction that's in effect currently. */
1258 @Override
1259 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001260 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1261 return false;
1262 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001263 Bundle restrictions = getEffectiveUserRestrictions(userId);
1264 return restrictions != null && restrictions.getBoolean(restrictionKey);
1265 }
1266
1267 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001268 * @hide
1269 *
1270 * Returns who set a user restriction on a user.
1271 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1272 * @param restrictionKey the string key representing the restriction
1273 * @param userId the id of the user for whom to retrieve the restrictions.
1274 * @return The source of user restriction. Any combination of
1275 * {@link UserManager#RESTRICTION_NOT_SET},
1276 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1277 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1278 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1279 */
1280 @Override
1281 public int getUserRestrictionSource(String restrictionKey, int userId) {
1282 checkManageUsersPermission("getUserRestrictionSource");
1283 int result = UserManager.RESTRICTION_NOT_SET;
1284
1285 // Shortcut for the most common case
1286 if (!hasUserRestriction(restrictionKey, userId)) {
1287 return result;
1288 }
1289
1290 if (hasBaseUserRestriction(restrictionKey, userId)) {
1291 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1292 }
1293
1294 synchronized(mRestrictionsLock) {
1295 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1296 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1297 && localRestrictions.getBoolean(restrictionKey)) {
1298 // Local restrictions may have been set by device owner the userId of which is
1299 // stored in mGlobalRestrictionOwnerUserId.
1300 if (mGlobalRestrictionOwnerUserId == userId) {
1301 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1302 } else {
1303 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1304 }
1305 }
1306 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1307 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1308 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1309 }
1310 }
1311
1312 return result;
1313 }
1314
1315 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001316 * @return UserRestrictions that are in effect currently. This always returns a new
1317 * {@link Bundle}.
1318 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001319 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001320 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001321 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001322 }
1323
1324 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001325 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1326 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001327 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1328 return false;
1329 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001330 synchronized (mRestrictionsLock) {
1331 Bundle bundle = mBaseUserRestrictions.get(userId);
1332 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1333 }
1334 }
1335
1336 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001337 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001338 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001339 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1340 return;
1341 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001342 synchronized (mRestrictionsLock) {
1343 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1344 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001345 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1346 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001347 newRestrictions.putBoolean(key, value);
1348
Fyodor Kupolov82402752015-10-28 14:54:51 -07001349 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001350 }
1351 }
1352
Makoto Onuki068c54a2015-10-13 14:34:03 -07001353 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001354 * Optionally updating user restrictions, calculate the effective user restrictions and also
1355 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001356 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001357 * @param newRestrictions User restrictions to set.
1358 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001359 * @param userId target user ID.
1360 */
1361 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001362 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001363 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001364
1365 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1366 mAppliedUserRestrictions.get(userId));
1367
1368 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001369 if (newRestrictions != null) {
1370 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001371 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1372
1373 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001374 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1375 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001376
1377 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1378 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001379 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001380 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001381 }
1382
Fyodor Kupolov82402752015-10-28 14:54:51 -07001383 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001384
Makoto Onuki759a7632015-10-28 16:43:10 -07001385 mCachedEffectiveUserRestrictions.put(userId, effective);
1386
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001387 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001388 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001389 debug("Applying user restrictions: userId=" + userId
1390 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001391 }
1392
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001393 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001394 mHandler.post(new Runnable() {
1395 @Override
1396 public void run() {
1397 try {
1398 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1399 } catch (RemoteException e) {
1400 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1401 }
1402 }
1403 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001404 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001405
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001406 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001407
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001408 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001409 }
1410
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001411 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001412 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001413 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1414 // actually, but we still need some kind of synchronization otherwise we might end up
1415 // calling listeners out-of-order, thus "LR".
1416
1417 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1418 return;
1419 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001420
1421 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1422 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1423
1424 mHandler.post(new Runnable() {
1425 @Override
1426 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001427 UserRestrictionsUtils.applyUserRestrictions(
1428 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001429
Makoto Onukid45a4a22015-11-02 17:17:38 -08001430 final UserRestrictionsListener[] listeners;
1431 synchronized (mUserRestrictionsListeners) {
1432 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1433 mUserRestrictionsListeners.toArray(listeners);
1434 }
1435 for (int i = 0; i < listeners.length; i++) {
1436 listeners[i].onUserRestrictionsChanged(userId,
1437 newRestrictionsFinal, prevRestrictionsFinal);
1438 }
1439 }
1440 });
1441 }
1442
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001443 // Package private for the inner class.
1444 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001445 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001446 }
1447
1448 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 // Package private for the inner class.
1450 void applyUserRestrictionsForAllUsersLR() {
1451 if (DBG) {
1452 debug("applyUserRestrictionsForAllUsersLR");
1453 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001454 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001455 mCachedEffectiveUserRestrictions.clear();
1456
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001457 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001458 // it on a handler.
1459 final Runnable r = new Runnable() {
1460 @Override
1461 public void run() {
1462 // Then get the list of running users.
1463 final int[] runningUsers;
1464 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001465 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001466 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001467 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001468 return;
1469 }
1470 // Then re-calculate the effective restrictions and apply, only for running users.
1471 // It's okay if a new user has started after the getRunningUserIds() call,
1472 // because we'll do the same thing (re-calculate the restrictions and apply)
1473 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001474 synchronized (mRestrictionsLock) {
1475 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001476 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001477 }
1478 }
1479 }
1480 };
1481 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001482 }
1483
Amith Yamasani258848d2012-08-10 17:06:33 -07001484 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001485 * Check if we've hit the limit of how many users can be created.
1486 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001487 private boolean isUserLimitReached() {
1488 int count;
1489 synchronized (mUsersLock) {
1490 count = getAliveUsersExcludingGuestsCountLU();
1491 }
1492 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001493 }
1494
1495 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001496 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001497 checkManageUsersPermission("check if more managed profiles can be added.");
1498 if (ActivityManager.isLowRamDeviceStatic()) {
1499 return false;
1500 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001501 if (!mContext.getPackageManager().hasSystemFeature(
1502 PackageManager.FEATURE_MANAGED_USERS)) {
1503 return false;
1504 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001505 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001506 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1507 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001508 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001509 return false;
1510 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001511 synchronized(mUsersLock) {
1512 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001513 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001514 return false;
1515 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001516 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1517 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001518 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001519 return usersCountAfterRemoving == 1
1520 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001521 }
1522 }
1523
Fyodor Kupolov82402752015-10-28 14:54:51 -07001524 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001525 int aliveUserCount = 0;
1526 final int totalUserCount = mUsers.size();
1527 // Skip over users being removed
1528 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001529 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001530 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001531 aliveUserCount++;
1532 }
1533 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001534 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001535 }
1536
1537 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001538 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001539 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1540 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1541 * permissions can make certain calls to the UserManager.
1542 *
1543 * @param message used as message if SecurityException is thrown
1544 * @throws SecurityException if the caller does not have enough privilege.
1545 */
1546 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1547 final int uid = Binder.getCallingUid();
1548 if (uid != Process.SYSTEM_UID && uid != 0
1549 && ActivityManager.checkComponentPermission(
1550 Manifest.permission.MANAGE_USERS,
1551 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1552 && ActivityManager.checkComponentPermission(
1553 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1554 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1555 throw new SecurityException(
1556 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1557 + message);
1558 }
1559 }
1560
1561 /**
1562 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001563 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001564 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001565 *
1566 * @param message used as message if SecurityException is thrown
1567 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001568 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001569 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001570 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001571 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001572 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1573 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001574 }
1575
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001576 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001577 * Enforces that only the system UID or root's UID or apps that have the
1578 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1579 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1580 * can make certain calls to the UserManager.
1581 *
1582 * @param message used as message if SecurityException is thrown
1583 * @throws SecurityException if the caller is not system or root
1584 * @see #hasManageOrCreateUsersPermission()
1585 */
1586 private static final void checkManageOrCreateUsersPermission(String message) {
1587 if (!hasManageOrCreateUsersPermission()) {
1588 throw new SecurityException(
1589 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1590 }
1591 }
1592
1593 /**
1594 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1595 * to create user/profiles other than what is allowed for
1596 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1597 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1598 */
1599 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1600 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1601 if (!hasManageOrCreateUsersPermission()) {
1602 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1603 + "permission to create an user with flags: " + creationFlags);
1604 }
1605 } else if (!hasManageUsersPermission()) {
1606 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1607 + " with flags: " + creationFlags);
1608 }
1609 }
1610
1611 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001612 * @return whether the calling UID is system UID or root's UID or the calling app has the
1613 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1614 */
1615 private static final boolean hasManageUsersPermission() {
1616 final int callingUid = Binder.getCallingUid();
1617 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1618 || callingUid == Process.ROOT_UID
1619 || ActivityManager.checkComponentPermission(
1620 android.Manifest.permission.MANAGE_USERS,
1621 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1622 }
1623
1624 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001625 * @return whether the calling UID is system UID or root's UID or the calling app has the
1626 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1627 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1628 */
1629 private static final boolean hasManageOrCreateUsersPermission() {
1630 final int callingUid = Binder.getCallingUid();
1631 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1632 || callingUid == Process.ROOT_UID
1633 || ActivityManager.checkComponentPermission(
1634 android.Manifest.permission.MANAGE_USERS,
1635 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1636 || ActivityManager.checkComponentPermission(
1637 android.Manifest.permission.CREATE_USERS,
1638 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1639 }
1640
1641 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001642 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1643 * UserManager.
1644 *
1645 * @param message used as message if SecurityException is thrown
1646 * @throws SecurityException if the caller is not system or root
1647 */
1648 private static void checkSystemOrRoot(String message) {
1649 final int uid = Binder.getCallingUid();
1650 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1651 throw new SecurityException("Only system may: " + message);
1652 }
1653 }
1654
Fyodor Kupolov82402752015-10-28 14:54:51 -07001655 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001656 try {
1657 File dir = new File(mUsersDir, Integer.toString(info.id));
1658 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001659 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001660 if (!dir.exists()) {
1661 dir.mkdir();
1662 FileUtils.setPermissions(
1663 dir.getPath(),
1664 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1665 -1, -1);
1666 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001667 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001668 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001669 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001670 info.iconPath = file.getAbsolutePath();
1671 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001672 try {
1673 os.close();
1674 } catch (IOException ioe) {
1675 // What the ... !
1676 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001677 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001678 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001679 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001680 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001681 }
1682
Amith Yamasani0b285492011-04-14 17:35:23 -07001683 /**
1684 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1685 * cache it elsewhere.
1686 * @return the array of user ids.
1687 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001688 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001689 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001690 return mUserIds;
1691 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001692 }
1693
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001694 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001695 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001696 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001697 return;
1698 }
1699 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001700 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001701 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001702 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001703 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001704 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001705 int type;
1706 while ((type = parser.next()) != XmlPullParser.START_TAG
1707 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001708 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001709 }
1710
1711 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001712 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001713 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001714 return;
1715 }
1716
Amith Yamasani2a003292012-08-14 18:25:45 -07001717 mNextSerialNumber = -1;
1718 if (parser.getName().equals(TAG_USERS)) {
1719 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1720 if (lastSerialNumber != null) {
1721 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1722 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001723 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1724 if (versionNumber != null) {
1725 mUserVersion = Integer.parseInt(versionNumber);
1726 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001727 }
1728
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001729 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1730
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001731 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301732 if (type == XmlPullParser.START_TAG) {
1733 final String name = parser.getName();
1734 if (name.equals(TAG_USER)) {
1735 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001736
Amith Yamasani12747872015-12-07 14:19:49 -08001737 UserData userData = readUserLP(Integer.parseInt(id));
1738
1739 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001740 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001741 mUsers.put(userData.info.id, userData);
1742 if (mNextSerialNumber < 0
1743 || mNextSerialNumber <= userData.info.id) {
1744 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001745 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301746 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001747 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301748 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001749 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1750 && type != XmlPullParser.END_TAG) {
1751 if (type == XmlPullParser.START_TAG) {
1752 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001753 synchronized (mGuestRestrictions) {
1754 UserRestrictionsUtils
1755 .readRestrictions(parser, mGuestRestrictions);
1756 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001757 }
1758 break;
1759 }
1760 }
Makoto Onuki82de3002016-09-30 09:58:15 -07001761 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1762 UserRestrictionsUtils.readRestrictions(parser,
1763 newDevicePolicyGlobalUserRestrictions);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001764 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1765 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1766 if (ownerUserId != null) {
1767 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1768 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001769 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001770 }
1771 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001772 synchronized (mRestrictionsLock) {
1773 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1774 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001775 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001776 upgradeIfNecessaryLP();
1777 } catch (IOException | XmlPullParserException e) {
1778 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001779 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001780 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001781 }
1782 }
1783
Amith Yamasani6f34b412012-10-22 18:19:27 -07001784 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001785 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001786 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001787 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001789 int userVersion = mUserVersion;
1790 if (userVersion < 1) {
1791 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001792 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1793 if ("Primary".equals(userData.info.name)) {
1794 userData.info.name =
1795 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1796 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001797 }
1798 userVersion = 1;
1799 }
1800
Amith Yamasanibc9625052012-11-15 14:39:18 -08001801 if (userVersion < 2) {
1802 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001803 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1804 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1805 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1806 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001807 }
1808 userVersion = 2;
1809 }
1810
Amith Yamasani350962c2013-08-06 11:18:53 -07001811
Amith Yamasani5e486f52013-08-07 11:06:44 -07001812 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001813 userVersion = 4;
1814 }
1815
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001816 if (userVersion < 5) {
1817 initDefaultGuestRestrictions();
1818 userVersion = 5;
1819 }
1820
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001821 if (userVersion < 6) {
1822 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001823 synchronized (mUsersLock) {
1824 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001825 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001826 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001827 if (!splitSystemUser && userData.info.isRestricted()
1828 && (userData.info.restrictedProfileParentId
1829 == UserInfo.NO_PROFILE_GROUP_ID)) {
1830 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1831 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001832 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001833 }
1834 }
1835 userVersion = 6;
1836 }
1837
Amith Yamasani6f34b412012-10-22 18:19:27 -07001838 if (userVersion < USER_VERSION) {
1839 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1840 + USER_VERSION);
1841 } else {
1842 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001843
1844 if (originalVersion < mUserVersion) {
1845 writeUserListLP();
1846 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001847 }
1848 }
1849
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001850 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001851 int flags = UserInfo.FLAG_INITIALIZED;
1852 // In split system user mode, the admin and primary flags are assigned to the first human
1853 // user.
1854 if (!UserManager.isSplitSystemUser()) {
1855 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1856 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001857 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001858 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001859 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001860 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001861 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001862
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001863 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001864 try {
1865 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1866 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1867 for (String userRestriction : defaultFirstUserRestrictions) {
1868 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1869 restrictions.putBoolean(userRestriction, true);
1870 }
1871 }
1872 } catch (Resources.NotFoundException e) {
1873 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1874 }
1875
Makoto Onuki068c54a2015-10-13 14:34:03 -07001876 synchronized (mRestrictionsLock) {
1877 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1878 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001879
Fyodor Kupolov82402752015-10-28 14:54:51 -07001880 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001881 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001882
Amith Yamasani12747872015-12-07 14:19:49 -08001883 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001884 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001885 }
1886
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001887 private String getOwnerName() {
1888 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1889 }
1890
Amith Yamasani12747872015-12-07 14:19:49 -08001891 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001892 if (DBG) {
1893 debug("scheduleWriteUser");
1894 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001895 // No need to wrap it within a lock -- worst case, we'll just post the same message
1896 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001897 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1898 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001899 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1900 }
1901 }
1902
Amith Yamasani12747872015-12-07 14:19:49 -08001903 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001904 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001905 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001906 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001907 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001908 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001909 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001910 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001911 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001912 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001913 userFile.finishWrite(fos);
1914 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001915 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001916 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001917 }
1918 }
1919
1920 /*
Kenny Guy02c89902016-11-15 19:36:38 +00001921 * Writes the user file in this format:
1922 *
1923 * <user flags="20039023" id="0">
1924 * <name>Primary</name>
1925 * </user>
1926 */
1927 @VisibleForTesting
1928 void writeUserLP(UserData userData, OutputStream os)
1929 throws IOException, XmlPullParserException {
1930 // XmlSerializer serializer = XmlUtils.serializerInstance();
1931 final XmlSerializer serializer = new FastXmlSerializer();
1932 serializer.setOutput(os, StandardCharsets.UTF_8.name());
1933 serializer.startDocument(null, true);
1934 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1935
1936 final UserInfo userInfo = userData.info;
1937 serializer.startTag(null, TAG_USER);
1938 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
1939 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
1940 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
1941 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1942 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1943 Long.toString(userInfo.lastLoggedInTime));
1944 if (userInfo.lastLoggedInFingerprint != null) {
1945 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1946 userInfo.lastLoggedInFingerprint);
1947 }
1948 if (userInfo.iconPath != null) {
1949 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1950 }
1951 if (userInfo.partial) {
1952 serializer.attribute(null, ATTR_PARTIAL, "true");
1953 }
1954 if (userInfo.guestToRemove) {
1955 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1956 }
1957 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1958 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1959 Integer.toString(userInfo.profileGroupId));
1960 }
1961 serializer.attribute(null, ATTR_PROFILE_BADGE,
1962 Integer.toString(userInfo.profileBadge));
1963 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1964 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1965 Integer.toString(userInfo.restrictedProfileParentId));
1966 }
1967 // Write seed data
1968 if (userData.persistSeedData) {
1969 if (userData.seedAccountName != null) {
1970 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1971 }
1972 if (userData.seedAccountType != null) {
1973 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1974 }
1975 }
1976 if (userInfo.name != null) {
1977 serializer.startTag(null, TAG_NAME);
1978 serializer.text(userInfo.name);
1979 serializer.endTag(null, TAG_NAME);
1980 }
1981 synchronized (mRestrictionsLock) {
1982 UserRestrictionsUtils.writeRestrictions(serializer,
1983 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1984 UserRestrictionsUtils.writeRestrictions(serializer,
1985 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1986 TAG_DEVICE_POLICY_RESTRICTIONS);
1987 }
1988
1989 if (userData.account != null) {
1990 serializer.startTag(null, TAG_ACCOUNT);
1991 serializer.text(userData.account);
1992 serializer.endTag(null, TAG_ACCOUNT);
1993 }
1994
1995 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1996 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1997 userData.seedAccountOptions.saveToXml(serializer);
1998 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1999 }
2000
2001 serializer.endTag(null, TAG_USER);
2002
2003 serializer.endDocument();
2004 }
2005
2006 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002007 * Writes the user list file in this format:
2008 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002009 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002010 * <user id="0"></user>
2011 * <user id="2"></user>
2012 * </users>
2013 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002014 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002015 if (DBG) {
2016 debug("writeUserList");
2017 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002018 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002019 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002020 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002021 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002022 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2023
2024 // XmlSerializer serializer = XmlUtils.serializerInstance();
2025 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002026 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002027 serializer.startDocument(null, true);
2028 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2029
2030 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002031 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002032 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002033
Adam Lesinskieddeb492014-09-08 17:50:03 -07002034 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002035 synchronized (mGuestRestrictions) {
2036 UserRestrictionsUtils
2037 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2038 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302039 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002040 synchronized (mRestrictionsLock) {
2041 UserRestrictionsUtils.writeRestrictions(serializer,
2042 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
2043 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002044 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
2045 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
2046 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002047 int[] userIdsToWrite;
2048 synchronized (mUsersLock) {
2049 userIdsToWrite = new int[mUsers.size()];
2050 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002051 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002052 userIdsToWrite[i] = user.id;
2053 }
2054 }
2055 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002056 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002057 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002058 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002059 }
2060
2061 serializer.endTag(null, TAG_USERS);
2062
2063 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002064 userListFile.finishWrite(fos);
2065 } catch (Exception e) {
2066 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002067 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002068 }
2069 }
2070
Amith Yamasani12747872015-12-07 14:19:49 -08002071 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002072 FileInputStream fis = null;
2073 try {
2074 AtomicFile userFile =
2075 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2076 fis = userFile.openRead();
2077 return readUserLP(id, fis);
2078 } catch (IOException ioe) {
2079 Slog.e(LOG_TAG, "Error reading user list");
2080 } catch (XmlPullParserException pe) {
2081 Slog.e(LOG_TAG, "Error reading user list");
2082 } finally {
2083 IoUtils.closeQuietly(fis);
2084 }
2085 return null;
2086 }
2087
2088 @VisibleForTesting
2089 UserData readUserLP(int id, InputStream is) throws IOException,
2090 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002091 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002092 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002093 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002094 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002095 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002096 long creationTime = 0L;
2097 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002098 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002099 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002100 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002101 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002102 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002103 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002104 boolean persistSeedData = false;
2105 String seedAccountName = null;
2106 String seedAccountType = null;
2107 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002108 Bundle baseRestrictions = new Bundle();
2109 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002110
Kenny Guy02c89902016-11-15 19:36:38 +00002111 XmlPullParser parser = Xml.newPullParser();
2112 parser.setInput(is, StandardCharsets.UTF_8.name());
2113 int type;
2114 while ((type = parser.next()) != XmlPullParser.START_TAG
2115 && type != XmlPullParser.END_DOCUMENT) {
2116 // Skip
2117 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002118
Kenny Guy02c89902016-11-15 19:36:38 +00002119 if (type != XmlPullParser.START_TAG) {
2120 Slog.e(LOG_TAG, "Unable to read user " + id);
2121 return null;
2122 }
2123
2124 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2125 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2126 if (storedId != id) {
2127 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002128 return null;
2129 }
Kenny Guy02c89902016-11-15 19:36:38 +00002130 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2131 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2132 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2133 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2134 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2135 lastLoggedInFingerprint = parser.getAttributeValue(null,
2136 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2137 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2138 UserInfo.NO_PROFILE_GROUP_ID);
2139 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2140 restrictedProfileParentId = readIntAttribute(parser,
2141 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2142 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2143 if ("true".equals(valueString)) {
2144 partial = true;
2145 }
2146 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2147 if ("true".equals(valueString)) {
2148 guestToRemove = true;
2149 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002150
Kenny Guy02c89902016-11-15 19:36:38 +00002151 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2152 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2153 if (seedAccountName != null || seedAccountType != null) {
2154 persistSeedData = true;
2155 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002156
Kenny Guy02c89902016-11-15 19:36:38 +00002157 int outerDepth = parser.getDepth();
2158 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2159 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2160 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2161 continue;
2162 }
2163 String tag = parser.getName();
2164 if (TAG_NAME.equals(tag)) {
2165 type = parser.next();
2166 if (type == XmlPullParser.TEXT) {
2167 name = parser.getText();
2168 }
2169 } else if (TAG_RESTRICTIONS.equals(tag)) {
2170 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2171 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2172 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
2173 } else if (TAG_ACCOUNT.equals(tag)) {
2174 type = parser.next();
2175 if (type == XmlPullParser.TEXT) {
2176 account = parser.getText();
2177 }
2178 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2179 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002180 persistSeedData = true;
2181 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002182 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002183 }
Kenny Guy02c89902016-11-15 19:36:38 +00002184
2185 // Create the UserInfo object that gets passed around
2186 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2187 userInfo.serialNumber = serialNumber;
2188 userInfo.creationTime = creationTime;
2189 userInfo.lastLoggedInTime = lastLoggedInTime;
2190 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2191 userInfo.partial = partial;
2192 userInfo.guestToRemove = guestToRemove;
2193 userInfo.profileGroupId = profileGroupId;
2194 userInfo.profileBadge = profileBadge;
2195 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2196
2197 // Create the UserData object that's internal to this class
2198 UserData userData = new UserData();
2199 userData.info = userInfo;
2200 userData.account = account;
2201 userData.seedAccountName = seedAccountName;
2202 userData.seedAccountType = seedAccountType;
2203 userData.persistSeedData = persistSeedData;
2204 userData.seedAccountOptions = seedAccountOptions;
2205
2206 synchronized (mRestrictionsLock) {
2207 mBaseUserRestrictions.put(id, baseRestrictions);
2208 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2209 }
2210 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002211 }
2212
Amith Yamasani920ace02012-09-20 22:15:37 -07002213 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2214 String valueString = parser.getAttributeValue(null, attr);
2215 if (valueString == null) return defaultValue;
2216 try {
2217 return Integer.parseInt(valueString);
2218 } catch (NumberFormatException nfe) {
2219 return defaultValue;
2220 }
2221 }
2222
2223 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2224 String valueString = parser.getAttributeValue(null, attr);
2225 if (valueString == null) return defaultValue;
2226 try {
2227 return Long.parseLong(valueString);
2228 } catch (NumberFormatException nfe) {
2229 return defaultValue;
2230 }
2231 }
2232
Amith Yamasanib82add22013-07-09 11:24:44 -07002233 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002234 * Removes the app restrictions file for a specific package and user id, if it exists.
2235 */
2236 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2237 synchronized (mPackagesLock) {
2238 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002239 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002240 if (resFile.exists()) {
2241 resFile.delete();
2242 }
2243 }
2244 }
2245
Kenny Guya52dc3e2014-02-11 15:33:14 +00002246 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002247 public UserInfo createProfileForUser(String name, int flags, int userId,
2248 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002249 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002250 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002251 }
2252
Amith Yamasani258848d2012-08-10 17:06:33 -07002253 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002254 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2255 String[] disallowedPackages) {
2256 checkManageOrCreateUsersPermission(flags);
2257 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2258 }
2259
2260 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002261 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002262 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002263 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002264 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002265
Jessica Hummelbe81c802014-04-22 15:49:22 +01002266 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002267 return createUserInternal(name, flags, parentId, null);
2268 }
2269
2270 private UserInfo createUserInternal(String name, int flags, int parentId,
2271 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002272 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2273 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2274 : UserManager.DISALLOW_ADD_USER;
2275 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2276 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002277 return null;
2278 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002279 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2280 }
2281
2282 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2283 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002284 DeviceStorageMonitorInternal dsm = LocalServices
2285 .getService(DeviceStorageMonitorInternal.class);
2286 if (dsm.isMemoryLow()) {
2287 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2288 return null;
2289 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002290 if (ActivityManager.isLowRamDeviceStatic()) {
2291 return null;
2292 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002293 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002294 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002295 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002296 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002297 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002298 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002299 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002300 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002301 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002302 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002303 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002304 if (parentId != UserHandle.USER_NULL) {
2305 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002306 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002307 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002308 if (parent == null) return null;
2309 }
2310 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2311 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2312 return null;
2313 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002314 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2315 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002316 // been reached, cannot add a user.
2317 return null;
2318 }
2319 // If we're adding a guest and there already exists one, bail.
2320 if (isGuest && findCurrentGuestUser() != null) {
2321 return null;
2322 }
2323 // In legacy mode, restricted profile's parent can only be the owner user
2324 if (isRestricted && !UserManager.isSplitSystemUser()
2325 && (parentId != UserHandle.USER_SYSTEM)) {
2326 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2327 return null;
2328 }
2329 if (isRestricted && UserManager.isSplitSystemUser()) {
2330 if (parent == null) {
2331 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2332 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002333 return null;
2334 }
Amith Yamasani12747872015-12-07 14:19:49 -08002335 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002336 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2337 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002338 return null;
2339 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002340 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002341 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2342 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002343 Log.e(LOG_TAG,
2344 "Ephemeral users are supported on split-system-user systems only.");
2345 return null;
2346 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002347 // In split system user mode, we assign the first human user the primary flag.
2348 // And if there is no device owner, we also assign the admin flag to primary user.
2349 if (UserManager.isSplitSystemUser()
2350 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2351 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002352 synchronized (mUsersLock) {
2353 if (!mIsDeviceManaged) {
2354 flags |= UserInfo.FLAG_ADMIN;
2355 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002356 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002357 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002358
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002359 userId = getNextAvailableId();
2360 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002361 boolean ephemeralGuests = Resources.getSystem()
2362 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002363
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002364 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002365 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2366 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2367 || (parent != null && parent.info.isEphemeral())) {
2368 flags |= UserInfo.FLAG_EPHEMERAL;
2369 }
2370
2371 userInfo = new UserInfo(userId, name, null, flags);
2372 userInfo.serialNumber = mNextSerialNumber++;
2373 long now = System.currentTimeMillis();
2374 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2375 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002376 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002377 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2378 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2379 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002380 userData = new UserData();
2381 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002382 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002383 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002384 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002385 writeUserListLP();
2386 if (parent != null) {
2387 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002388 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2389 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002390 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002391 }
Amith Yamasani12747872015-12-07 14:19:49 -08002392 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002393 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002394 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2395 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002396 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002397 }
Amith Yamasani12747872015-12-07 14:19:49 -08002398 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002399 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002400 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002401 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002402 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002403 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002404 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002405 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002406 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002407 userInfo.partial = false;
2408 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002409 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002410 }
2411 updateUserIds();
2412 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002413 if (isGuest) {
2414 synchronized (mGuestRestrictions) {
2415 restrictions.putAll(mGuestRestrictions);
2416 }
2417 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002418 synchronized (mRestrictionsLock) {
2419 mBaseUserRestrictions.append(userId, restrictions);
2420 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002421 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002422 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2423 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2424 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2425 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002426 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002427 } finally {
2428 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002429 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002430 return userInfo;
2431 }
2432
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002433 @VisibleForTesting
2434 UserData putUserInfo(UserInfo userInfo) {
2435 final UserData userData = new UserData();
2436 userData.info = userInfo;
2437 synchronized (mUsers) {
2438 mUsers.put(userInfo.id, userData);
2439 }
2440 return userData;
2441 }
2442
2443 @VisibleForTesting
2444 void removeUserInfo(int userId) {
2445 synchronized (mUsers) {
2446 mUsers.remove(userId);
2447 }
2448 }
2449
Amith Yamasani0b285492011-04-14 17:35:23 -07002450 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002451 * @hide
2452 */
Amith Yamasani12747872015-12-07 14:19:49 -08002453 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002454 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002455 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002456 final UserInfo user = createProfileForUser(
2457 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002458 if (user == null) {
2459 return null;
2460 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002461 long identity = Binder.clearCallingIdentity();
2462 try {
2463 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2464 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2465 // the putIntForUser() will fail.
2466 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2467 android.provider.Settings.Secure.LOCATION_MODE,
2468 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2469 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2470 } finally {
2471 Binder.restoreCallingIdentity(identity);
2472 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002473 return user;
2474 }
2475
2476 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002477 * Find the current guest user. If the Guest user is partial,
2478 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002479 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002480 private UserInfo findCurrentGuestUser() {
2481 synchronized (mUsersLock) {
2482 final int size = mUsers.size();
2483 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002484 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002485 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2486 return user;
2487 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002488 }
2489 }
2490 return null;
2491 }
2492
2493 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002494 * Mark this guest user for deletion to allow us to create another guest
2495 * and switch to that user before actually removing this guest.
2496 * @param userHandle the userid of the current guest
2497 * @return whether the user could be marked for deletion
2498 */
Amith Yamasani12747872015-12-07 14:19:49 -08002499 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002500 public boolean markGuestForDeletion(int userHandle) {
2501 checkManageUsersPermission("Only the system can remove users");
2502 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2503 UserManager.DISALLOW_REMOVE_USER, false)) {
2504 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2505 return false;
2506 }
2507
2508 long ident = Binder.clearCallingIdentity();
2509 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002510 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002511 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002512 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002513 userData = mUsers.get(userHandle);
2514 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002515 return false;
2516 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002517 }
Amith Yamasani12747872015-12-07 14:19:49 -08002518 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002519 return false;
2520 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002521 // We set this to a guest user that is to be removed. This is a temporary state
2522 // where we are allowed to add new Guest users, even if this one is still not
2523 // removed. This user will still show up in getUserInfo() calls.
2524 // If we don't get around to removing this Guest user, it will be purged on next
2525 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002526 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002527 // Mark it as disabled, so that it isn't returned any more when
2528 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002529 userData.info.flags |= UserInfo.FLAG_DISABLED;
2530 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002531 }
2532 } finally {
2533 Binder.restoreCallingIdentity(ident);
2534 }
2535 return true;
2536 }
2537
2538 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002539 * Removes a user and all data directories created for that user. This method should be called
2540 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002541 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002542 */
Amith Yamasani12747872015-12-07 14:19:49 -08002543 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002544 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002545 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002546 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002547
2548 final boolean isManagedProfile;
2549 synchronized (mUsersLock) {
2550 UserInfo userInfo = getUserInfoLU(userHandle);
2551 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2552 }
2553 String restriction = isManagedProfile
2554 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2555 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2556 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002557 return false;
2558 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002559 return removeUserUnchecked(userHandle);
2560 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002561
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002562 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002563 long ident = Binder.clearCallingIdentity();
2564 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002565 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002566 int currentUser = ActivityManager.getCurrentUser();
2567 if (currentUser == userHandle) {
2568 Log.w(LOG_TAG, "Current user cannot be removed");
2569 return false;
2570 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002571 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002572 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002573 userData = mUsers.get(userHandle);
2574 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002575 return false;
2576 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002577
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002578 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002579 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002580
Kenny Guyee58b4f2014-05-23 15:19:53 +01002581 try {
2582 mAppOpsService.removeUser(userHandle);
2583 } catch (RemoteException e) {
2584 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2585 }
2586 // Set this to a partially created user, so that the user will be purged
2587 // on next startup, in case the runtime stops now before stopping and
2588 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002589 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002590 // Mark it as disabled, so that it isn't returned any more when
2591 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002592 userData.info.flags |= UserInfo.FLAG_DISABLED;
2593 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002594 }
2595
Amith Yamasani12747872015-12-07 14:19:49 -08002596 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2597 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002598 // Send broadcast to notify system that the user removed was a
2599 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002600 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002601 }
2602
2603 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2604 int res;
2605 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002606 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002607 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002608 @Override
2609 public void userStopped(int userId) {
2610 finishRemoveUser(userId);
2611 }
2612 @Override
2613 public void userStopAborted(int userId) {
2614 }
2615 });
2616 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002617 return false;
2618 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002619 return res == ActivityManager.USER_OP_SUCCESS;
2620 } finally {
2621 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002622 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002623 }
2624
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002625 @VisibleForTesting
2626 void addRemovingUserIdLocked(int userId) {
2627 // We remember deleted user IDs to prevent them from being
2628 // reused during the current boot; they can still be reused
2629 // after a reboot or recycling of userIds.
2630 mRemovingUserIds.put(userId, true);
2631 mRecentlyRemovedIds.add(userId);
2632 // Keep LRU queue of recently removed IDs for recycling
2633 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2634 mRecentlyRemovedIds.removeFirst();
2635 }
2636 }
2637
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002638 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002639 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002640 // Let other services shutdown any activity and clean up their state before completely
2641 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002642 long ident = Binder.clearCallingIdentity();
2643 try {
2644 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2645 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002646 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2647 android.Manifest.permission.MANAGE_USERS,
2648
2649 new BroadcastReceiver() {
2650 @Override
2651 public void onReceive(Context context, Intent intent) {
2652 if (DBG) {
2653 Slog.i(LOG_TAG,
2654 "USER_REMOVED broadcast sent, cleaning up user data "
2655 + userHandle);
2656 }
2657 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002658 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002659 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002660 // Clean up any ActivityManager state
2661 LocalServices.getService(ActivityManagerInternal.class)
2662 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002663 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002664 }
2665 }.start();
2666 }
2667 },
2668
2669 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002670 } finally {
2671 Binder.restoreCallingIdentity(ident);
2672 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002673 }
2674
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002675 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002676 try {
2677 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2678 } catch (IllegalStateException e) {
2679 // This may be simply because the user was partially created.
2680 Slog.i(LOG_TAG,
2681 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2682 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002683
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002684 // Cleanup gatekeeper secure user id
2685 try {
2686 final IGateKeeperService gk = GateKeeper.getService();
2687 if (gk != null) {
2688 gk.clearSecureUserId(userHandle);
2689 }
2690 } catch (Exception ex) {
2691 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2692 }
2693
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002694 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002695 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002696
2697 // Clean up all data before removing metadata
2698 mPm.destroyUserData(userHandle,
2699 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2700
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002701 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002702 synchronized (mUsersLock) {
2703 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002704 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002705 }
2706 synchronized (mUserStates) {
2707 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002708 }
2709 synchronized (mRestrictionsLock) {
2710 mBaseUserRestrictions.remove(userHandle);
2711 mAppliedUserRestrictions.remove(userHandle);
2712 mCachedEffectiveUserRestrictions.remove(userHandle);
2713 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002714 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002715 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002716 synchronized (mPackagesLock) {
2717 writeUserListLP();
2718 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002719 // Remove user file
2720 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2721 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002722 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002723 if (RELEASE_DELETED_USER_ID) {
2724 synchronized (mUsers) {
2725 mRemovingUserIds.delete(userHandle);
2726 }
2727 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002728 }
2729
Kenny Guyf8d3a232014-05-15 16:09:52 +01002730 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002731 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002732 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2733 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002734 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002735 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002736 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002737 }
2738
Amith Yamasani2a003292012-08-14 18:25:45 -07002739 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002740 public Bundle getApplicationRestrictions(String packageName) {
2741 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2742 }
2743
2744 @Override
2745 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002746 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002747 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002748 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002749 }
2750 synchronized (mPackagesLock) {
2751 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002752 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002753 }
2754 }
2755
2756 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002757 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002758 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002759 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002760 if (restrictions != null) {
2761 restrictions.setDefusable(true);
2762 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002763 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002764 if (restrictions == null || restrictions.isEmpty()) {
2765 cleanAppRestrictionsForPackage(packageName, userId);
2766 } else {
2767 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002768 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002769 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002770 }
Robin Lee66e5d962014-04-09 16:44:21 +01002771
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002772 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2773 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2774 changeIntent.setPackage(packageName);
2775 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2776 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002777 }
2778
2779 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002780 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002781 try {
2782 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002783 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002784 } catch (NameNotFoundException nnfe) {
2785 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002786 } finally {
2787 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002788 }
2789 }
2790
Fyodor Kupolov82402752015-10-28 14:54:51 -07002791 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002792 AtomicFile restrictionsFile =
2793 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2794 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002795 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002796 }
2797
2798 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002799 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002800 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002801 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002802 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002803 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002804 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002805
2806 FileInputStream fis = null;
2807 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002808 fis = restrictionsFile.openRead();
2809 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002810 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002811 XmlUtils.nextElement(parser);
2812 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002813 Slog.e(LOG_TAG, "Unable to read restrictions file "
2814 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002815 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002816 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002817 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2818 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002819 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002820 } catch (IOException|XmlPullParserException e) {
2821 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002822 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002823 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002824 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002825 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002826 }
2827
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002828 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2829 XmlPullParser parser) throws XmlPullParserException, IOException {
2830 int type = parser.getEventType();
2831 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2832 String key = parser.getAttributeValue(null, ATTR_KEY);
2833 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2834 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2835 if (multiple != null) {
2836 values.clear();
2837 int count = Integer.parseInt(multiple);
2838 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2839 if (type == XmlPullParser.START_TAG
2840 && parser.getName().equals(TAG_VALUE)) {
2841 values.add(parser.nextText().trim());
2842 count--;
2843 }
2844 }
2845 String [] valueStrings = new String[values.size()];
2846 values.toArray(valueStrings);
2847 restrictions.putStringArray(key, valueStrings);
2848 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2849 restrictions.putBundle(key, readBundleEntry(parser, values));
2850 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2851 final int outerDepth = parser.getDepth();
2852 ArrayList<Bundle> bundleList = new ArrayList<>();
2853 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2854 Bundle childBundle = readBundleEntry(parser, values);
2855 bundleList.add(childBundle);
2856 }
2857 restrictions.putParcelableArray(key,
2858 bundleList.toArray(new Bundle[bundleList.size()]));
2859 } else {
2860 String value = parser.nextText().trim();
2861 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2862 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2863 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2864 restrictions.putInt(key, Integer.parseInt(value));
2865 } else {
2866 restrictions.putString(key, value);
2867 }
2868 }
2869 }
2870 }
2871
2872 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2873 throws IOException, XmlPullParserException {
2874 Bundle childBundle = new Bundle();
2875 final int outerDepth = parser.getDepth();
2876 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2877 readEntry(childBundle, values, parser);
2878 }
2879 return childBundle;
2880 }
2881
Fyodor Kupolov82402752015-10-28 14:54:51 -07002882 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002883 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002884 AtomicFile restrictionsFile = new AtomicFile(
2885 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002886 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002887 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002888 }
2889
2890 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002892 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002893 try {
2894 fos = restrictionsFile.startWrite();
2895 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2896
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002897 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002898 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002899 serializer.startDocument(null, true);
2900 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2901
2902 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002903 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002904 serializer.endTag(null, TAG_RESTRICTIONS);
2905
2906 serializer.endDocument();
2907 restrictionsFile.finishWrite(fos);
2908 } catch (Exception e) {
2909 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002910 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2911 }
2912 }
2913
2914 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2915 throws IOException {
2916 for (String key : restrictions.keySet()) {
2917 Object value = restrictions.get(key);
2918 serializer.startTag(null, TAG_ENTRY);
2919 serializer.attribute(null, ATTR_KEY, key);
2920
2921 if (value instanceof Boolean) {
2922 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2923 serializer.text(value.toString());
2924 } else if (value instanceof Integer) {
2925 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2926 serializer.text(value.toString());
2927 } else if (value == null || value instanceof String) {
2928 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2929 serializer.text(value != null ? (String) value : "");
2930 } else if (value instanceof Bundle) {
2931 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2932 writeBundle((Bundle) value, serializer);
2933 } else if (value instanceof Parcelable[]) {
2934 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2935 Parcelable[] array = (Parcelable[]) value;
2936 for (Parcelable parcelable : array) {
2937 if (!(parcelable instanceof Bundle)) {
2938 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2939 }
2940 serializer.startTag(null, TAG_ENTRY);
2941 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2942 writeBundle((Bundle) parcelable, serializer);
2943 serializer.endTag(null, TAG_ENTRY);
2944 }
2945 } else {
2946 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2947 String[] values = (String[]) value;
2948 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2949 for (String choice : values) {
2950 serializer.startTag(null, TAG_VALUE);
2951 serializer.text(choice != null ? choice : "");
2952 serializer.endTag(null, TAG_VALUE);
2953 }
2954 }
2955 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002956 }
2957 }
2958
2959 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002960 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002961 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002962 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002963 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002964 }
2965 }
2966
2967 @Override
2968 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002969 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002970 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002971 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002972 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002973 }
2974 // Not found
2975 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002976 }
2977 }
2978
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002979 @Override
2980 public long getUserCreationTime(int userHandle) {
2981 int callingUserId = UserHandle.getCallingUserId();
2982 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002983 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002984 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002985 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002986 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002987 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002988 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002989 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002990 }
2991 }
2992 }
2993 if (userInfo == null) {
2994 throw new SecurityException("userHandle can only be the calling user or a managed "
2995 + "profile associated with this user");
2996 }
2997 return userInfo.creationTime;
2998 }
2999
Amith Yamasani0b285492011-04-14 17:35:23 -07003000 /**
3001 * Caches the list of user ids in an array, adjusting the array size when necessary.
3002 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003003 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003004 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003005 synchronized (mUsersLock) {
3006 final int userSize = mUsers.size();
3007 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003008 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003009 num++;
3010 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003011 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003012 final int[] newUsers = new int[num];
3013 int n = 0;
3014 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003015 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003016 newUsers[n++] = mUsers.keyAt(i);
3017 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003018 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003019 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003020 }
3021 }
3022
3023 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003024 * Called right before a user is started. This gives us a chance to prepare
3025 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003026 */
3027 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003028 UserInfo userInfo = getUserInfo(userId);
3029 if (userInfo == null) {
3030 return;
3031 }
3032 final int userSerial = userInfo.serialNumber;
3033 // Migrate only if build fingerprints mismatch
3034 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003035 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003036 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003037
3038 if (userId != UserHandle.USER_SYSTEM) {
3039 synchronized (mRestrictionsLock) {
3040 applyUserRestrictionsLR(userId);
3041 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003042 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003043
3044 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003045 }
3046
3047 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003048 * Called right before a user is unlocked. This gives us a chance to prepare
3049 * app storage.
3050 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003051 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003052 UserInfo userInfo = getUserInfo(userId);
3053 if (userInfo == null) {
3054 return;
3055 }
3056 final int userSerial = userInfo.serialNumber;
3057 // Migrate only if build fingerprints mismatch
3058 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003059 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003060 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003061 }
3062
3063 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003064 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003065 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003066 * @param userId the user that was just foregrounded
3067 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003068 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003069 UserData userData = getUserDataNoChecks(userId);
3070 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003071 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3072 return;
3073 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003074
3075 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003076 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003077 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003078 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003079 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3080 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003081 }
3082
Amith Yamasanieb437d42016-04-29 09:31:25 -07003083 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07003084 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07003085 String demoLauncher =
3086 mContext.getResources().getString(
3087 com.android.internal.R.string.config_demoModeLauncherComponent);
3088 if (!TextUtils.isEmpty(demoLauncher)) {
3089 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07003090 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00003091 try {
3092 final IPackageManager iPm = AppGlobals.getPackageManager();
3093 iPm.setComponentEnabledSetting(componentToEnable,
3094 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3095 /* userId= */ userId);
3096 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3097 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3098 /* userId= */ userId, null);
3099 } catch (RemoteException re) {
3100 // Internal, shouldn't happen
3101 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003102 }
3103 }
3104 }
3105
Amith Yamasani920ace02012-09-20 22:15:37 -07003106 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003107 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003108 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003109 @VisibleForTesting
3110 int getNextAvailableId() {
3111 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003112 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003113 nextId = scanNextAvailableIdLocked();
3114 if (nextId >= 0) {
3115 return nextId;
3116 }
3117 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3118 // except most recently removed
3119 if (mRemovingUserIds.size() > 0) {
3120 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3121 mRemovingUserIds.clear();
3122 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3123 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003124 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003125 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003126 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003127 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003128 if (nextId < 0) {
3129 throw new IllegalStateException("No user id available!");
3130 }
3131 return nextId;
3132 }
3133
3134 private int scanNextAvailableIdLocked() {
3135 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3136 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3137 return i;
3138 }
3139 }
3140 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003141 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003142
Amith Yamasanifc95e702013-09-26 13:20:17 -07003143 private String packageToRestrictionsFileName(String packageName) {
3144 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3145 }
3146
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003147 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003148 * Enforce that serial number stored in user directory inode matches the
3149 * given expected value. Gracefully sets the serial number if currently
3150 * undefined.
3151 *
3152 * @throws IOException when problem extracting serial number, or serial
3153 * number is mismatched.
3154 */
3155 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003156 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3157 // When we're emulating FBE, the directory may have been chmod
3158 // 000'ed, meaning we can't read the serial number to enforce it;
3159 // instead of destroying the user, just log a warning.
3160 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3161 return;
3162 }
3163
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003164 final int foundSerial = getSerialNumber(file);
3165 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3166
3167 if (foundSerial == -1) {
3168 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3169 try {
3170 setSerialNumber(file, serialNumber);
3171 } catch (IOException e) {
3172 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3173 }
3174
3175 } else if (foundSerial != serialNumber) {
3176 throw new IOException("Found serial number " + foundSerial
3177 + " doesn't match expected " + serialNumber);
3178 }
3179 }
3180
3181 /**
3182 * Set serial number stored in user directory inode.
3183 *
3184 * @throws IOException if serial number was already set
3185 */
3186 private static void setSerialNumber(File file, int serialNumber)
3187 throws IOException {
3188 try {
3189 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3190 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3191 } catch (ErrnoException e) {
3192 throw e.rethrowAsIOException();
3193 }
3194 }
3195
3196 /**
3197 * Return serial number stored in user directory inode.
3198 *
3199 * @return parsed serial number, or -1 if not set
3200 */
3201 private static int getSerialNumber(File file) throws IOException {
3202 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003203 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3204 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003205 try {
3206 return Integer.parseInt(serial);
3207 } catch (NumberFormatException e) {
3208 throw new IOException("Bad serial number: " + serial);
3209 }
3210 } catch (ErrnoException e) {
3211 if (e.errno == OsConstants.ENODATA) {
3212 return -1;
3213 } else {
3214 throw e.rethrowAsIOException();
3215 }
3216 }
3217 }
3218
Amith Yamasani920ace02012-09-20 22:15:37 -07003219 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003220 public void setSeedAccountData(int userId, String accountName, String accountType,
3221 PersistableBundle accountOptions, boolean persist) {
3222 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3223 synchronized (mPackagesLock) {
3224 final UserData userData;
3225 synchronized (mUsersLock) {
3226 userData = getUserDataLU(userId);
3227 if (userData == null) {
3228 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3229 return;
3230 }
3231 userData.seedAccountName = accountName;
3232 userData.seedAccountType = accountType;
3233 userData.seedAccountOptions = accountOptions;
3234 userData.persistSeedData = persist;
3235 }
3236 if (persist) {
3237 writeUserLP(userData);
3238 }
3239 }
3240 }
3241
3242 @Override
3243 public String getSeedAccountName() throws RemoteException {
3244 checkManageUsersPermission("Cannot get seed account information");
3245 synchronized (mUsersLock) {
3246 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3247 return userData.seedAccountName;
3248 }
3249 }
3250
3251 @Override
3252 public String getSeedAccountType() throws RemoteException {
3253 checkManageUsersPermission("Cannot get seed account information");
3254 synchronized (mUsersLock) {
3255 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3256 return userData.seedAccountType;
3257 }
3258 }
3259
3260 @Override
3261 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3262 checkManageUsersPermission("Cannot get seed account information");
3263 synchronized (mUsersLock) {
3264 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3265 return userData.seedAccountOptions;
3266 }
3267 }
3268
3269 @Override
3270 public void clearSeedAccountData() throws RemoteException {
3271 checkManageUsersPermission("Cannot clear seed account information");
3272 synchronized (mPackagesLock) {
3273 UserData userData;
3274 synchronized (mUsersLock) {
3275 userData = getUserDataLU(UserHandle.getCallingUserId());
3276 if (userData == null) return;
3277 userData.clearSeedAccountData();
3278 }
3279 writeUserLP(userData);
3280 }
3281 }
3282
3283 @Override
3284 public boolean someUserHasSeedAccount(String accountName, String accountType)
3285 throws RemoteException {
3286 checkManageUsersPermission("Cannot check seed account information");
3287 synchronized (mUsersLock) {
3288 final int userSize = mUsers.size();
3289 for (int i = 0; i < userSize; i++) {
3290 final UserData data = mUsers.valueAt(i);
3291 if (data.info.isInitialized()) continue;
3292 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3293 continue;
3294 }
3295 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3296 continue;
3297 }
3298 return true;
3299 }
3300 }
3301 return false;
3302 }
3303
3304 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003305 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003306 FileDescriptor err, String[] args, ShellCallback callback,
3307 ResultReceiver resultReceiver) {
3308 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003309 }
3310
3311 int onShellCommand(Shell shell, String cmd) {
3312 if (cmd == null) {
3313 return shell.handleDefaultCommands(cmd);
3314 }
3315
3316 final PrintWriter pw = shell.getOutPrintWriter();
3317 try {
3318 switch(cmd) {
3319 case "list":
3320 return runList(pw);
3321 }
3322 } catch (RemoteException e) {
3323 pw.println("Remote exception: " + e);
3324 }
3325 return -1;
3326 }
3327
3328 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003329 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003330 final List<UserInfo> users = getUsers(false);
3331 if (users == null) {
3332 pw.println("Error: couldn't get users");
3333 return 1;
3334 } else {
3335 pw.println("Users:");
3336 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003337 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003338 pw.println("\t" + users.get(i).toString() + running);
3339 }
3340 return 0;
3341 }
3342 }
3343
3344 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003345 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3346 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3347 != PackageManager.PERMISSION_GRANTED) {
3348 pw.println("Permission Denial: can't dump UserManager from from pid="
3349 + Binder.getCallingPid()
3350 + ", uid=" + Binder.getCallingUid()
3351 + " without permission "
3352 + android.Manifest.permission.DUMP);
3353 return;
3354 }
3355
3356 long now = System.currentTimeMillis();
3357 StringBuilder sb = new StringBuilder();
3358 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003359 synchronized (mUsersLock) {
3360 pw.println("Users:");
3361 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003362 UserData userData = mUsers.valueAt(i);
3363 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003364 continue;
3365 }
Amith Yamasani12747872015-12-07 14:19:49 -08003366 UserInfo userInfo = userData.info;
3367 final int userId = userInfo.id;
3368 pw.print(" "); pw.print(userInfo);
3369 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003370 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003371 pw.print(" <removing> ");
3372 }
Amith Yamasani12747872015-12-07 14:19:49 -08003373 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003374 pw.print(" <partial>");
3375 }
3376 pw.println();
3377 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003378 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003379 pw.println("<unknown>");
3380 } else {
3381 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003382 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003383 sb.append(" ago");
3384 pw.println(sb);
3385 }
3386 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003387 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003388 pw.println("<unknown>");
3389 } else {
3390 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003391 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003392 sb.append(" ago");
3393 pw.println(sb);
3394 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003395 pw.print(" Last logged in fingerprint: ");
3396 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003397 pw.print(" Has profile owner: ");
3398 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003399 pw.println(" Restrictions:");
3400 synchronized (mRestrictionsLock) {
3401 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003402 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003403 pw.println(" Device policy local restrictions:");
3404 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003405 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003406 pw.println(" Effective restrictions:");
3407 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003408 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003409 }
Amith Yamasani12747872015-12-07 14:19:49 -08003410
3411 if (userData.account != null) {
3412 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003413 pw.println();
3414 }
Amith Yamasani12747872015-12-07 14:19:49 -08003415
3416 if (userData.seedAccountName != null) {
3417 pw.print(" Seed account name: " + userData.seedAccountName);
3418 pw.println();
3419 if (userData.seedAccountType != null) {
3420 pw.print(" account type: " + userData.seedAccountType);
3421 pw.println();
3422 }
3423 if (userData.seedAccountOptions != null) {
3424 pw.print(" account options exist");
3425 pw.println();
3426 }
3427 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003428 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003429 }
Amith Yamasani12747872015-12-07 14:19:49 -08003430 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003431 pw.println(" Device policy global restrictions:");
3432 synchronized (mRestrictionsLock) {
3433 UserRestrictionsUtils
3434 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3435 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003436 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003437 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3438 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003439 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003440 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003441 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003442 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003443 synchronized (mUsersLock) {
3444 pw.println();
3445 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003446 if (mRemovingUserIds.size() > 0) {
3447 pw.println();
3448 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3449 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003450 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003451 synchronized (mUserStates) {
3452 pw.println(" Started users state: " + mUserStates);
3453 }
Amith Yamasani12747872015-12-07 14:19:49 -08003454 // Dump some capabilities
3455 pw.println();
3456 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3457 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003458 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3459 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003460 }
3461 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003462
3463 final class MainHandler extends Handler {
3464
3465 @Override
3466 public void handleMessage(Message msg) {
3467 switch (msg.what) {
3468 case WRITE_USER_MSG:
3469 removeMessages(WRITE_USER_MSG, msg.obj);
3470 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003471 int userId = ((UserData) msg.obj).info.id;
3472 UserData userData = getUserDataNoChecks(userId);
3473 if (userData != null) {
3474 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003475 }
3476 }
3477 }
3478 }
3479 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003480
3481 /**
3482 * @param userId
3483 * @return whether the user has been initialized yet
3484 */
3485 boolean isInitialized(int userId) {
3486 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3487 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003488
3489 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003490 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003491 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3492 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003493 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003494 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003495 }
3496
3497 @Override
3498 public Bundle getBaseUserRestrictions(int userId) {
3499 synchronized (mRestrictionsLock) {
3500 return mBaseUserRestrictions.get(userId);
3501 }
3502 }
3503
3504 @Override
3505 public void setBaseUserRestrictionsByDpmsForMigration(
3506 int userId, Bundle baseRestrictions) {
3507 synchronized (mRestrictionsLock) {
3508 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003509 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003510 }
3511
Amith Yamasani12747872015-12-07 14:19:49 -08003512 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003513 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003514 if (userData != null) {
3515 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003516 } else {
3517 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3518 }
3519 }
3520 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003521
3522 @Override
3523 public boolean getUserRestriction(int userId, String key) {
3524 return getUserRestrictions(userId).getBoolean(key);
3525 }
3526
3527 @Override
3528 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3529 synchronized (mUserRestrictionsListeners) {
3530 mUserRestrictionsListeners.add(listener);
3531 }
3532 }
3533
3534 @Override
3535 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3536 synchronized (mUserRestrictionsListeners) {
3537 mUserRestrictionsListeners.remove(listener);
3538 }
3539 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003540
3541 @Override
3542 public void setDeviceManaged(boolean isManaged) {
3543 synchronized (mUsersLock) {
3544 mIsDeviceManaged = isManaged;
3545 }
3546 }
3547
3548 @Override
3549 public void setUserManaged(int userId, boolean isManaged) {
3550 synchronized (mUsersLock) {
3551 mIsUserManaged.put(userId, isManaged);
3552 }
3553 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003554
3555 @Override
3556 public void setUserIcon(int userId, Bitmap bitmap) {
3557 long ident = Binder.clearCallingIdentity();
3558 try {
3559 synchronized (mPackagesLock) {
3560 UserData userData = getUserDataNoChecks(userId);
3561 if (userData == null || userData.info.partial) {
3562 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3563 return;
3564 }
3565 writeBitmapLP(userData.info, bitmap);
3566 writeUserLP(userData);
3567 }
3568 sendUserInfoChangedBroadcast(userId);
3569 } finally {
3570 Binder.restoreCallingIdentity(ident);
3571 }
3572 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003573
3574 @Override
3575 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3576 synchronized (mUsersLock) {
3577 mForceEphemeralUsers = forceEphemeralUsers;
3578 }
3579 }
3580
3581 @Override
3582 public void removeAllUsers() {
3583 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3584 // Remove the non-system users straight away.
3585 removeNonSystemUsers();
3586 } else {
3587 // Switch to the system user first and then remove the other users.
3588 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3589 @Override
3590 public void onReceive(Context context, Intent intent) {
3591 int userId =
3592 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3593 if (userId != UserHandle.USER_SYSTEM) {
3594 return;
3595 }
3596 mContext.unregisterReceiver(this);
3597 removeNonSystemUsers();
3598 }
3599 };
3600 IntentFilter userSwitchedFilter = new IntentFilter();
3601 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3602 mContext.registerReceiver(
3603 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3604
3605 // Switch to the system user.
3606 ActivityManager am =
3607 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3608 am.switchUser(UserHandle.USER_SYSTEM);
3609 }
3610 }
phweisse9c44062016-02-10 12:57:38 +01003611
3612 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003613 public void onEphemeralUserStop(int userId) {
3614 synchronized (mUsersLock) {
3615 UserInfo userInfo = getUserInfoLU(userId);
3616 if (userInfo != null && userInfo.isEphemeral()) {
3617 // Do not allow switching back to the ephemeral user again as the user is going
3618 // to be deleted.
3619 userInfo.flags |= UserInfo.FLAG_DISABLED;
3620 if (userInfo.isGuest()) {
3621 // Indicate that the guest will be deleted after it stops.
3622 userInfo.guestToRemove = true;
3623 }
3624 }
3625 }
3626 }
3627
3628 @Override
phweisse9c44062016-02-10 12:57:38 +01003629 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003630 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003631 // Keep this in sync with UserManager.createUser
3632 if (user != null && !user.isAdmin()) {
3633 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3634 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3635 }
3636 return user;
3637 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003638
3639 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003640 public boolean removeUserEvenWhenDisallowed(int userId) {
3641 return removeUserUnchecked(userId);
3642 }
3643
3644 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003645 public boolean isUserRunning(int userId) {
3646 synchronized (mUserStates) {
3647 return mUserStates.get(userId, -1) >= 0;
3648 }
3649 }
3650
3651 @Override
3652 public void setUserState(int userId, int userState) {
3653 synchronized (mUserStates) {
3654 mUserStates.put(userId, userState);
3655 }
3656 }
3657
3658 @Override
3659 public void removeUserState(int userId) {
3660 synchronized (mUserStates) {
3661 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003662 }
3663 }
3664
3665 @Override
3666 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003667 synchronized (mUserStates) {
3668 int state = mUserStates.get(userId, -1);
3669 return (state == UserState.STATE_RUNNING_UNLOCKING)
3670 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003671 }
3672 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003673
3674 @Override
3675 public boolean isUserUnlocked(int userId) {
3676 synchronized (mUserStates) {
3677 int state = mUserStates.get(userId, -1);
3678 return state == UserState.STATE_RUNNING_UNLOCKED;
3679 }
3680 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003681 }
3682
3683 /* Remove all the users except of the system one. */
3684 private void removeNonSystemUsers() {
3685 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3686 synchronized (mUsersLock) {
3687 final int userSize = mUsers.size();
3688 for (int i = 0; i < userSize; i++) {
3689 UserInfo ui = mUsers.valueAt(i).info;
3690 if (ui.id != UserHandle.USER_SYSTEM) {
3691 usersToRemove.add(ui);
3692 }
3693 }
3694 }
3695 for (UserInfo ui: usersToRemove) {
3696 removeUser(ui.id);
3697 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003698 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003699
3700 private class Shell extends ShellCommand {
3701 @Override
3702 public int onCommand(String cmd) {
3703 return onShellCommand(this, cmd);
3704 }
3705
3706 @Override
3707 public void onHelp() {
3708 final PrintWriter pw = getOutPrintWriter();
3709 pw.println("User manager (user) commands:");
3710 pw.println(" help");
3711 pw.println(" Print this help text.");
3712 pw.println("");
3713 pw.println(" list");
3714 pw.println(" Prints all users on the system.");
3715 }
3716 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003717
3718 private static void debug(String message) {
3719 Log.d(LOG_TAG, message +
3720 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3721 }
Kenny Guy02c89902016-11-15 19:36:38 +00003722
3723 @VisibleForTesting
3724 static int getMaxManagedProfiles() {
3725 // Allow overriding max managed profiles on debuggable builds for testing
3726 // of multiple profiles.
3727 if (!Build.IS_DEBUGGABLE) {
3728 return MAX_MANAGED_PROFILES;
3729 } else {
3730 return SystemProperties.getInt("persist.sys.max_profiles",
3731 MAX_MANAGED_PROFILES);
3732 }
3733 }
3734
3735 @VisibleForTesting
3736 int getFreeProfileBadgeLU(int parentUserId) {
3737 int maxManagedProfiles = getMaxManagedProfiles();
3738 boolean[] usedBadges = new boolean[maxManagedProfiles];
3739 final int userSize = mUsers.size();
3740 for (int i = 0; i < userSize; i++) {
3741 UserInfo ui = mUsers.valueAt(i).info;
3742 // Check which badge indexes are already used by this profile group.
3743 if (ui.isManagedProfile()
3744 && ui.profileGroupId == parentUserId
3745 && !mRemovingUserIds.get(ui.id)
3746 && ui.profileBadge < maxManagedProfiles) {
3747 usedBadges[ui.profileBadge] = true;
3748 }
3749 }
3750 for (int i = 0; i < maxManagedProfiles; i++) {
3751 if (!usedBadges[i]) {
3752 return i;
3753 }
3754 }
3755 return 0;
3756 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003757
3758 /**
3759 * Checks if the given user has a managed profile associated with it.
3760 * @param userId The parent user
3761 * @return
3762 */
3763 boolean hasManagedProfile(int userId) {
3764 synchronized (mUsersLock) {
3765 UserInfo userInfo = getUserInfoLU(userId);
3766 final int userSize = mUsers.size();
3767 for (int i = 0; i < userSize; i++) {
3768 UserInfo profile = mUsers.valueAt(i).info;
3769 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3770 return true;
3771 }
3772 }
3773 return false;
3774 }
3775 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003776}