blob: c0de214c5833349c91db313165ce287c4128587a [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;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000036import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.content.Context;
38import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010039import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010040import android.content.IntentSender;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000041import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070042import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080043import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
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;
114import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700115import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100116import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.util.ArrayList;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700118import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.util.List;
120
Makoto Onuki068c54a2015-10-13 14:34:03 -0700121/**
122 * Service for {@link UserManager}.
123 *
124 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700125 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800126 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700127 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
128 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
129 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700130 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700131public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700132
Amith Yamasani2a003292012-08-14 18:25:45 -0700133 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800134 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800135 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700136 // Can be used for manual testing of id recycling
137 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700138
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800140 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700142 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700144 private static final String ATTR_CREATION_TIME = "created";
145 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600146 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700147 private static final String ATTR_SERIAL_NO = "serialNumber";
148 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700149 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700150 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700151 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100152 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700153 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800154 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
155 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530156 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700158 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800159 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800160 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100161 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800162 private static final String TAG_ENTRY = "entry";
163 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800164 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800165 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700166 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800167 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700168
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700169 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
170 private static final String ATTR_TYPE_STRING = "s";
171 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700172 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700173 private static final String ATTR_TYPE_BUNDLE = "B";
174 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700175
Amith Yamasani0b285492011-04-14 17:35:23 -0700176 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700177 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700178 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100179 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700180
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800181 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700182 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800183
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700184 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
185 UserInfo.FLAG_MANAGED_PROFILE
186 | UserInfo.FLAG_EPHEMERAL
187 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700188 | UserInfo.FLAG_GUEST
189 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700190
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700191 @VisibleForTesting
192 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700193 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700194 @VisibleForTesting
195 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
196
197 // Max size of the queue of recently removed users
198 @VisibleForTesting
199 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700200
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700201 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700202
Amith Yamasani920ace02012-09-20 22:15:37 -0700203 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
204
Nicolas Prevotb8186812015-08-06 15:00:03 +0100205 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700206 // without first making sure that the rest of the framework is prepared for it.
207 private static final int MAX_MANAGED_PROFILES = 1;
208
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800209 static final int WRITE_USER_MSG = 1;
210 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530211
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700212 private static final String XATTR_SERIAL = "user.serial";
213
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800214 // Tron counters
215 private static final String TRON_GUEST_CREATED = "users_guest_created";
216 private static final String TRON_USER_CREATED = "users_user_created";
217
Dianne Hackborn4428e172012-08-24 17:43:05 -0700218 private final Context mContext;
219 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700220 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700221 // Short-term lock for internal state, when interaction/sync with PM is not required
222 private final Object mUsersLock = new Object();
223 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700224
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800225 private final Handler mHandler;
226
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700227 private final File mUsersDir;
228 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800230 private static final IBinder mUserRestriconToken = new Binder();
231
Makoto Onuki068c54a2015-10-13 14:34:03 -0700232 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800233 * User-related information that is used for persisting to flash. Only UserInfo is
234 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800235 */
Amith Yamasani12747872015-12-07 14:19:49 -0800236 private static class UserData {
237 // Basic user information and properties
238 UserInfo info;
239 // Account name used when there is a strong association between a user and an account
240 String account;
241 // Account information for seeding into a newly created user. This could also be
242 // used for login validation for an existing user, for updating their credentials.
243 // In the latter case, data may not need to be persisted as it is only valid for the
244 // current login session.
245 String seedAccountName;
246 String seedAccountType;
247 PersistableBundle seedAccountOptions;
248 // Whether to perist the seed account information to be available after a boot
249 boolean persistSeedData;
250
251 void clearSeedAccountData() {
252 seedAccountName = null;
253 seedAccountType = null;
254 seedAccountOptions = null;
255 persistSeedData = false;
256 }
257 }
258
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800259 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800260 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800261
262 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700263 * User restrictions set via UserManager. This doesn't include restrictions set by
264 * device owner / profile owners.
265 *
266 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
267 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
268 * maybe shared between {@link #mBaseUserRestrictions} and
269 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
270 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700271 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700272 */
273 @GuardedBy("mRestrictionsLock")
274 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
275
276 /**
277 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
278 * with device / profile owner restrictions. We'll initialize it lazily; use
279 * {@link #getEffectiveUserRestrictions} to access it.
280 *
281 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
282 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
283 * maybe shared between {@link #mBaseUserRestrictions} and
284 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
285 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700286 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700287 */
288 @GuardedBy("mRestrictionsLock")
289 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
290
Makoto Onuki4f160732015-10-27 17:15:38 -0700291 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800292 * User restrictions that have already been applied in
293 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
294 * that have changed since the last
295 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700296 */
297 @GuardedBy("mRestrictionsLock")
298 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
299
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800300 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800301 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
302 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800303 */
304 @GuardedBy("mRestrictionsLock")
305 private Bundle mDevicePolicyGlobalUserRestrictions;
306
307 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100308 * Id of the user that set global restrictions.
309 */
310 @GuardedBy("mRestrictionsLock")
311 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
312
313 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800314 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
315 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800316 */
317 @GuardedBy("mRestrictionsLock")
318 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
319
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800320 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530321 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800322
323 /**
324 * Set of user IDs being actively removed. Removed IDs linger in this set
325 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700326 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800327 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700328 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800329 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700330
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700331 /**
332 * Queue of recently removed userIds. Used for recycling of userIds
333 */
334 @GuardedBy("mUsersLock")
335 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
336
Fyodor Kupolov82402752015-10-28 14:54:51 -0700337 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700338 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800339 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700340 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700341 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700342
Jason Monk62062992014-05-06 09:55:28 -0400343 private IAppOpsService mAppOpsService;
344
Makoto Onuki068c54a2015-10-13 14:34:03 -0700345 private final LocalService mLocalService;
346
Makoto Onukie7927da2015-11-25 10:05:17 -0800347 @GuardedBy("mUsersLock")
348 private boolean mIsDeviceManaged;
349
350 @GuardedBy("mUsersLock")
351 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
352
Makoto Onukid45a4a22015-11-02 17:17:38 -0800353 @GuardedBy("mUserRestrictionsListeners")
354 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
355 new ArrayList<>();
356
Clara Bayarria1771112015-12-18 16:29:18 +0000357 private final LockPatternUtils mLockPatternUtils;
358
Ricky Waib1dd80b2016-06-07 18:00:55 +0100359 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
360 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
361
362 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
363 @Override
364 public void onReceive(Context context, Intent intent) {
365 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
366 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
367 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
368 setQuietModeEnabled(userHandle, false);
369 if (target != null) {
370 try {
371 mContext.startIntentSender(target, null, 0, 0, 0);
372 } catch (IntentSender.SendIntentException e) {
373 /* ignore */
374 }
375 }
376 }
377 }
378 };
379
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100380 /**
381 * Whether all users should be created ephemeral.
382 */
383 @GuardedBy("mUsersLock")
384 private boolean mForceEphemeralUsers;
385
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000386 @GuardedBy("mUserStates")
387 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700388
Amith Yamasani258848d2012-08-10 17:06:33 -0700389 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700390
Dianne Hackborn4428e172012-08-24 17:43:05 -0700391 public static UserManagerService getInstance() {
392 synchronized (UserManagerService.class) {
393 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700394 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700396
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700397 public static class LifeCycle extends SystemService {
398
399 private UserManagerService mUms;
400
401 /**
402 * @param context
403 */
404 public LifeCycle(Context context) {
405 super(context);
406 }
407
408 @Override
409 public void onStart() {
410 mUms = UserManagerService.getInstance();
411 publishBinderService(Context.USER_SERVICE, mUms);
412 }
413
414 @Override
415 public void onBootPhase(int phase) {
416 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
417 mUms.cleanupPartialUsers();
418 }
419 }
420 }
421
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700422 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800423 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700424 UserManagerService(Context context) {
425 this(context, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700426 }
427
Dianne Hackborn4428e172012-08-24 17:43:05 -0700428 /**
429 * Called by package manager to create the service. This is closely
430 * associated with the package manager, and the given lock is the
431 * package manager's own lock.
432 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800433 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
434 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700435 }
436
Dianne Hackborn4428e172012-08-24 17:43:05 -0700437 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800438 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 mContext = context;
440 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800442 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800443 synchronized (mPackagesLock) {
444 mUsersDir = new File(dataDir, USER_INFO_DIR);
445 mUsersDir.mkdirs();
446 // Make zeroth user directory, for services to migrate their files to that location
447 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
448 userZeroDir.mkdirs();
449 FileUtils.setPermissions(mUsersDir.toString(),
450 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
451 -1, -1);
452 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
453 initDefaultGuestRestrictions();
454 readUserListLP();
455 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700456 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700457 mLocalService = new LocalService();
458 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000459 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000460 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700461 }
462
463 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400464 mAppOpsService = IAppOpsService.Stub.asInterface(
465 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800466
467 synchronized (mRestrictionsLock) {
468 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400469 }
Samuel Tand9453b82016-03-14 15:57:02 -0700470
471 UserInfo currentGuestUser = findCurrentGuestUser();
472 if (currentGuestUser != null && !hasUserRestriction(
473 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
474 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
475 // to it, in case this guest was created in a previous version where this
476 // user restriction was not a default guest restriction.
477 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
478 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700479
Ricky Waib1dd80b2016-06-07 18:00:55 +0100480 mContext.registerReceiver(mDisableQuietModeCallback,
481 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
482 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700483 }
484
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700485 void cleanupPartialUsers() {
486 // Prune out any partially created, partially removed and ephemeral users.
487 ArrayList<UserInfo> partials = new ArrayList<>();
488 synchronized (mUsersLock) {
489 final int userSize = mUsers.size();
490 for (int i = 0; i < userSize; i++) {
491 UserInfo ui = mUsers.valueAt(i).info;
492 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
493 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700494 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700495 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700496 }
497 }
498 }
499 final int partialsSize = partials.size();
500 for (int i = 0; i < partialsSize; i++) {
501 UserInfo ui = partials.get(i);
502 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
503 + " (name=" + ui.name + ")");
504 removeUserState(ui.id);
505 }
506 }
507
Amith Yamasani258848d2012-08-10 17:06:33 -0700508 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800509 public String getUserAccount(int userId) {
510 checkManageUserAndAcrossUsersFullPermission("get user account");
511 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800512 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800513 }
514 }
515
516 @Override
517 public void setUserAccount(int userId, String accountName) {
518 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800519 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800520 synchronized (mPackagesLock) {
521 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800522 final UserData userData = mUsers.get(userId);
523 if (userData == null) {
524 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
525 return;
526 }
527 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800528 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800529 userData.account = accountName;
530 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800531 }
532 }
533
534 if (userToUpdate != null) {
535 writeUserLP(userToUpdate);
536 }
537 }
538 }
539
540 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700541 public UserInfo getPrimaryUser() {
542 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700543 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700544 final int userSize = mUsers.size();
545 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800546 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800547 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700548 return ui;
549 }
550 }
551 }
552 return null;
553 }
554
555 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700556 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700557 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700558 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700559 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700560 final int userSize = mUsers.size();
561 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800562 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700563 if (ui.partial) {
564 continue;
565 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800566 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700567 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700568 }
Amith Yamasani13593602012-03-22 16:16:17 -0700569 }
570 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700571 }
Amith Yamasani13593602012-03-22 16:16:17 -0700572 }
573
Amith Yamasani258848d2012-08-10 17:06:33 -0700574 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100575 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700576 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800577 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700578 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700579 } else {
580 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800581 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700582 final long ident = Binder.clearCallingIdentity();
583 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700584 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700585 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100586 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 } finally {
588 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000589 }
590 }
591
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700592 @Override
593 public int[] getProfileIds(int userId, boolean enabledOnly) {
594 if (userId != UserHandle.getCallingUserId()) {
595 checkManageUsersPermission("getting profiles related to user " + userId);
596 }
597 final long ident = Binder.clearCallingIdentity();
598 try {
599 synchronized (mUsersLock) {
600 return getProfileIdsLU(userId, enabledOnly).toArray();
601 }
602 } finally {
603 Binder.restoreCallingIdentity(ident);
604 }
605 }
606
Amith Yamasanibe465322014-04-24 13:45:17 -0700607 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700608 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700609 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
610 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
611 for (int i = 0; i < profileIds.size(); i++) {
612 int profileId = profileIds.get(i);
613 UserInfo userInfo = mUsers.get(profileId).info;
614 // If full info is not required - clear PII data to prevent 3P apps from reading it
615 if (!fullInfo) {
616 userInfo = new UserInfo(userInfo);
617 userInfo.name = null;
618 userInfo.iconPath = null;
619 } else {
620 userInfo = userWithName(userInfo);
621 }
622 users.add(userInfo);
623 }
624 return users;
625 }
626
627 /**
628 * Assume permissions already checked and caller's identity cleared
629 */
630 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700631 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700632 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700633 if (user == null) {
634 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700635 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700636 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700637 final int userSize = mUsers.size();
638 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800639 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700640 if (!isProfileOf(user, profile)) {
641 continue;
642 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100643 if (enabledOnly && !profile.isEnabled()) {
644 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700645 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700646 if (mRemovingUserIds.get(profile.id)) {
647 continue;
648 }
Tony Mak80189cd2016-04-05 17:21:42 +0100649 if (profile.partial) {
650 continue;
651 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700652 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700653 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700654 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700655 }
656
Jessica Hummelbe81c802014-04-22 15:49:22 +0100657 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700658 public int getCredentialOwnerProfile(int userHandle) {
659 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000660 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700661 synchronized (mUsersLock) {
662 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700663 if (profileParent != null) {
664 return profileParent.id;
665 }
666 }
667 }
668
669 return userHandle;
670 }
671
672 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700673 public boolean isSameProfileGroup(int userId, int otherUserId) {
674 if (userId == otherUserId) return true;
675 checkManageUsersPermission("check if in the same profile group");
676 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700677 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700678 }
679 }
680
Fyodor Kupolov82402752015-10-28 14:54:51 -0700681 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
682 synchronized (mUsersLock) {
683 UserInfo userInfo = getUserInfoLU(userId);
684 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
685 return false;
686 }
687 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
688 if (otherUserInfo == null
689 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
690 return false;
691 }
692 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700693 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700694 }
695
696 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100697 public UserInfo getProfileParent(int userHandle) {
698 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700699 synchronized (mUsersLock) {
700 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700701 }
702 }
703
Fyodor Kupolov82402752015-10-28 14:54:51 -0700704 private UserInfo getProfileParentLU(int userHandle) {
705 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700706 if (profile == null) {
707 return null;
708 }
709 int parentUserId = profile.profileGroupId;
710 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
711 return null;
712 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700713 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100714 }
715 }
716
Fyodor Kupolov82402752015-10-28 14:54:51 -0700717 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100718 return user.id == profile.id ||
719 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
720 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000721 }
722
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000723 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000724 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100725 Intent intent = new Intent();
726 if (inQuietMode) {
727 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
728 } else {
729 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
730 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000731 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
732 intent.putExtra(Intent.EXTRA_USER, profileHandle);
733 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000734 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000735 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000736 }
737
738 @Override
739 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
740 checkManageUsersPermission("silence profile");
741 boolean changed = false;
742 UserInfo profile, parent;
743 synchronized (mPackagesLock) {
744 synchronized (mUsersLock) {
745 profile = getUserInfoLU(userHandle);
746 parent = getProfileParentLU(userHandle);
747
748 }
749 if (profile == null || !profile.isManagedProfile()) {
750 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
751 }
752 if (profile.isQuietModeEnabled() != enableQuietMode) {
753 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800754 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000755 changed = true;
756 }
757 }
758 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000759 long identity = Binder.clearCallingIdentity();
760 try {
761 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100762 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100763 LocalServices.getService(ActivityManagerInternal.class)
764 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000765 } else {
766 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
767 }
768 } catch (RemoteException e) {
769 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
770 } finally {
771 Binder.restoreCallingIdentity(identity);
772 }
773
774 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
775 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000776 }
777 }
778
779 @Override
780 public boolean isQuietModeEnabled(int userHandle) {
781 synchronized (mPackagesLock) {
782 UserInfo info;
783 synchronized (mUsersLock) {
784 info = getUserInfoLU(userHandle);
785 }
786 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000787 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000788 }
789 return info.isQuietModeEnabled();
790 }
791 }
792
Kenny Guya52dc3e2014-02-11 15:33:14 +0000793 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100794 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100795 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600796 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100797 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100798 // if the user is already unlocked, no need to show a profile challenge
799 setQuietModeEnabled(userHandle, false);
800 return true;
801 }
802
803 long identity = Binder.clearCallingIdentity();
804 try {
805 // otherwise, we show a profile challenge to trigger decryption of the user
806 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
807 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100808 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
809 // lock, confirm screenlock page will know and show personal challenge, and unlock
810 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100811 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
812 userHandle);
813 if (unlockIntent == null) {
814 return false;
815 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100816 final Intent callBackIntent = new Intent(
817 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100818 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100819 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100820 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100821 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
822 callBackIntent.setPackage(mContext.getPackageName());
823 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
824 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
825 mContext,
826 0,
827 callBackIntent,
828 PendingIntent.FLAG_CANCEL_CURRENT |
829 PendingIntent.FLAG_ONE_SHOT |
830 PendingIntent.FLAG_IMMUTABLE);
831 // After unlocking the challenge, it will disable quiet mode and run the original
832 // intentSender
833 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100834 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
835 mContext.startActivity(unlockIntent);
836 } finally {
837 Binder.restoreCallingIdentity(identity);
838 }
839 return false;
840 }
841
842 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100843 public void setUserEnabled(int userId) {
844 checkManageUsersPermission("enable user");
845 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700846 UserInfo info;
847 synchronized (mUsersLock) {
848 info = getUserInfoLU(userId);
849 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100850 if (info != null && !info.isEnabled()) {
851 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800852 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100853 }
854 }
855 }
856
857 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700858 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700859 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000860 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700861 return userWithName(getUserInfoLU(userId));
862 }
863 }
864
865 /**
866 * Returns a UserInfo object with the name filled in, for Owner, or the original
867 * if the name is already set.
868 */
869 private UserInfo userWithName(UserInfo orig) {
870 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
871 UserInfo withName = new UserInfo(orig);
872 withName.name = getOwnerName();
873 return withName;
874 } else {
875 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000876 }
877 }
878
879 @Override
880 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000881 int callingUserId = UserHandle.getCallingUserId();
882 if (callingUserId != userId && !hasManageUsersPermission()) {
883 synchronized (mPackagesLock) {
884 if (!isSameProfileGroupLP(callingUserId, userId)) {
885 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000886 "You need MANAGE_USERS permission to: check if specified user a " +
887 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000888 }
889 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000890 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700891 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700892 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000893 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700894 }
895 }
896
Amith Yamasani71e6c692013-03-24 17:39:28 -0700897 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700898 public boolean isDemoUser(int userId) {
899 int callingUserId = UserHandle.getCallingUserId();
900 if (callingUserId != userId && !hasManageUsersPermission()) {
901 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
902 + " is a demo user");
903 }
904 synchronized (mUsersLock) {
905 UserInfo userInfo = getUserInfoLU(userId);
906 return userInfo != null && userInfo.isDemo();
907 }
908 }
909
910 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700911 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700912 synchronized (mUsersLock) {
913 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700914 }
915 }
916
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700917 @Override
918 public boolean canHaveRestrictedProfile(int userId) {
919 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700920 synchronized (mUsersLock) {
921 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700922 if (userInfo == null || !userInfo.canHaveProfile()) {
923 return false;
924 }
925 if (!userInfo.isAdmin()) {
926 return false;
927 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800928 // restricted profile can be created if there is no DO set and the admin user has no PO;
929 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700930 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700931 }
932
Amith Yamasani195263742012-08-21 15:40:12 -0700933 /*
934 * Should be locked on mUsers before calling this.
935 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700936 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800937 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700938 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800939 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700940 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
941 return null;
942 }
Amith Yamasani12747872015-12-07 14:19:49 -0800943 return userData != null ? userData.info : null;
944 }
945
946 private UserData getUserDataLU(int userId) {
947 final UserData userData = mUsers.get(userId);
948 // If it is partial and not in the process of being removed, return as unknown user.
949 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
950 return null;
951 }
952 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700953 }
954
Fyodor Kupolov82402752015-10-28 14:54:51 -0700955 /**
956 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
957 * <p>No permissions checking or any addition checks are made</p>
958 */
959 private UserInfo getUserInfoNoChecks(int userId) {
960 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800961 final UserData userData = mUsers.get(userId);
962 return userData != null ? userData.info : null;
963 }
964 }
965
966 /**
967 * Obtains {@link #mUsersLock} and return UserData from mUsers.
968 * <p>No permissions checking or any addition checks are made</p>
969 */
970 private UserData getUserDataNoChecks(int userId) {
971 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700972 return mUsers.get(userId);
973 }
974 }
975
Amith Yamasani236b2b52015-08-18 14:32:14 -0700976 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700977 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700978 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700979 }
980
Amith Yamasani258848d2012-08-10 17:06:33 -0700981 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700982 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700983 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700984 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700985 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800986 UserData userData = getUserDataNoChecks(userId);
987 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700988 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
989 return;
990 }
Amith Yamasani12747872015-12-07 14:19:49 -0800991 if (name != null && !name.equals(userData.info.name)) {
992 userData.info.name = name;
993 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700994 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700995 }
996 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700997 if (changed) {
998 sendUserInfoChangedBroadcast(userId);
999 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001000 }
1001
Amith Yamasani258848d2012-08-10 17:06:33 -07001002 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001003 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001004 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001005 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1006 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1007 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001008 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001009 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001010 }
1011
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001012
1013
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001014 private void sendUserInfoChangedBroadcast(int userId) {
1015 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1016 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1017 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001018 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001019 }
1020
Amith Yamasani258848d2012-08-10 17:06:33 -07001021 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001022 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001023 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001024 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001025 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1026 if (targetUserInfo == null || targetUserInfo.partial) {
1027 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001028 return null;
1029 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001030
1031 final int callingUserId = UserHandle.getCallingUserId();
1032 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1033 final int targetGroupId = targetUserInfo.profileGroupId;
1034 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1035 && callingGroupId == targetGroupId);
1036 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001037 checkManageUsersPermission("get the icon of a user who is not related");
1038 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001039
1040 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001041 return null;
1042 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001043 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001044 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001045
1046 try {
1047 return ParcelFileDescriptor.open(
1048 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1049 } catch (FileNotFoundException e) {
1050 Log.e(LOG_TAG, "Couldn't find icon file", e);
1051 }
1052 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001053 }
1054
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001055 public void makeInitialized(int userId) {
1056 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001057 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001058 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001059 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001060 userData = mUsers.get(userId);
1061 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001062 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001063 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001064 }
Amith Yamasani12747872015-12-07 14:19:49 -08001065 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1066 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001067 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001068 }
1069 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001070 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001071 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001072 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001073 }
1074
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001075 /**
1076 * If default guest restrictions haven't been initialized yet, add the basic
1077 * restrictions.
1078 */
1079 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001080 synchronized (mGuestRestrictions) {
1081 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001082 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001083 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001084 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1085 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1086 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001087 }
1088 }
1089
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001090 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301091 public Bundle getDefaultGuestRestrictions() {
1092 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001093 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301094 return new Bundle(mGuestRestrictions);
1095 }
1096 }
1097
1098 @Override
1099 public void setDefaultGuestRestrictions(Bundle restrictions) {
1100 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001101 synchronized (mGuestRestrictions) {
1102 mGuestRestrictions.clear();
1103 mGuestRestrictions.putAll(restrictions);
1104 }
1105 synchronized (mPackagesLock) {
1106 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301107 }
1108 }
1109
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001110 /**
1111 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1112 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001113 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001114 @Nullable Bundle global) {
1115 Preconditions.checkNotNull(local);
1116 boolean globalChanged = false;
1117 boolean localChanged;
1118 synchronized (mRestrictionsLock) {
1119 if (global != null) {
1120 // Update global.
1121 globalChanged = !UserRestrictionsUtils.areEqual(
1122 mDevicePolicyGlobalUserRestrictions, global);
1123 if (globalChanged) {
1124 mDevicePolicyGlobalUserRestrictions = global;
1125 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001126 // Remember the global restriction owner userId to be able to make a distinction
1127 // in getUserRestrictionSource on who set local policies.
1128 mGlobalRestrictionOwnerUserId = userId;
1129 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001130 if (mGlobalRestrictionOwnerUserId == userId) {
1131 // When profile owner sets restrictions it passes null global bundle and we
1132 // reset global restriction owner userId.
1133 // This means this user used to have DO, but now the DO is gone and the user
1134 // instead has PO.
1135 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1136 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001137 }
1138 {
1139 // Update local.
1140 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1141 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1142 if (localChanged) {
1143 mDevicePolicyLocalUserRestrictions.put(userId, local);
1144 }
1145 }
1146 }
1147 if (DBG) {
1148 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1149 + " global=" + global + (globalChanged ? " (changed)" : "")
1150 + " local=" + local + (localChanged ? " (changed)" : "")
1151 );
1152 }
1153 // Don't call them within the mRestrictionsLock.
1154 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001155 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001156 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001157 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001158 if (globalChanged) {
1159 writeUserListLP();
1160 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001161 }
1162
1163 synchronized (mRestrictionsLock) {
1164 if (globalChanged) {
1165 applyUserRestrictionsForAllUsersLR();
1166 } else if (localChanged) {
1167 applyUserRestrictionsLR(userId);
1168 }
1169 }
1170 }
1171
Makoto Onuki068c54a2015-10-13 14:34:03 -07001172 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001173 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001174 final Bundle baseRestrictions =
1175 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1176 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1177 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001178
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001179 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1180 // Common case first.
1181 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001182 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001183 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1184 UserRestrictionsUtils.merge(effective, global);
1185 UserRestrictionsUtils.merge(effective, local);
1186
Makoto Onuki068c54a2015-10-13 14:34:03 -07001187 return effective;
1188 }
1189
1190 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001191 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001192 if (DBG) {
1193 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1194 }
1195 mCachedEffectiveUserRestrictions.remove(userId);
1196 }
1197
1198 private Bundle getEffectiveUserRestrictions(int userId) {
1199 synchronized (mRestrictionsLock) {
1200 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1201 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001202 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001203 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1204 }
1205 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001206 }
1207 }
1208
Makoto Onuki068c54a2015-10-13 14:34:03 -07001209 /** @return a specific user restriction that's in effect currently. */
1210 @Override
1211 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001212 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1213 return false;
1214 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001215 Bundle restrictions = getEffectiveUserRestrictions(userId);
1216 return restrictions != null && restrictions.getBoolean(restrictionKey);
1217 }
1218
1219 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001220 * @hide
1221 *
1222 * Returns who set a user restriction on a user.
1223 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1224 * @param restrictionKey the string key representing the restriction
1225 * @param userId the id of the user for whom to retrieve the restrictions.
1226 * @return The source of user restriction. Any combination of
1227 * {@link UserManager#RESTRICTION_NOT_SET},
1228 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1229 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1230 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1231 */
1232 @Override
1233 public int getUserRestrictionSource(String restrictionKey, int userId) {
1234 checkManageUsersPermission("getUserRestrictionSource");
1235 int result = UserManager.RESTRICTION_NOT_SET;
1236
1237 // Shortcut for the most common case
1238 if (!hasUserRestriction(restrictionKey, userId)) {
1239 return result;
1240 }
1241
1242 if (hasBaseUserRestriction(restrictionKey, userId)) {
1243 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1244 }
1245
1246 synchronized(mRestrictionsLock) {
1247 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1248 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1249 && localRestrictions.getBoolean(restrictionKey)) {
1250 // Local restrictions may have been set by device owner the userId of which is
1251 // stored in mGlobalRestrictionOwnerUserId.
1252 if (mGlobalRestrictionOwnerUserId == userId) {
1253 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1254 } else {
1255 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1256 }
1257 }
1258 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1259 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1260 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1261 }
1262 }
1263
1264 return result;
1265 }
1266
1267 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001268 * @return UserRestrictions that are in effect currently. This always returns a new
1269 * {@link Bundle}.
1270 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001271 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001272 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001273 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001274 }
1275
1276 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001277 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1278 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001279 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1280 return false;
1281 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001282 synchronized (mRestrictionsLock) {
1283 Bundle bundle = mBaseUserRestrictions.get(userId);
1284 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1285 }
1286 }
1287
1288 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001289 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001290 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001291 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1292 return;
1293 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001294 synchronized (mRestrictionsLock) {
1295 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1296 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001297 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1298 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001299 newRestrictions.putBoolean(key, value);
1300
Fyodor Kupolov82402752015-10-28 14:54:51 -07001301 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001302 }
1303 }
1304
Makoto Onuki068c54a2015-10-13 14:34:03 -07001305 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001306 * Optionally updating user restrictions, calculate the effective user restrictions and also
1307 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001308 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001309 * @param newRestrictions User restrictions to set.
1310 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001311 * @param userId target user ID.
1312 */
1313 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001314 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001315 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001316
1317 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1318 mAppliedUserRestrictions.get(userId));
1319
1320 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001321 if (newRestrictions != null) {
1322 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001323 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1324
1325 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001326 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1327 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001328
1329 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1330 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001331 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001332 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001333 }
1334
Fyodor Kupolov82402752015-10-28 14:54:51 -07001335 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001336
Makoto Onuki759a7632015-10-28 16:43:10 -07001337 mCachedEffectiveUserRestrictions.put(userId, effective);
1338
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001339 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001340 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001341 debug("Applying user restrictions: userId=" + userId
1342 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001343 }
1344
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001345 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001346 mHandler.post(new Runnable() {
1347 @Override
1348 public void run() {
1349 try {
1350 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1351 } catch (RemoteException e) {
1352 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1353 }
1354 }
1355 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001356 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001357
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001358 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001359
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001360 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001361 }
1362
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001363 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001364 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001365 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1366 // actually, but we still need some kind of synchronization otherwise we might end up
1367 // calling listeners out-of-order, thus "LR".
1368
1369 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1370 return;
1371 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001372
1373 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1374 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1375
1376 mHandler.post(new Runnable() {
1377 @Override
1378 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001379 UserRestrictionsUtils.applyUserRestrictions(
1380 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001381
Makoto Onukid45a4a22015-11-02 17:17:38 -08001382 final UserRestrictionsListener[] listeners;
1383 synchronized (mUserRestrictionsListeners) {
1384 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1385 mUserRestrictionsListeners.toArray(listeners);
1386 }
1387 for (int i = 0; i < listeners.length; i++) {
1388 listeners[i].onUserRestrictionsChanged(userId,
1389 newRestrictionsFinal, prevRestrictionsFinal);
1390 }
1391 }
1392 });
1393 }
1394
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001395 // Package private for the inner class.
1396 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001397 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001398 }
1399
1400 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001401 // Package private for the inner class.
1402 void applyUserRestrictionsForAllUsersLR() {
1403 if (DBG) {
1404 debug("applyUserRestrictionsForAllUsersLR");
1405 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001406 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001407 mCachedEffectiveUserRestrictions.clear();
1408
Makoto Onuki068c54a2015-10-13 14:34:03 -07001409 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1410 // it on a handler.
1411 final Runnable r = new Runnable() {
1412 @Override
1413 public void run() {
1414 // Then get the list of running users.
1415 final int[] runningUsers;
1416 try {
1417 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1418 } catch (RemoteException e) {
1419 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1420 return;
1421 }
1422 // Then re-calculate the effective restrictions and apply, only for running users.
1423 // It's okay if a new user has started after the getRunningUserIds() call,
1424 // because we'll do the same thing (re-calculate the restrictions and apply)
1425 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001426 synchronized (mRestrictionsLock) {
1427 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001428 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001429 }
1430 }
1431 }
1432 };
1433 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001434 }
1435
Amith Yamasani258848d2012-08-10 17:06:33 -07001436 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001437 * Check if we've hit the limit of how many users can be created.
1438 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001439 private boolean isUserLimitReached() {
1440 int count;
1441 synchronized (mUsersLock) {
1442 count = getAliveUsersExcludingGuestsCountLU();
1443 }
1444 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001445 }
1446
1447 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001448 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001449 checkManageUsersPermission("check if more managed profiles can be added.");
1450 if (ActivityManager.isLowRamDeviceStatic()) {
1451 return false;
1452 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001453 if (!mContext.getPackageManager().hasSystemFeature(
1454 PackageManager.FEATURE_MANAGED_USERS)) {
1455 return false;
1456 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001457 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001458 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1459 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1460 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001461 return false;
1462 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001463 synchronized(mUsersLock) {
1464 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001465 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001466 return false;
1467 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001468 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1469 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001470 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001471 return usersCountAfterRemoving == 1
1472 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001473 }
1474 }
1475
Fyodor Kupolov82402752015-10-28 14:54:51 -07001476 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001477 int aliveUserCount = 0;
1478 final int totalUserCount = mUsers.size();
1479 // Skip over users being removed
1480 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001481 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001482 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001483 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001484 aliveUserCount++;
1485 }
1486 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001487 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001488 }
1489
1490 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001491 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001492 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1493 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1494 * permissions can make certain calls to the UserManager.
1495 *
1496 * @param message used as message if SecurityException is thrown
1497 * @throws SecurityException if the caller does not have enough privilege.
1498 */
1499 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1500 final int uid = Binder.getCallingUid();
1501 if (uid != Process.SYSTEM_UID && uid != 0
1502 && ActivityManager.checkComponentPermission(
1503 Manifest.permission.MANAGE_USERS,
1504 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1505 && ActivityManager.checkComponentPermission(
1506 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1507 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1508 throw new SecurityException(
1509 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1510 + message);
1511 }
1512 }
1513
1514 /**
1515 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001516 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001517 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001518 *
1519 * @param message used as message if SecurityException is thrown
1520 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001521 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001522 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001523 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001524 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001525 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1526 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001527 }
1528
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001529 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001530 * Enforces that only the system UID or root's UID or apps that have the
1531 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1532 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1533 * can make certain calls to the UserManager.
1534 *
1535 * @param message used as message if SecurityException is thrown
1536 * @throws SecurityException if the caller is not system or root
1537 * @see #hasManageOrCreateUsersPermission()
1538 */
1539 private static final void checkManageOrCreateUsersPermission(String message) {
1540 if (!hasManageOrCreateUsersPermission()) {
1541 throw new SecurityException(
1542 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1543 }
1544 }
1545
1546 /**
1547 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1548 * to create user/profiles other than what is allowed for
1549 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1550 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1551 */
1552 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1553 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1554 if (!hasManageOrCreateUsersPermission()) {
1555 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1556 + "permission to create an user with flags: " + creationFlags);
1557 }
1558 } else if (!hasManageUsersPermission()) {
1559 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1560 + " with flags: " + creationFlags);
1561 }
1562 }
1563
1564 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001565 * @return whether the calling UID is system UID or root's UID or the calling app has the
1566 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1567 */
1568 private static final boolean hasManageUsersPermission() {
1569 final int callingUid = Binder.getCallingUid();
1570 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1571 || callingUid == Process.ROOT_UID
1572 || ActivityManager.checkComponentPermission(
1573 android.Manifest.permission.MANAGE_USERS,
1574 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1575 }
1576
1577 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001578 * @return whether the calling UID is system UID or root's UID or the calling app has the
1579 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1580 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1581 */
1582 private static final boolean hasManageOrCreateUsersPermission() {
1583 final int callingUid = Binder.getCallingUid();
1584 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1585 || callingUid == Process.ROOT_UID
1586 || ActivityManager.checkComponentPermission(
1587 android.Manifest.permission.MANAGE_USERS,
1588 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1589 || ActivityManager.checkComponentPermission(
1590 android.Manifest.permission.CREATE_USERS,
1591 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1592 }
1593
1594 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001595 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1596 * UserManager.
1597 *
1598 * @param message used as message if SecurityException is thrown
1599 * @throws SecurityException if the caller is not system or root
1600 */
1601 private static void checkSystemOrRoot(String message) {
1602 final int uid = Binder.getCallingUid();
1603 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1604 throw new SecurityException("Only system may: " + message);
1605 }
1606 }
1607
Fyodor Kupolov82402752015-10-28 14:54:51 -07001608 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001609 try {
1610 File dir = new File(mUsersDir, Integer.toString(info.id));
1611 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001612 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001613 if (!dir.exists()) {
1614 dir.mkdir();
1615 FileUtils.setPermissions(
1616 dir.getPath(),
1617 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1618 -1, -1);
1619 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001620 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001621 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001622 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001623 info.iconPath = file.getAbsolutePath();
1624 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001625 try {
1626 os.close();
1627 } catch (IOException ioe) {
1628 // What the ... !
1629 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001630 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001631 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001632 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001633 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001634 }
1635
Amith Yamasani0b285492011-04-14 17:35:23 -07001636 /**
1637 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1638 * cache it elsewhere.
1639 * @return the array of user ids.
1640 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001641 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001642 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001643 return mUserIds;
1644 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001645 }
1646
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001647 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001648 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001649 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001650 return;
1651 }
1652 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001653 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001654 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001655 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001657 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001658 int type;
1659 while ((type = parser.next()) != XmlPullParser.START_TAG
1660 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001661 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662 }
1663
1664 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001665 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001666 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001667 return;
1668 }
1669
Amith Yamasani2a003292012-08-14 18:25:45 -07001670 mNextSerialNumber = -1;
1671 if (parser.getName().equals(TAG_USERS)) {
1672 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1673 if (lastSerialNumber != null) {
1674 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1675 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001676 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1677 if (versionNumber != null) {
1678 mUserVersion = Integer.parseInt(versionNumber);
1679 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001680 }
1681
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1683
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001684 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301685 if (type == XmlPullParser.START_TAG) {
1686 final String name = parser.getName();
1687 if (name.equals(TAG_USER)) {
1688 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001689
Amith Yamasani12747872015-12-07 14:19:49 -08001690 UserData userData = readUserLP(Integer.parseInt(id));
1691
1692 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001693 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001694 mUsers.put(userData.info.id, userData);
1695 if (mNextSerialNumber < 0
1696 || mNextSerialNumber <= userData.info.id) {
1697 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001698 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301699 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001700 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301701 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001702 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1703 && type != XmlPullParser.END_TAG) {
1704 if (type == XmlPullParser.START_TAG) {
1705 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001706 synchronized (mGuestRestrictions) {
1707 UserRestrictionsUtils
1708 .readRestrictions(parser, mGuestRestrictions);
1709 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001710 }
1711 break;
1712 }
1713 }
Makoto Onuki82de3002016-09-30 09:58:15 -07001714 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1715 UserRestrictionsUtils.readRestrictions(parser,
1716 newDevicePolicyGlobalUserRestrictions);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001717 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1718 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1719 if (ownerUserId != null) {
1720 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1721 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001722 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001723 }
1724 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001725 synchronized (mRestrictionsLock) {
1726 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1727 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001728 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001729 upgradeIfNecessaryLP();
1730 } catch (IOException | XmlPullParserException e) {
1731 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001732 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001733 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001734 }
1735 }
1736
Amith Yamasani6f34b412012-10-22 18:19:27 -07001737 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001738 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001739 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001740 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001741 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001742 int userVersion = mUserVersion;
1743 if (userVersion < 1) {
1744 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001745 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1746 if ("Primary".equals(userData.info.name)) {
1747 userData.info.name =
1748 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1749 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001750 }
1751 userVersion = 1;
1752 }
1753
Amith Yamasanibc9625052012-11-15 14:39:18 -08001754 if (userVersion < 2) {
1755 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001756 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1757 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1758 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1759 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001760 }
1761 userVersion = 2;
1762 }
1763
Amith Yamasani350962c2013-08-06 11:18:53 -07001764
Amith Yamasani5e486f52013-08-07 11:06:44 -07001765 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001766 userVersion = 4;
1767 }
1768
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001769 if (userVersion < 5) {
1770 initDefaultGuestRestrictions();
1771 userVersion = 5;
1772 }
1773
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001774 if (userVersion < 6) {
1775 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001776 synchronized (mUsersLock) {
1777 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001778 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001779 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001780 if (!splitSystemUser && userData.info.isRestricted()
1781 && (userData.info.restrictedProfileParentId
1782 == UserInfo.NO_PROFILE_GROUP_ID)) {
1783 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1784 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001785 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001786 }
1787 }
1788 userVersion = 6;
1789 }
1790
Amith Yamasani6f34b412012-10-22 18:19:27 -07001791 if (userVersion < USER_VERSION) {
1792 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1793 + USER_VERSION);
1794 } else {
1795 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001796
1797 if (originalVersion < mUserVersion) {
1798 writeUserListLP();
1799 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001800 }
1801 }
1802
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001803 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001804 int flags = UserInfo.FLAG_INITIALIZED;
1805 // In split system user mode, the admin and primary flags are assigned to the first human
1806 // user.
1807 if (!UserManager.isSplitSystemUser()) {
1808 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1809 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001810 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001811 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001812 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001813 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001814 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001815
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001816 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001817 try {
1818 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1819 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1820 for (String userRestriction : defaultFirstUserRestrictions) {
1821 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1822 restrictions.putBoolean(userRestriction, true);
1823 }
1824 }
1825 } catch (Resources.NotFoundException e) {
1826 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1827 }
1828
Makoto Onuki068c54a2015-10-13 14:34:03 -07001829 synchronized (mRestrictionsLock) {
1830 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1831 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001832
Fyodor Kupolov82402752015-10-28 14:54:51 -07001833 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001834 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001835
Amith Yamasani12747872015-12-07 14:19:49 -08001836 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001837 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001838 }
1839
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001840 private String getOwnerName() {
1841 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1842 }
1843
Amith Yamasani12747872015-12-07 14:19:49 -08001844 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001845 if (DBG) {
1846 debug("scheduleWriteUser");
1847 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001848 // No need to wrap it within a lock -- worst case, we'll just post the same message
1849 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001850 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1851 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001852 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1853 }
1854 }
1855
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001856 /*
1857 * Writes the user file in this format:
1858 *
1859 * <user flags="20039023" id="0">
1860 * <name>Primary</name>
1861 * </user>
1862 */
Amith Yamasani12747872015-12-07 14:19:49 -08001863 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001864 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001865 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001866 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001867 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001868 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001869 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001870 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001871 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1872
1873 // XmlSerializer serializer = XmlUtils.serializerInstance();
1874 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001875 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001876 serializer.startDocument(null, true);
1877 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1878
Amith Yamasani12747872015-12-07 14:19:49 -08001879 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001880 serializer.startTag(null, TAG_USER);
1881 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001882 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001883 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001884 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1885 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1886 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001887 if (userInfo.lastLoggedInFingerprint != null) {
1888 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1889 userInfo.lastLoggedInFingerprint);
1890 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001891 if (userInfo.iconPath != null) {
1892 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1893 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001894 if (userInfo.partial) {
1895 serializer.attribute(null, ATTR_PARTIAL, "true");
1896 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001897 if (userInfo.guestToRemove) {
1898 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1899 }
Kenny Guy2a764942014-04-02 13:29:20 +01001900 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1901 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1902 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001903 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001904 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1905 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1906 Integer.toString(userInfo.restrictedProfileParentId));
1907 }
Amith Yamasani12747872015-12-07 14:19:49 -08001908 // Write seed data
1909 if (userData.persistSeedData) {
1910 if (userData.seedAccountName != null) {
1911 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1912 }
1913 if (userData.seedAccountType != null) {
1914 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1915 }
1916 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001917 if (userInfo.name != null) {
1918 serializer.startTag(null, TAG_NAME);
1919 serializer.text(userInfo.name);
1920 serializer.endTag(null, TAG_NAME);
1921 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001922 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001923 UserRestrictionsUtils.writeRestrictions(serializer,
1924 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1925 UserRestrictionsUtils.writeRestrictions(serializer,
1926 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1927 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001928 }
Amith Yamasani12747872015-12-07 14:19:49 -08001929
1930 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001931 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001932 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001933 serializer.endTag(null, TAG_ACCOUNT);
1934 }
1935
Amith Yamasani12747872015-12-07 14:19:49 -08001936 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1937 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1938 userData.seedAccountOptions.saveToXml(serializer);
1939 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1940 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001941 serializer.endTag(null, TAG_USER);
1942
1943 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001944 userFile.finishWrite(fos);
1945 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001946 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001947 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001948 }
1949 }
1950
1951 /*
1952 * Writes the user list file in this format:
1953 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001954 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001955 * <user id="0"></user>
1956 * <user id="2"></user>
1957 * </users>
1958 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001959 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001960 if (DBG) {
1961 debug("writeUserList");
1962 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001963 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001964 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001965 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001966 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001967 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1968
1969 // XmlSerializer serializer = XmlUtils.serializerInstance();
1970 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001971 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001972 serializer.startDocument(null, true);
1973 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1974
1975 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001976 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001977 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001978
Adam Lesinskieddeb492014-09-08 17:50:03 -07001979 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001980 synchronized (mGuestRestrictions) {
1981 UserRestrictionsUtils
1982 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1983 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301984 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001985 synchronized (mRestrictionsLock) {
1986 UserRestrictionsUtils.writeRestrictions(serializer,
1987 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1988 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001989 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1990 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1991 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001992 int[] userIdsToWrite;
1993 synchronized (mUsersLock) {
1994 userIdsToWrite = new int[mUsers.size()];
1995 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001996 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001997 userIdsToWrite[i] = user.id;
1998 }
1999 }
2000 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002001 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002002 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002003 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002004 }
2005
2006 serializer.endTag(null, TAG_USERS);
2007
2008 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002009 userListFile.finishWrite(fos);
2010 } catch (Exception e) {
2011 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002012 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002013 }
2014 }
2015
Amith Yamasani12747872015-12-07 14:19:49 -08002016 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002017 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002018 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002019 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002020 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002021 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002022 long creationTime = 0L;
2023 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002024 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002025 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002026 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002027 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002028 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002029 boolean persistSeedData = false;
2030 String seedAccountName = null;
2031 String seedAccountType = null;
2032 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002033 Bundle baseRestrictions = new Bundle();
2034 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002035
2036 FileInputStream fis = null;
2037 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002038 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002039 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002040 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002041 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002042 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002043 int type;
2044 while ((type = parser.next()) != XmlPullParser.START_TAG
2045 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002046 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002047 }
2048
2049 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002050 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002051 return null;
2052 }
2053
2054 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002055 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2056 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002057 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002058 return null;
2059 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002060 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2061 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002062 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002063 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2064 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002065 lastLoggedInFingerprint = parser.getAttributeValue(null,
2066 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002067 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2068 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002069 restrictedProfileParentId = readIntAttribute(parser,
2070 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002071 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2072 if ("true".equals(valueString)) {
2073 partial = true;
2074 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002075 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2076 if ("true".equals(valueString)) {
2077 guestToRemove = true;
2078 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002079
Amith Yamasani12747872015-12-07 14:19:49 -08002080 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2081 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2082 if (seedAccountName != null || seedAccountType != null) {
2083 persistSeedData = true;
2084 }
2085
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002086 int outerDepth = parser.getDepth();
2087 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2088 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2089 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2090 continue;
2091 }
2092 String tag = parser.getName();
2093 if (TAG_NAME.equals(tag)) {
2094 type = parser.next();
2095 if (type == XmlPullParser.TEXT) {
2096 name = parser.getText();
2097 }
2098 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002099 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2100 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2101 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002102 } else if (TAG_ACCOUNT.equals(tag)) {
2103 type = parser.next();
2104 if (type == XmlPullParser.TEXT) {
2105 account = parser.getText();
2106 }
Amith Yamasani12747872015-12-07 14:19:49 -08002107 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2108 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2109 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002110 }
2111 }
2112 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002113
Amith Yamasani12747872015-12-07 14:19:49 -08002114 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002115 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002116 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002117 userInfo.creationTime = creationTime;
2118 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002119 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002120 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002121 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002122 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002123 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002124
2125 // Create the UserData object that's internal to this class
2126 UserData userData = new UserData();
2127 userData.info = userInfo;
2128 userData.account = account;
2129 userData.seedAccountName = seedAccountName;
2130 userData.seedAccountType = seedAccountType;
2131 userData.persistSeedData = persistSeedData;
2132 userData.seedAccountOptions = seedAccountOptions;
2133
Makoto Onuki068c54a2015-10-13 14:34:03 -07002134 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002135 mBaseUserRestrictions.put(id, baseRestrictions);
2136 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002137 }
Amith Yamasani12747872015-12-07 14:19:49 -08002138 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002139 } catch (IOException ioe) {
2140 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002141 } finally {
2142 if (fis != null) {
2143 try {
2144 fis.close();
2145 } catch (IOException e) {
2146 }
2147 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002148 }
2149 return null;
2150 }
2151
Amith Yamasani920ace02012-09-20 22:15:37 -07002152 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2153 String valueString = parser.getAttributeValue(null, attr);
2154 if (valueString == null) return defaultValue;
2155 try {
2156 return Integer.parseInt(valueString);
2157 } catch (NumberFormatException nfe) {
2158 return defaultValue;
2159 }
2160 }
2161
2162 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2163 String valueString = parser.getAttributeValue(null, attr);
2164 if (valueString == null) return defaultValue;
2165 try {
2166 return Long.parseLong(valueString);
2167 } catch (NumberFormatException nfe) {
2168 return defaultValue;
2169 }
2170 }
2171
Amith Yamasanib82add22013-07-09 11:24:44 -07002172 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002173 * Removes the app restrictions file for a specific package and user id, if it exists.
2174 */
2175 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2176 synchronized (mPackagesLock) {
2177 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002178 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002179 if (resFile.exists()) {
2180 resFile.delete();
2181 }
2182 }
2183 }
2184
Kenny Guya52dc3e2014-02-11 15:33:14 +00002185 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002186 public UserInfo createProfileForUser(String name, int flags, int userId,
2187 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002188 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002189 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002190 }
2191
Amith Yamasani258848d2012-08-10 17:06:33 -07002192 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002193 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2194 String[] disallowedPackages) {
2195 checkManageOrCreateUsersPermission(flags);
2196 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2197 }
2198
2199 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002200 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002201 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002202 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002203 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002204
Jessica Hummelbe81c802014-04-22 15:49:22 +01002205 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002206 return createUserInternal(name, flags, parentId, null);
2207 }
2208
2209 private UserInfo createUserInternal(String name, int flags, int parentId,
2210 String[] disallowedPackages) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002211 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002212 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2213 return null;
2214 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002215 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2216 }
2217
2218 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2219 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002220 DeviceStorageMonitorInternal dsm = LocalServices
2221 .getService(DeviceStorageMonitorInternal.class);
2222 if (dsm.isMemoryLow()) {
2223 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2224 return null;
2225 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002226 if (ActivityManager.isLowRamDeviceStatic()) {
2227 return null;
2228 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002229 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002230 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002231 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002232 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002233 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002234 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002235 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002236 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002237 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002238 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002239 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002240 if (parentId != UserHandle.USER_NULL) {
2241 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002242 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002243 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002244 if (parent == null) return null;
2245 }
2246 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2247 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2248 return null;
2249 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002250 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2251 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002252 // been reached, cannot add a user.
2253 return null;
2254 }
2255 // If we're adding a guest and there already exists one, bail.
2256 if (isGuest && findCurrentGuestUser() != null) {
2257 return null;
2258 }
2259 // In legacy mode, restricted profile's parent can only be the owner user
2260 if (isRestricted && !UserManager.isSplitSystemUser()
2261 && (parentId != UserHandle.USER_SYSTEM)) {
2262 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2263 return null;
2264 }
2265 if (isRestricted && UserManager.isSplitSystemUser()) {
2266 if (parent == null) {
2267 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2268 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002269 return null;
2270 }
Amith Yamasani12747872015-12-07 14:19:49 -08002271 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002272 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2273 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002274 return null;
2275 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002276 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002277 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2278 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002279 Log.e(LOG_TAG,
2280 "Ephemeral users are supported on split-system-user systems only.");
2281 return null;
2282 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002283 // In split system user mode, we assign the first human user the primary flag.
2284 // And if there is no device owner, we also assign the admin flag to primary user.
2285 if (UserManager.isSplitSystemUser()
2286 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2287 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002288 synchronized (mUsersLock) {
2289 if (!mIsDeviceManaged) {
2290 flags |= UserInfo.FLAG_ADMIN;
2291 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002292 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002293 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002294
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002295 userId = getNextAvailableId();
2296 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002297 boolean ephemeralGuests = Resources.getSystem()
2298 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002299
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002300 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002301 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2302 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2303 || (parent != null && parent.info.isEphemeral())) {
2304 flags |= UserInfo.FLAG_EPHEMERAL;
2305 }
2306
2307 userInfo = new UserInfo(userId, name, null, flags);
2308 userInfo.serialNumber = mNextSerialNumber++;
2309 long now = System.currentTimeMillis();
2310 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2311 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002312 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002313 userData = new UserData();
2314 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002315 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002316 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002317 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002318 writeUserListLP();
2319 if (parent != null) {
2320 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002321 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2322 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002323 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002324 }
Amith Yamasani12747872015-12-07 14:19:49 -08002325 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002326 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002327 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2328 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002329 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002330 }
Amith Yamasani12747872015-12-07 14:19:49 -08002331 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002332 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002333 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002334 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002335 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002336 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002337 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002338 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002339 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002340 userInfo.partial = false;
2341 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002342 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002343 }
2344 updateUserIds();
2345 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002346 if (isGuest) {
2347 synchronized (mGuestRestrictions) {
2348 restrictions.putAll(mGuestRestrictions);
2349 }
2350 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002351 synchronized (mRestrictionsLock) {
2352 mBaseUserRestrictions.append(userId, restrictions);
2353 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002354 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002355 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2356 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2357 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2358 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002359 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002360 } finally {
2361 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002362 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002363 return userInfo;
2364 }
2365
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002366 @VisibleForTesting
2367 UserData putUserInfo(UserInfo userInfo) {
2368 final UserData userData = new UserData();
2369 userData.info = userInfo;
2370 synchronized (mUsers) {
2371 mUsers.put(userInfo.id, userData);
2372 }
2373 return userData;
2374 }
2375
2376 @VisibleForTesting
2377 void removeUserInfo(int userId) {
2378 synchronized (mUsers) {
2379 mUsers.remove(userId);
2380 }
2381 }
2382
Amith Yamasani0b285492011-04-14 17:35:23 -07002383 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002384 * @hide
2385 */
Amith Yamasani12747872015-12-07 14:19:49 -08002386 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002387 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002388 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002389 final UserInfo user = createProfileForUser(
2390 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002391 if (user == null) {
2392 return null;
2393 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002394 long identity = Binder.clearCallingIdentity();
2395 try {
2396 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2397 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2398 // the putIntForUser() will fail.
2399 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2400 android.provider.Settings.Secure.LOCATION_MODE,
2401 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2402 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2403 } finally {
2404 Binder.restoreCallingIdentity(identity);
2405 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002406 return user;
2407 }
2408
2409 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002410 * Find the current guest user. If the Guest user is partial,
2411 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002412 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002413 private UserInfo findCurrentGuestUser() {
2414 synchronized (mUsersLock) {
2415 final int size = mUsers.size();
2416 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002417 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002418 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2419 return user;
2420 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002421 }
2422 }
2423 return null;
2424 }
2425
2426 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002427 * Mark this guest user for deletion to allow us to create another guest
2428 * and switch to that user before actually removing this guest.
2429 * @param userHandle the userid of the current guest
2430 * @return whether the user could be marked for deletion
2431 */
Amith Yamasani12747872015-12-07 14:19:49 -08002432 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002433 public boolean markGuestForDeletion(int userHandle) {
2434 checkManageUsersPermission("Only the system can remove users");
2435 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2436 UserManager.DISALLOW_REMOVE_USER, false)) {
2437 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2438 return false;
2439 }
2440
2441 long ident = Binder.clearCallingIdentity();
2442 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002443 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002444 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002445 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002446 userData = mUsers.get(userHandle);
2447 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 return false;
2449 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002450 }
Amith Yamasani12747872015-12-07 14:19:49 -08002451 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002452 return false;
2453 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002454 // We set this to a guest user that is to be removed. This is a temporary state
2455 // where we are allowed to add new Guest users, even if this one is still not
2456 // removed. This user will still show up in getUserInfo() calls.
2457 // If we don't get around to removing this Guest user, it will be purged on next
2458 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002459 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002460 // Mark it as disabled, so that it isn't returned any more when
2461 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002462 userData.info.flags |= UserInfo.FLAG_DISABLED;
2463 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002464 }
2465 } finally {
2466 Binder.restoreCallingIdentity(ident);
2467 }
2468 return true;
2469 }
2470
2471 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002472 * Removes a user and all data directories created for that user. This method should be called
2473 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002474 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002475 */
Amith Yamasani12747872015-12-07 14:19:49 -08002476 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002477 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002478 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002479 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2480 UserManager.DISALLOW_REMOVE_USER, false)) {
2481 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2482 return false;
2483 }
2484
Kenny Guyee58b4f2014-05-23 15:19:53 +01002485 long ident = Binder.clearCallingIdentity();
2486 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002487 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002488 int currentUser = ActivityManager.getCurrentUser();
2489 if (currentUser == userHandle) {
2490 Log.w(LOG_TAG, "Current user cannot be removed");
2491 return false;
2492 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002493 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002494 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002495 userData = mUsers.get(userHandle);
2496 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002497 return false;
2498 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002499
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002500 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002501 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002502
Kenny Guyee58b4f2014-05-23 15:19:53 +01002503 try {
2504 mAppOpsService.removeUser(userHandle);
2505 } catch (RemoteException e) {
2506 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2507 }
2508 // Set this to a partially created user, so that the user will be purged
2509 // on next startup, in case the runtime stops now before stopping and
2510 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002511 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002512 // Mark it as disabled, so that it isn't returned any more when
2513 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002514 userData.info.flags |= UserInfo.FLAG_DISABLED;
2515 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002516 }
2517
Amith Yamasani12747872015-12-07 14:19:49 -08002518 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2519 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002520 // Send broadcast to notify system that the user removed was a
2521 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002522 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002523 }
2524
2525 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2526 int res;
2527 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002528 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2529 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002530 @Override
2531 public void userStopped(int userId) {
2532 finishRemoveUser(userId);
2533 }
2534 @Override
2535 public void userStopAborted(int userId) {
2536 }
2537 });
2538 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002539 return false;
2540 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002541 return res == ActivityManager.USER_OP_SUCCESS;
2542 } finally {
2543 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002544 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002545 }
2546
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002547 @VisibleForTesting
2548 void addRemovingUserIdLocked(int userId) {
2549 // We remember deleted user IDs to prevent them from being
2550 // reused during the current boot; they can still be reused
2551 // after a reboot or recycling of userIds.
2552 mRemovingUserIds.put(userId, true);
2553 mRecentlyRemovedIds.add(userId);
2554 // Keep LRU queue of recently removed IDs for recycling
2555 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2556 mRecentlyRemovedIds.removeFirst();
2557 }
2558 }
2559
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002560 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002561 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002562 // Let other services shutdown any activity and clean up their state before completely
2563 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002564 long ident = Binder.clearCallingIdentity();
2565 try {
2566 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2567 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002568 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2569 android.Manifest.permission.MANAGE_USERS,
2570
2571 new BroadcastReceiver() {
2572 @Override
2573 public void onReceive(Context context, Intent intent) {
2574 if (DBG) {
2575 Slog.i(LOG_TAG,
2576 "USER_REMOVED broadcast sent, cleaning up user data "
2577 + userHandle);
2578 }
2579 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002580 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002581 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002582 // Clean up any ActivityManager state
2583 LocalServices.getService(ActivityManagerInternal.class)
2584 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002585 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002586 }
2587 }.start();
2588 }
2589 },
2590
2591 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002592 } finally {
2593 Binder.restoreCallingIdentity(ident);
2594 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002595 }
2596
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002597 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002598 try {
2599 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2600 } catch (IllegalStateException e) {
2601 // This may be simply because the user was partially created.
2602 Slog.i(LOG_TAG,
2603 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2604 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002605
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002606 // Cleanup gatekeeper secure user id
2607 try {
2608 final IGateKeeperService gk = GateKeeper.getService();
2609 if (gk != null) {
2610 gk.clearSecureUserId(userHandle);
2611 }
2612 } catch (Exception ex) {
2613 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2614 }
2615
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002616 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002617 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002618
2619 // Clean up all data before removing metadata
2620 mPm.destroyUserData(userHandle,
2621 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2622
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002623 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002624 synchronized (mUsersLock) {
2625 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002626 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002627 }
2628 synchronized (mUserStates) {
2629 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002630 }
2631 synchronized (mRestrictionsLock) {
2632 mBaseUserRestrictions.remove(userHandle);
2633 mAppliedUserRestrictions.remove(userHandle);
2634 mCachedEffectiveUserRestrictions.remove(userHandle);
2635 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002636 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002637 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002638 synchronized (mPackagesLock) {
2639 writeUserListLP();
2640 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002641 // Remove user file
2642 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2643 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002644 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002645 if (RELEASE_DELETED_USER_ID) {
2646 synchronized (mUsers) {
2647 mRemovingUserIds.delete(userHandle);
2648 }
2649 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002650 }
2651
Kenny Guyf8d3a232014-05-15 16:09:52 +01002652 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002653 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002654 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2655 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002656 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002657 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002658 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002659 }
2660
Amith Yamasani2a003292012-08-14 18:25:45 -07002661 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002662 public Bundle getApplicationRestrictions(String packageName) {
2663 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2664 }
2665
2666 @Override
2667 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002668 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002669 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002670 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002671 }
2672 synchronized (mPackagesLock) {
2673 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002674 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002675 }
2676 }
2677
2678 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002679 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002680 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002681 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002682 if (restrictions != null) {
2683 restrictions.setDefusable(true);
2684 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002685 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002686 if (restrictions == null || restrictions.isEmpty()) {
2687 cleanAppRestrictionsForPackage(packageName, userId);
2688 } else {
2689 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002690 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002691 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002692 }
Robin Lee66e5d962014-04-09 16:44:21 +01002693
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002694 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2695 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2696 changeIntent.setPackage(packageName);
2697 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2698 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002699 }
2700
2701 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002702 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002703 try {
2704 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002705 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002706 } catch (NameNotFoundException nnfe) {
2707 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002708 } finally {
2709 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002710 }
2711 }
2712
Fyodor Kupolov82402752015-10-28 14:54:51 -07002713 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002714 AtomicFile restrictionsFile =
2715 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2716 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002717 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002718 }
2719
2720 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002721 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002722 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002723 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002724 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002725 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002726 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002727
2728 FileInputStream fis = null;
2729 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002730 fis = restrictionsFile.openRead();
2731 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002732 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002733 XmlUtils.nextElement(parser);
2734 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002735 Slog.e(LOG_TAG, "Unable to read restrictions file "
2736 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002737 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002738 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002739 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2740 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002741 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002742 } catch (IOException|XmlPullParserException e) {
2743 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002744 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002745 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002746 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002747 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002748 }
2749
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002750 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2751 XmlPullParser parser) throws XmlPullParserException, IOException {
2752 int type = parser.getEventType();
2753 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2754 String key = parser.getAttributeValue(null, ATTR_KEY);
2755 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2756 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2757 if (multiple != null) {
2758 values.clear();
2759 int count = Integer.parseInt(multiple);
2760 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2761 if (type == XmlPullParser.START_TAG
2762 && parser.getName().equals(TAG_VALUE)) {
2763 values.add(parser.nextText().trim());
2764 count--;
2765 }
2766 }
2767 String [] valueStrings = new String[values.size()];
2768 values.toArray(valueStrings);
2769 restrictions.putStringArray(key, valueStrings);
2770 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2771 restrictions.putBundle(key, readBundleEntry(parser, values));
2772 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2773 final int outerDepth = parser.getDepth();
2774 ArrayList<Bundle> bundleList = new ArrayList<>();
2775 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2776 Bundle childBundle = readBundleEntry(parser, values);
2777 bundleList.add(childBundle);
2778 }
2779 restrictions.putParcelableArray(key,
2780 bundleList.toArray(new Bundle[bundleList.size()]));
2781 } else {
2782 String value = parser.nextText().trim();
2783 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2784 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2785 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2786 restrictions.putInt(key, Integer.parseInt(value));
2787 } else {
2788 restrictions.putString(key, value);
2789 }
2790 }
2791 }
2792 }
2793
2794 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2795 throws IOException, XmlPullParserException {
2796 Bundle childBundle = new Bundle();
2797 final int outerDepth = parser.getDepth();
2798 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2799 readEntry(childBundle, values, parser);
2800 }
2801 return childBundle;
2802 }
2803
Fyodor Kupolov82402752015-10-28 14:54:51 -07002804 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002805 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002806 AtomicFile restrictionsFile = new AtomicFile(
2807 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002808 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002809 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002810 }
2811
2812 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002813 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002814 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002815 try {
2816 fos = restrictionsFile.startWrite();
2817 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2818
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002819 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002820 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002821 serializer.startDocument(null, true);
2822 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2823
2824 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002825 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002826 serializer.endTag(null, TAG_RESTRICTIONS);
2827
2828 serializer.endDocument();
2829 restrictionsFile.finishWrite(fos);
2830 } catch (Exception e) {
2831 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002832 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2833 }
2834 }
2835
2836 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2837 throws IOException {
2838 for (String key : restrictions.keySet()) {
2839 Object value = restrictions.get(key);
2840 serializer.startTag(null, TAG_ENTRY);
2841 serializer.attribute(null, ATTR_KEY, key);
2842
2843 if (value instanceof Boolean) {
2844 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2845 serializer.text(value.toString());
2846 } else if (value instanceof Integer) {
2847 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2848 serializer.text(value.toString());
2849 } else if (value == null || value instanceof String) {
2850 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2851 serializer.text(value != null ? (String) value : "");
2852 } else if (value instanceof Bundle) {
2853 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2854 writeBundle((Bundle) value, serializer);
2855 } else if (value instanceof Parcelable[]) {
2856 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2857 Parcelable[] array = (Parcelable[]) value;
2858 for (Parcelable parcelable : array) {
2859 if (!(parcelable instanceof Bundle)) {
2860 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2861 }
2862 serializer.startTag(null, TAG_ENTRY);
2863 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2864 writeBundle((Bundle) parcelable, serializer);
2865 serializer.endTag(null, TAG_ENTRY);
2866 }
2867 } else {
2868 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2869 String[] values = (String[]) value;
2870 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2871 for (String choice : values) {
2872 serializer.startTag(null, TAG_VALUE);
2873 serializer.text(choice != null ? choice : "");
2874 serializer.endTag(null, TAG_VALUE);
2875 }
2876 }
2877 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002878 }
2879 }
2880
2881 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002882 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002883 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002884 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002885 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002886 }
2887 }
2888
2889 @Override
2890 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002892 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002893 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002894 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002895 }
2896 // Not found
2897 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002898 }
2899 }
2900
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002901 @Override
2902 public long getUserCreationTime(int userHandle) {
2903 int callingUserId = UserHandle.getCallingUserId();
2904 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002905 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002906 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002907 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002908 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002909 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002910 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002911 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002912 }
2913 }
2914 }
2915 if (userInfo == null) {
2916 throw new SecurityException("userHandle can only be the calling user or a managed "
2917 + "profile associated with this user");
2918 }
2919 return userInfo.creationTime;
2920 }
2921
Amith Yamasani0b285492011-04-14 17:35:23 -07002922 /**
2923 * Caches the list of user ids in an array, adjusting the array size when necessary.
2924 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002925 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002926 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002927 synchronized (mUsersLock) {
2928 final int userSize = mUsers.size();
2929 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002930 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002931 num++;
2932 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002933 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002934 final int[] newUsers = new int[num];
2935 int n = 0;
2936 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002937 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002938 newUsers[n++] = mUsers.keyAt(i);
2939 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002940 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002941 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002942 }
2943 }
2944
2945 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002946 * Called right before a user is started. This gives us a chance to prepare
2947 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002948 */
2949 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002950 UserInfo userInfo = getUserInfo(userId);
2951 if (userInfo == null) {
2952 return;
2953 }
2954 final int userSerial = userInfo.serialNumber;
2955 // Migrate only if build fingerprints mismatch
2956 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002957 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002958 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002959
2960 if (userId != UserHandle.USER_SYSTEM) {
2961 synchronized (mRestrictionsLock) {
2962 applyUserRestrictionsLR(userId);
2963 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002964 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002965
2966 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002967 }
2968
2969 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002970 * Called right before a user is unlocked. This gives us a chance to prepare
2971 * app storage.
2972 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002973 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002974 UserInfo userInfo = getUserInfo(userId);
2975 if (userInfo == null) {
2976 return;
2977 }
2978 final int userSerial = userInfo.serialNumber;
2979 // Migrate only if build fingerprints mismatch
2980 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002981 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002982 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002983 }
2984
2985 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002986 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002987 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002988 * @param userId the user that was just foregrounded
2989 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002990 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002991 UserData userData = getUserDataNoChecks(userId);
2992 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002993 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2994 return;
2995 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002996
2997 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002998 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002999 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003000 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003001 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3002 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003003 }
3004
Amith Yamasanieb437d42016-04-29 09:31:25 -07003005 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07003006 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07003007 String demoLauncher =
3008 mContext.getResources().getString(
3009 com.android.internal.R.string.config_demoModeLauncherComponent);
3010 if (!TextUtils.isEmpty(demoLauncher)) {
3011 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07003012 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00003013 try {
3014 final IPackageManager iPm = AppGlobals.getPackageManager();
3015 iPm.setComponentEnabledSetting(componentToEnable,
3016 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3017 /* userId= */ userId);
3018 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3019 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3020 /* userId= */ userId, null);
3021 } catch (RemoteException re) {
3022 // Internal, shouldn't happen
3023 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003024 }
3025 }
3026 }
3027
Amith Yamasani920ace02012-09-20 22:15:37 -07003028 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003029 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003030 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003031 @VisibleForTesting
3032 int getNextAvailableId() {
3033 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003034 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003035 nextId = scanNextAvailableIdLocked();
3036 if (nextId >= 0) {
3037 return nextId;
3038 }
3039 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3040 // except most recently removed
3041 if (mRemovingUserIds.size() > 0) {
3042 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3043 mRemovingUserIds.clear();
3044 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3045 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003046 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003047 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003048 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003049 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003050 if (nextId < 0) {
3051 throw new IllegalStateException("No user id available!");
3052 }
3053 return nextId;
3054 }
3055
3056 private int scanNextAvailableIdLocked() {
3057 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3058 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3059 return i;
3060 }
3061 }
3062 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003063 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003064
Amith Yamasanifc95e702013-09-26 13:20:17 -07003065 private String packageToRestrictionsFileName(String packageName) {
3066 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3067 }
3068
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003069 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003070 * Enforce that serial number stored in user directory inode matches the
3071 * given expected value. Gracefully sets the serial number if currently
3072 * undefined.
3073 *
3074 * @throws IOException when problem extracting serial number, or serial
3075 * number is mismatched.
3076 */
3077 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003078 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3079 // When we're emulating FBE, the directory may have been chmod
3080 // 000'ed, meaning we can't read the serial number to enforce it;
3081 // instead of destroying the user, just log a warning.
3082 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3083 return;
3084 }
3085
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003086 final int foundSerial = getSerialNumber(file);
3087 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3088
3089 if (foundSerial == -1) {
3090 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3091 try {
3092 setSerialNumber(file, serialNumber);
3093 } catch (IOException e) {
3094 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3095 }
3096
3097 } else if (foundSerial != serialNumber) {
3098 throw new IOException("Found serial number " + foundSerial
3099 + " doesn't match expected " + serialNumber);
3100 }
3101 }
3102
3103 /**
3104 * Set serial number stored in user directory inode.
3105 *
3106 * @throws IOException if serial number was already set
3107 */
3108 private static void setSerialNumber(File file, int serialNumber)
3109 throws IOException {
3110 try {
3111 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3112 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3113 } catch (ErrnoException e) {
3114 throw e.rethrowAsIOException();
3115 }
3116 }
3117
3118 /**
3119 * Return serial number stored in user directory inode.
3120 *
3121 * @return parsed serial number, or -1 if not set
3122 */
3123 private static int getSerialNumber(File file) throws IOException {
3124 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003125 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3126 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003127 try {
3128 return Integer.parseInt(serial);
3129 } catch (NumberFormatException e) {
3130 throw new IOException("Bad serial number: " + serial);
3131 }
3132 } catch (ErrnoException e) {
3133 if (e.errno == OsConstants.ENODATA) {
3134 return -1;
3135 } else {
3136 throw e.rethrowAsIOException();
3137 }
3138 }
3139 }
3140
Amith Yamasani920ace02012-09-20 22:15:37 -07003141 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003142 public void setSeedAccountData(int userId, String accountName, String accountType,
3143 PersistableBundle accountOptions, boolean persist) {
3144 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3145 synchronized (mPackagesLock) {
3146 final UserData userData;
3147 synchronized (mUsersLock) {
3148 userData = getUserDataLU(userId);
3149 if (userData == null) {
3150 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3151 return;
3152 }
3153 userData.seedAccountName = accountName;
3154 userData.seedAccountType = accountType;
3155 userData.seedAccountOptions = accountOptions;
3156 userData.persistSeedData = persist;
3157 }
3158 if (persist) {
3159 writeUserLP(userData);
3160 }
3161 }
3162 }
3163
3164 @Override
3165 public String getSeedAccountName() throws RemoteException {
3166 checkManageUsersPermission("Cannot get seed account information");
3167 synchronized (mUsersLock) {
3168 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3169 return userData.seedAccountName;
3170 }
3171 }
3172
3173 @Override
3174 public String getSeedAccountType() throws RemoteException {
3175 checkManageUsersPermission("Cannot get seed account information");
3176 synchronized (mUsersLock) {
3177 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3178 return userData.seedAccountType;
3179 }
3180 }
3181
3182 @Override
3183 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3184 checkManageUsersPermission("Cannot get seed account information");
3185 synchronized (mUsersLock) {
3186 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3187 return userData.seedAccountOptions;
3188 }
3189 }
3190
3191 @Override
3192 public void clearSeedAccountData() throws RemoteException {
3193 checkManageUsersPermission("Cannot clear seed account information");
3194 synchronized (mPackagesLock) {
3195 UserData userData;
3196 synchronized (mUsersLock) {
3197 userData = getUserDataLU(UserHandle.getCallingUserId());
3198 if (userData == null) return;
3199 userData.clearSeedAccountData();
3200 }
3201 writeUserLP(userData);
3202 }
3203 }
3204
3205 @Override
3206 public boolean someUserHasSeedAccount(String accountName, String accountType)
3207 throws RemoteException {
3208 checkManageUsersPermission("Cannot check seed account information");
3209 synchronized (mUsersLock) {
3210 final int userSize = mUsers.size();
3211 for (int i = 0; i < userSize; i++) {
3212 final UserData data = mUsers.valueAt(i);
3213 if (data.info.isInitialized()) continue;
3214 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3215 continue;
3216 }
3217 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3218 continue;
3219 }
3220 return true;
3221 }
3222 }
3223 return false;
3224 }
3225
3226 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003227 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003228 FileDescriptor err, String[] args, ShellCallback callback,
3229 ResultReceiver resultReceiver) {
3230 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003231 }
3232
3233 int onShellCommand(Shell shell, String cmd) {
3234 if (cmd == null) {
3235 return shell.handleDefaultCommands(cmd);
3236 }
3237
3238 final PrintWriter pw = shell.getOutPrintWriter();
3239 try {
3240 switch(cmd) {
3241 case "list":
3242 return runList(pw);
3243 }
3244 } catch (RemoteException e) {
3245 pw.println("Remote exception: " + e);
3246 }
3247 return -1;
3248 }
3249
3250 private int runList(PrintWriter pw) throws RemoteException {
3251 final IActivityManager am = ActivityManagerNative.getDefault();
3252 final List<UserInfo> users = getUsers(false);
3253 if (users == null) {
3254 pw.println("Error: couldn't get users");
3255 return 1;
3256 } else {
3257 pw.println("Users:");
3258 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003259 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003260 pw.println("\t" + users.get(i).toString() + running);
3261 }
3262 return 0;
3263 }
3264 }
3265
3266 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003267 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3268 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3269 != PackageManager.PERMISSION_GRANTED) {
3270 pw.println("Permission Denial: can't dump UserManager from from pid="
3271 + Binder.getCallingPid()
3272 + ", uid=" + Binder.getCallingUid()
3273 + " without permission "
3274 + android.Manifest.permission.DUMP);
3275 return;
3276 }
3277
3278 long now = System.currentTimeMillis();
3279 StringBuilder sb = new StringBuilder();
3280 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003281 synchronized (mUsersLock) {
3282 pw.println("Users:");
3283 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003284 UserData userData = mUsers.valueAt(i);
3285 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003286 continue;
3287 }
Amith Yamasani12747872015-12-07 14:19:49 -08003288 UserInfo userInfo = userData.info;
3289 final int userId = userInfo.id;
3290 pw.print(" "); pw.print(userInfo);
3291 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003292 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003293 pw.print(" <removing> ");
3294 }
Amith Yamasani12747872015-12-07 14:19:49 -08003295 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003296 pw.print(" <partial>");
3297 }
3298 pw.println();
3299 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003300 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003301 pw.println("<unknown>");
3302 } else {
3303 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003304 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003305 sb.append(" ago");
3306 pw.println(sb);
3307 }
3308 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003309 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003310 pw.println("<unknown>");
3311 } else {
3312 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003313 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003314 sb.append(" ago");
3315 pw.println(sb);
3316 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003317 pw.print(" Last logged in fingerprint: ");
3318 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003319 pw.print(" Has profile owner: ");
3320 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003321 pw.println(" Restrictions:");
3322 synchronized (mRestrictionsLock) {
3323 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003324 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003325 pw.println(" Device policy local restrictions:");
3326 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003327 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003328 pw.println(" Effective restrictions:");
3329 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003330 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003331 }
Amith Yamasani12747872015-12-07 14:19:49 -08003332
3333 if (userData.account != null) {
3334 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003335 pw.println();
3336 }
Amith Yamasani12747872015-12-07 14:19:49 -08003337
3338 if (userData.seedAccountName != null) {
3339 pw.print(" Seed account name: " + userData.seedAccountName);
3340 pw.println();
3341 if (userData.seedAccountType != null) {
3342 pw.print(" account type: " + userData.seedAccountType);
3343 pw.println();
3344 }
3345 if (userData.seedAccountOptions != null) {
3346 pw.print(" account options exist");
3347 pw.println();
3348 }
3349 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003350 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003351 }
Amith Yamasani12747872015-12-07 14:19:49 -08003352 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003353 pw.println(" Device policy global restrictions:");
3354 synchronized (mRestrictionsLock) {
3355 UserRestrictionsUtils
3356 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3357 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003358 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003359 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3360 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003361 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003362 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003363 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003364 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003365 synchronized (mUsersLock) {
3366 pw.println();
3367 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003368 if (mRemovingUserIds.size() > 0) {
3369 pw.println();
3370 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3371 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003372 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003373 synchronized (mUserStates) {
3374 pw.println(" Started users state: " + mUserStates);
3375 }
Amith Yamasani12747872015-12-07 14:19:49 -08003376 // Dump some capabilities
3377 pw.println();
3378 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3379 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003380 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3381 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003382 }
3383 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003384
3385 final class MainHandler extends Handler {
3386
3387 @Override
3388 public void handleMessage(Message msg) {
3389 switch (msg.what) {
3390 case WRITE_USER_MSG:
3391 removeMessages(WRITE_USER_MSG, msg.obj);
3392 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003393 int userId = ((UserData) msg.obj).info.id;
3394 UserData userData = getUserDataNoChecks(userId);
3395 if (userData != null) {
3396 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003397 }
3398 }
3399 }
3400 }
3401 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003402
3403 /**
3404 * @param userId
3405 * @return whether the user has been initialized yet
3406 */
3407 boolean isInitialized(int userId) {
3408 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3409 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003410
3411 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003412 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003413 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3414 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003415 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003416 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003417 }
3418
3419 @Override
3420 public Bundle getBaseUserRestrictions(int userId) {
3421 synchronized (mRestrictionsLock) {
3422 return mBaseUserRestrictions.get(userId);
3423 }
3424 }
3425
3426 @Override
3427 public void setBaseUserRestrictionsByDpmsForMigration(
3428 int userId, Bundle baseRestrictions) {
3429 synchronized (mRestrictionsLock) {
3430 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003431 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003432 }
3433
Amith Yamasani12747872015-12-07 14:19:49 -08003434 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003435 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003436 if (userData != null) {
3437 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003438 } else {
3439 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3440 }
3441 }
3442 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003443
3444 @Override
3445 public boolean getUserRestriction(int userId, String key) {
3446 return getUserRestrictions(userId).getBoolean(key);
3447 }
3448
3449 @Override
3450 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3451 synchronized (mUserRestrictionsListeners) {
3452 mUserRestrictionsListeners.add(listener);
3453 }
3454 }
3455
3456 @Override
3457 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3458 synchronized (mUserRestrictionsListeners) {
3459 mUserRestrictionsListeners.remove(listener);
3460 }
3461 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003462
3463 @Override
3464 public void setDeviceManaged(boolean isManaged) {
3465 synchronized (mUsersLock) {
3466 mIsDeviceManaged = isManaged;
3467 }
3468 }
3469
3470 @Override
3471 public void setUserManaged(int userId, boolean isManaged) {
3472 synchronized (mUsersLock) {
3473 mIsUserManaged.put(userId, isManaged);
3474 }
3475 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003476
3477 @Override
3478 public void setUserIcon(int userId, Bitmap bitmap) {
3479 long ident = Binder.clearCallingIdentity();
3480 try {
3481 synchronized (mPackagesLock) {
3482 UserData userData = getUserDataNoChecks(userId);
3483 if (userData == null || userData.info.partial) {
3484 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3485 return;
3486 }
3487 writeBitmapLP(userData.info, bitmap);
3488 writeUserLP(userData);
3489 }
3490 sendUserInfoChangedBroadcast(userId);
3491 } finally {
3492 Binder.restoreCallingIdentity(ident);
3493 }
3494 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003495
3496 @Override
3497 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3498 synchronized (mUsersLock) {
3499 mForceEphemeralUsers = forceEphemeralUsers;
3500 }
3501 }
3502
3503 @Override
3504 public void removeAllUsers() {
3505 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3506 // Remove the non-system users straight away.
3507 removeNonSystemUsers();
3508 } else {
3509 // Switch to the system user first and then remove the other users.
3510 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3511 @Override
3512 public void onReceive(Context context, Intent intent) {
3513 int userId =
3514 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3515 if (userId != UserHandle.USER_SYSTEM) {
3516 return;
3517 }
3518 mContext.unregisterReceiver(this);
3519 removeNonSystemUsers();
3520 }
3521 };
3522 IntentFilter userSwitchedFilter = new IntentFilter();
3523 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3524 mContext.registerReceiver(
3525 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3526
3527 // Switch to the system user.
3528 ActivityManager am =
3529 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3530 am.switchUser(UserHandle.USER_SYSTEM);
3531 }
3532 }
phweisse9c44062016-02-10 12:57:38 +01003533
3534 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003535 public void onEphemeralUserStop(int userId) {
3536 synchronized (mUsersLock) {
3537 UserInfo userInfo = getUserInfoLU(userId);
3538 if (userInfo != null && userInfo.isEphemeral()) {
3539 // Do not allow switching back to the ephemeral user again as the user is going
3540 // to be deleted.
3541 userInfo.flags |= UserInfo.FLAG_DISABLED;
3542 if (userInfo.isGuest()) {
3543 // Indicate that the guest will be deleted after it stops.
3544 userInfo.guestToRemove = true;
3545 }
3546 }
3547 }
3548 }
3549
3550 @Override
phweisse9c44062016-02-10 12:57:38 +01003551 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003552 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003553 // Keep this in sync with UserManager.createUser
3554 if (user != null && !user.isAdmin()) {
3555 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3556 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3557 }
3558 return user;
3559 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003560
3561 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003562 public boolean isUserRunning(int userId) {
3563 synchronized (mUserStates) {
3564 return mUserStates.get(userId, -1) >= 0;
3565 }
3566 }
3567
3568 @Override
3569 public void setUserState(int userId, int userState) {
3570 synchronized (mUserStates) {
3571 mUserStates.put(userId, userState);
3572 }
3573 }
3574
3575 @Override
3576 public void removeUserState(int userId) {
3577 synchronized (mUserStates) {
3578 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003579 }
3580 }
3581
3582 @Override
3583 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003584 synchronized (mUserStates) {
3585 int state = mUserStates.get(userId, -1);
3586 return (state == UserState.STATE_RUNNING_UNLOCKING)
3587 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003588 }
3589 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003590 }
3591
3592 /* Remove all the users except of the system one. */
3593 private void removeNonSystemUsers() {
3594 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3595 synchronized (mUsersLock) {
3596 final int userSize = mUsers.size();
3597 for (int i = 0; i < userSize; i++) {
3598 UserInfo ui = mUsers.valueAt(i).info;
3599 if (ui.id != UserHandle.USER_SYSTEM) {
3600 usersToRemove.add(ui);
3601 }
3602 }
3603 }
3604 for (UserInfo ui: usersToRemove) {
3605 removeUser(ui.id);
3606 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003607 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003608
3609 private class Shell extends ShellCommand {
3610 @Override
3611 public int onCommand(String cmd) {
3612 return onShellCommand(this, cmd);
3613 }
3614
3615 @Override
3616 public void onHelp() {
3617 final PrintWriter pw = getOutPrintWriter();
3618 pw.println("User manager (user) commands:");
3619 pw.println(" help");
3620 pw.println(" Print this help text.");
3621 pw.println("");
3622 pw.println(" list");
3623 pw.println(" Prints all users on the system.");
3624 }
3625 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003626
3627 private static void debug(String message) {
3628 Log.d(LOG_TAG, message +
3629 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3630 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003631}