blob: c1cb032ce97f39ece4f5b3dd021156771274de74 [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;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070067import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080069import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010070import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070071import android.security.GateKeeper;
72import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070073import android.system.ErrnoException;
74import android.system.Os;
75import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070076import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070077import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070078import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070079import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import android.util.Slog;
81import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080082import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000083import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070084import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import android.util.Xml;
86
Makoto Onuki068c54a2015-10-13 14:34:03 -070087import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070088import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040089import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080090import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080091import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070092import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070093import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000094import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070095import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070096import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000097import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070098import com.android.server.storage.DeviceStorageMonitorInternal;
Jeff Sharkey47f71082016-02-01 17:03:54 -070099import libcore.io.IoUtils;
100import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800101
102import org.xmlpull.v1.XmlPullParser;
103import org.xmlpull.v1.XmlPullParserException;
104import org.xmlpull.v1.XmlSerializer;
105
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106import java.io.BufferedOutputStream;
107import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700108import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700110import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileOutputStream;
112import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700113import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100114import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115import java.util.ArrayList;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700116import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.util.List;
118
Makoto Onuki068c54a2015-10-13 14:34:03 -0700119/**
120 * Service for {@link UserManager}.
121 *
122 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700123 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800124 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700125 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
126 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
127 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700128 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700129public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700130
Amith Yamasani2a003292012-08-14 18:25:45 -0700131 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800132 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800133 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700134 // Can be used for manual testing of id recycling
135 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700136
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800138 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700140 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700142 private static final String ATTR_CREATION_TIME = "created";
143 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600144 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700145 private static final String ATTR_SERIAL_NO = "serialNumber";
146 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700147 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700148 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700149 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100150 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700151 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800152 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
153 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530154 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700155 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800157 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800158 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100159 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160 private static final String TAG_ENTRY = "entry";
161 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800162 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800163 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700164 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800165 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700167 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
168 private static final String ATTR_TYPE_STRING = "s";
169 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700170 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700171 private static final String ATTR_TYPE_BUNDLE = "B";
172 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700173
Amith Yamasani0b285492011-04-14 17:35:23 -0700174 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700176 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100177 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700178
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800179 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700180 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800181
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700182 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
183 UserInfo.FLAG_MANAGED_PROFILE
184 | UserInfo.FLAG_EPHEMERAL
185 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700186 | UserInfo.FLAG_GUEST
187 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700188
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700189 @VisibleForTesting
190 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700191 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700192 @VisibleForTesting
193 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
194
195 // Max size of the queue of recently removed users
196 @VisibleForTesting
197 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700198
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700199 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700200
Amith Yamasani920ace02012-09-20 22:15:37 -0700201 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
202
Nicolas Prevotb8186812015-08-06 15:00:03 +0100203 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700204 // without first making sure that the rest of the framework is prepared for it.
205 private static final int MAX_MANAGED_PROFILES = 1;
206
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800207 static final int WRITE_USER_MSG = 1;
208 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530209
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700210 private static final String XATTR_SERIAL = "user.serial";
211
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800212 // Tron counters
213 private static final String TRON_GUEST_CREATED = "users_guest_created";
214 private static final String TRON_USER_CREATED = "users_user_created";
215
Dianne Hackborn4428e172012-08-24 17:43:05 -0700216 private final Context mContext;
217 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700218 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700219 // Short-term lock for internal state, when interaction/sync with PM is not required
220 private final Object mUsersLock = new Object();
221 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700222
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800223 private final Handler mHandler;
224
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700225 private final File mUsersDir;
226 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700227
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800228 private static final IBinder mUserRestriconToken = new Binder();
229
Makoto Onuki068c54a2015-10-13 14:34:03 -0700230 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800231 * User-related information that is used for persisting to flash. Only UserInfo is
232 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800233 */
Amith Yamasani12747872015-12-07 14:19:49 -0800234 private static class UserData {
235 // Basic user information and properties
236 UserInfo info;
237 // Account name used when there is a strong association between a user and an account
238 String account;
239 // Account information for seeding into a newly created user. This could also be
240 // used for login validation for an existing user, for updating their credentials.
241 // In the latter case, data may not need to be persisted as it is only valid for the
242 // current login session.
243 String seedAccountName;
244 String seedAccountType;
245 PersistableBundle seedAccountOptions;
246 // Whether to perist the seed account information to be available after a boot
247 boolean persistSeedData;
248
249 void clearSeedAccountData() {
250 seedAccountName = null;
251 seedAccountType = null;
252 seedAccountOptions = null;
253 persistSeedData = false;
254 }
255 }
256
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800257 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800258 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800259
260 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700261 * User restrictions set via UserManager. This doesn't include restrictions set by
262 * device owner / profile owners.
263 *
264 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
265 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
266 * maybe shared between {@link #mBaseUserRestrictions} and
267 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
268 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700269 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700270 */
271 @GuardedBy("mRestrictionsLock")
272 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
273
274 /**
275 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
276 * with device / profile owner restrictions. We'll initialize it lazily; use
277 * {@link #getEffectiveUserRestrictions} to access it.
278 *
279 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
280 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
281 * maybe shared between {@link #mBaseUserRestrictions} and
282 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
283 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700284 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700285 */
286 @GuardedBy("mRestrictionsLock")
287 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
288
Makoto Onuki4f160732015-10-27 17:15:38 -0700289 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800290 * User restrictions that have already been applied in
291 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
292 * that have changed since the last
293 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700294 */
295 @GuardedBy("mRestrictionsLock")
296 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
297
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800298 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800299 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
300 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800301 */
302 @GuardedBy("mRestrictionsLock")
303 private Bundle mDevicePolicyGlobalUserRestrictions;
304
305 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100306 * Id of the user that set global restrictions.
307 */
308 @GuardedBy("mRestrictionsLock")
309 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
310
311 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800312 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
313 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800314 */
315 @GuardedBy("mRestrictionsLock")
316 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
317
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800318 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530319 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800320
321 /**
322 * Set of user IDs being actively removed. Removed IDs linger in this set
323 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700324 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800325 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700326 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800327 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700328
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700329 /**
330 * Queue of recently removed userIds. Used for recycling of userIds
331 */
332 @GuardedBy("mUsersLock")
333 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
334
Fyodor Kupolov82402752015-10-28 14:54:51 -0700335 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700336 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800337 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700338 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700339 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700340
Jason Monk62062992014-05-06 09:55:28 -0400341 private IAppOpsService mAppOpsService;
342
Makoto Onuki068c54a2015-10-13 14:34:03 -0700343 private final LocalService mLocalService;
344
Makoto Onukie7927da2015-11-25 10:05:17 -0800345 @GuardedBy("mUsersLock")
346 private boolean mIsDeviceManaged;
347
348 @GuardedBy("mUsersLock")
349 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
350
Makoto Onukid45a4a22015-11-02 17:17:38 -0800351 @GuardedBy("mUserRestrictionsListeners")
352 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
353 new ArrayList<>();
354
Clara Bayarria1771112015-12-18 16:29:18 +0000355 private final LockPatternUtils mLockPatternUtils;
356
Ricky Waib1dd80b2016-06-07 18:00:55 +0100357 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
358 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
359
360 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
361 @Override
362 public void onReceive(Context context, Intent intent) {
363 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
364 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
365 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
366 setQuietModeEnabled(userHandle, false);
367 if (target != null) {
368 try {
369 mContext.startIntentSender(target, null, 0, 0, 0);
370 } catch (IntentSender.SendIntentException e) {
371 /* ignore */
372 }
373 }
374 }
375 }
376 };
377
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100378 /**
379 * Whether all users should be created ephemeral.
380 */
381 @GuardedBy("mUsersLock")
382 private boolean mForceEphemeralUsers;
383
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000384 @GuardedBy("mUserStates")
385 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700386
Amith Yamasani258848d2012-08-10 17:06:33 -0700387 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700388
Dianne Hackborn4428e172012-08-24 17:43:05 -0700389 public static UserManagerService getInstance() {
390 synchronized (UserManagerService.class) {
391 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700392 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700393 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700394
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700395 public static class LifeCycle extends SystemService {
396
397 private UserManagerService mUms;
398
399 /**
400 * @param context
401 */
402 public LifeCycle(Context context) {
403 super(context);
404 }
405
406 @Override
407 public void onStart() {
408 mUms = UserManagerService.getInstance();
409 publishBinderService(Context.USER_SERVICE, mUms);
410 }
411
412 @Override
413 public void onBootPhase(int phase) {
414 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
415 mUms.cleanupPartialUsers();
416 }
417 }
418 }
419
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700420 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800421 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700422 UserManagerService(Context context) {
423 this(context, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700424 }
425
Dianne Hackborn4428e172012-08-24 17:43:05 -0700426 /**
427 * Called by package manager to create the service. This is closely
428 * associated with the package manager, and the given lock is the
429 * package manager's own lock.
430 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800431 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
432 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700433 }
434
Dianne Hackborn4428e172012-08-24 17:43:05 -0700435 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800436 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700437 mContext = context;
438 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800440 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800441 synchronized (mPackagesLock) {
442 mUsersDir = new File(dataDir, USER_INFO_DIR);
443 mUsersDir.mkdirs();
444 // Make zeroth user directory, for services to migrate their files to that location
445 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
446 userZeroDir.mkdirs();
447 FileUtils.setPermissions(mUsersDir.toString(),
448 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
449 -1, -1);
450 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
451 initDefaultGuestRestrictions();
452 readUserListLP();
453 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700454 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700455 mLocalService = new LocalService();
456 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000457 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000458 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700459 }
460
461 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400462 mAppOpsService = IAppOpsService.Stub.asInterface(
463 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800464
465 synchronized (mRestrictionsLock) {
466 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400467 }
Samuel Tand9453b82016-03-14 15:57:02 -0700468
469 UserInfo currentGuestUser = findCurrentGuestUser();
470 if (currentGuestUser != null && !hasUserRestriction(
471 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
472 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
473 // to it, in case this guest was created in a previous version where this
474 // user restriction was not a default guest restriction.
475 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
476 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700477
Ricky Waib1dd80b2016-06-07 18:00:55 +0100478 mContext.registerReceiver(mDisableQuietModeCallback,
479 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
480 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700481 }
482
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700483 void cleanupPartialUsers() {
484 // Prune out any partially created, partially removed and ephemeral users.
485 ArrayList<UserInfo> partials = new ArrayList<>();
486 synchronized (mUsersLock) {
487 final int userSize = mUsers.size();
488 for (int i = 0; i < userSize; i++) {
489 UserInfo ui = mUsers.valueAt(i).info;
490 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
491 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700492 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700493 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700494 }
495 }
496 }
497 final int partialsSize = partials.size();
498 for (int i = 0; i < partialsSize; i++) {
499 UserInfo ui = partials.get(i);
500 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
501 + " (name=" + ui.name + ")");
502 removeUserState(ui.id);
503 }
504 }
505
Amith Yamasani258848d2012-08-10 17:06:33 -0700506 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800507 public String getUserAccount(int userId) {
508 checkManageUserAndAcrossUsersFullPermission("get user account");
509 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800510 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800511 }
512 }
513
514 @Override
515 public void setUserAccount(int userId, String accountName) {
516 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800517 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800518 synchronized (mPackagesLock) {
519 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800520 final UserData userData = mUsers.get(userId);
521 if (userData == null) {
522 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
523 return;
524 }
525 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800526 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800527 userData.account = accountName;
528 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800529 }
530 }
531
532 if (userToUpdate != null) {
533 writeUserLP(userToUpdate);
534 }
535 }
536 }
537
538 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700539 public UserInfo getPrimaryUser() {
540 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700541 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700542 final int userSize = mUsers.size();
543 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800544 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800545 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700546 return ui;
547 }
548 }
549 }
550 return null;
551 }
552
553 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700554 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700555 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700557 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700558 final int userSize = mUsers.size();
559 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800560 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700561 if (ui.partial) {
562 continue;
563 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800564 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700565 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700566 }
Amith Yamasani13593602012-03-22 16:16:17 -0700567 }
568 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700569 }
Amith Yamasani13593602012-03-22 16:16:17 -0700570 }
571
Amith Yamasani258848d2012-08-10 17:06:33 -0700572 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100573 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700574 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800575 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700576 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700577 } else {
578 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800579 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700580 final long ident = Binder.clearCallingIdentity();
581 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700582 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700583 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100584 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700585 } finally {
586 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000587 }
588 }
589
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700590 @Override
591 public int[] getProfileIds(int userId, boolean enabledOnly) {
592 if (userId != UserHandle.getCallingUserId()) {
593 checkManageUsersPermission("getting profiles related to user " + userId);
594 }
595 final long ident = Binder.clearCallingIdentity();
596 try {
597 synchronized (mUsersLock) {
598 return getProfileIdsLU(userId, enabledOnly).toArray();
599 }
600 } finally {
601 Binder.restoreCallingIdentity(ident);
602 }
603 }
604
Amith Yamasanibe465322014-04-24 13:45:17 -0700605 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700606 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700607 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
608 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
609 for (int i = 0; i < profileIds.size(); i++) {
610 int profileId = profileIds.get(i);
611 UserInfo userInfo = mUsers.get(profileId).info;
612 // If full info is not required - clear PII data to prevent 3P apps from reading it
613 if (!fullInfo) {
614 userInfo = new UserInfo(userInfo);
615 userInfo.name = null;
616 userInfo.iconPath = null;
617 } else {
618 userInfo = userWithName(userInfo);
619 }
620 users.add(userInfo);
621 }
622 return users;
623 }
624
625 /**
626 * Assume permissions already checked and caller's identity cleared
627 */
628 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700629 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700630 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700631 if (user == null) {
632 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700633 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700634 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700635 final int userSize = mUsers.size();
636 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800637 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700638 if (!isProfileOf(user, profile)) {
639 continue;
640 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100641 if (enabledOnly && !profile.isEnabled()) {
642 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700643 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700644 if (mRemovingUserIds.get(profile.id)) {
645 continue;
646 }
Tony Mak80189cd2016-04-05 17:21:42 +0100647 if (profile.partial) {
648 continue;
649 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700650 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700651 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700652 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700653 }
654
Jessica Hummelbe81c802014-04-22 15:49:22 +0100655 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700656 public int getCredentialOwnerProfile(int userHandle) {
657 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000658 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700659 synchronized (mUsersLock) {
660 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700661 if (profileParent != null) {
662 return profileParent.id;
663 }
664 }
665 }
666
667 return userHandle;
668 }
669
670 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700671 public boolean isSameProfileGroup(int userId, int otherUserId) {
672 if (userId == otherUserId) return true;
673 checkManageUsersPermission("check if in the same profile group");
674 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700675 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700676 }
677 }
678
Fyodor Kupolov82402752015-10-28 14:54:51 -0700679 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
680 synchronized (mUsersLock) {
681 UserInfo userInfo = getUserInfoLU(userId);
682 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
683 return false;
684 }
685 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
686 if (otherUserInfo == null
687 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
688 return false;
689 }
690 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700691 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700692 }
693
694 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100695 public UserInfo getProfileParent(int userHandle) {
696 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700697 synchronized (mUsersLock) {
698 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700699 }
700 }
701
Fyodor Kupolov82402752015-10-28 14:54:51 -0700702 private UserInfo getProfileParentLU(int userHandle) {
703 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700704 if (profile == null) {
705 return null;
706 }
707 int parentUserId = profile.profileGroupId;
708 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
709 return null;
710 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700711 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100712 }
713 }
714
Fyodor Kupolov82402752015-10-28 14:54:51 -0700715 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100716 return user.id == profile.id ||
717 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
718 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000719 }
720
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000721 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000722 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100723 Intent intent = new Intent();
724 if (inQuietMode) {
725 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
726 } else {
727 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
728 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000729 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
730 intent.putExtra(Intent.EXTRA_USER, profileHandle);
731 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000732 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000733 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000734 }
735
736 @Override
737 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
738 checkManageUsersPermission("silence profile");
739 boolean changed = false;
740 UserInfo profile, parent;
741 synchronized (mPackagesLock) {
742 synchronized (mUsersLock) {
743 profile = getUserInfoLU(userHandle);
744 parent = getProfileParentLU(userHandle);
745
746 }
747 if (profile == null || !profile.isManagedProfile()) {
748 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
749 }
750 if (profile.isQuietModeEnabled() != enableQuietMode) {
751 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800752 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000753 changed = true;
754 }
755 }
756 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000757 long identity = Binder.clearCallingIdentity();
758 try {
759 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100760 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100761 LocalServices.getService(ActivityManagerInternal.class)
762 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000763 } else {
764 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
765 }
766 } catch (RemoteException e) {
767 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
768 } finally {
769 Binder.restoreCallingIdentity(identity);
770 }
771
772 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
773 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000774 }
775 }
776
777 @Override
778 public boolean isQuietModeEnabled(int userHandle) {
779 synchronized (mPackagesLock) {
780 UserInfo info;
781 synchronized (mUsersLock) {
782 info = getUserInfoLU(userHandle);
783 }
784 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000785 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000786 }
787 return info.isQuietModeEnabled();
788 }
789 }
790
Kenny Guya52dc3e2014-02-11 15:33:14 +0000791 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100792 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100793 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600794 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100795 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100796 // if the user is already unlocked, no need to show a profile challenge
797 setQuietModeEnabled(userHandle, false);
798 return true;
799 }
800
801 long identity = Binder.clearCallingIdentity();
802 try {
803 // otherwise, we show a profile challenge to trigger decryption of the user
804 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
805 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100806 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
807 // lock, confirm screenlock page will know and show personal challenge, and unlock
808 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100809 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
810 userHandle);
811 if (unlockIntent == null) {
812 return false;
813 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100814 final Intent callBackIntent = new Intent(
815 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100816 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100817 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100818 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100819 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
820 callBackIntent.setPackage(mContext.getPackageName());
821 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
822 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
823 mContext,
824 0,
825 callBackIntent,
826 PendingIntent.FLAG_CANCEL_CURRENT |
827 PendingIntent.FLAG_ONE_SHOT |
828 PendingIntent.FLAG_IMMUTABLE);
829 // After unlocking the challenge, it will disable quiet mode and run the original
830 // intentSender
831 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100832 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
833 mContext.startActivity(unlockIntent);
834 } finally {
835 Binder.restoreCallingIdentity(identity);
836 }
837 return false;
838 }
839
840 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100841 public void setUserEnabled(int userId) {
842 checkManageUsersPermission("enable user");
843 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700844 UserInfo info;
845 synchronized (mUsersLock) {
846 info = getUserInfoLU(userId);
847 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100848 if (info != null && !info.isEnabled()) {
849 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800850 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100851 }
852 }
853 }
854
855 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700856 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700857 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000858 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700859 return userWithName(getUserInfoLU(userId));
860 }
861 }
862
863 /**
864 * Returns a UserInfo object with the name filled in, for Owner, or the original
865 * if the name is already set.
866 */
867 private UserInfo userWithName(UserInfo orig) {
868 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
869 UserInfo withName = new UserInfo(orig);
870 withName.name = getOwnerName();
871 return withName;
872 } else {
873 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000874 }
875 }
876
877 @Override
878 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000879 int callingUserId = UserHandle.getCallingUserId();
880 if (callingUserId != userId && !hasManageUsersPermission()) {
881 synchronized (mPackagesLock) {
882 if (!isSameProfileGroupLP(callingUserId, userId)) {
883 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000884 "You need MANAGE_USERS permission to: check if specified user a " +
885 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000886 }
887 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000888 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700889 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700890 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000891 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700892 }
893 }
894
Amith Yamasani71e6c692013-03-24 17:39:28 -0700895 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700896 public boolean isDemoUser(int userId) {
897 int callingUserId = UserHandle.getCallingUserId();
898 if (callingUserId != userId && !hasManageUsersPermission()) {
899 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
900 + " is a demo user");
901 }
902 synchronized (mUsersLock) {
903 UserInfo userInfo = getUserInfoLU(userId);
904 return userInfo != null && userInfo.isDemo();
905 }
906 }
907
908 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700909 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700910 synchronized (mUsersLock) {
911 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700912 }
913 }
914
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700915 @Override
916 public boolean canHaveRestrictedProfile(int userId) {
917 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700918 synchronized (mUsersLock) {
919 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700920 if (userInfo == null || !userInfo.canHaveProfile()) {
921 return false;
922 }
923 if (!userInfo.isAdmin()) {
924 return false;
925 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800926 // restricted profile can be created if there is no DO set and the admin user has no PO;
927 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700928 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700929 }
930
Amith Yamasani195263742012-08-21 15:40:12 -0700931 /*
932 * Should be locked on mUsers before calling this.
933 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700934 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800935 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700936 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800937 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700938 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
939 return null;
940 }
Amith Yamasani12747872015-12-07 14:19:49 -0800941 return userData != null ? userData.info : null;
942 }
943
944 private UserData getUserDataLU(int userId) {
945 final UserData userData = mUsers.get(userId);
946 // If it is partial and not in the process of being removed, return as unknown user.
947 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
948 return null;
949 }
950 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700951 }
952
Fyodor Kupolov82402752015-10-28 14:54:51 -0700953 /**
954 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
955 * <p>No permissions checking or any addition checks are made</p>
956 */
957 private UserInfo getUserInfoNoChecks(int userId) {
958 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800959 final UserData userData = mUsers.get(userId);
960 return userData != null ? userData.info : null;
961 }
962 }
963
964 /**
965 * Obtains {@link #mUsersLock} and return UserData from mUsers.
966 * <p>No permissions checking or any addition checks are made</p>
967 */
968 private UserData getUserDataNoChecks(int userId) {
969 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700970 return mUsers.get(userId);
971 }
972 }
973
Amith Yamasani236b2b52015-08-18 14:32:14 -0700974 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700975 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700976 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700977 }
978
Amith Yamasani258848d2012-08-10 17:06:33 -0700979 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700980 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700981 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700982 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700983 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800984 UserData userData = getUserDataNoChecks(userId);
985 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700986 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
987 return;
988 }
Amith Yamasani12747872015-12-07 14:19:49 -0800989 if (name != null && !name.equals(userData.info.name)) {
990 userData.info.name = name;
991 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700992 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700993 }
994 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700995 if (changed) {
996 sendUserInfoChangedBroadcast(userId);
997 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700998 }
999
Amith Yamasani258848d2012-08-10 17:06:33 -07001000 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001001 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001002 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001003 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1004 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1005 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001006 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001007 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001008 }
1009
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001010
1011
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001012 private void sendUserInfoChangedBroadcast(int userId) {
1013 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1014 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1015 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001016 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001017 }
1018
Amith Yamasani258848d2012-08-10 17:06:33 -07001019 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001020 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001021 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001022 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001023 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1024 if (targetUserInfo == null || targetUserInfo.partial) {
1025 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001026 return null;
1027 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001028
1029 final int callingUserId = UserHandle.getCallingUserId();
1030 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1031 final int targetGroupId = targetUserInfo.profileGroupId;
1032 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1033 && callingGroupId == targetGroupId);
1034 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001035 checkManageUsersPermission("get the icon of a user who is not related");
1036 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001037
1038 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001039 return null;
1040 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001041 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001042 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001043
1044 try {
1045 return ParcelFileDescriptor.open(
1046 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1047 } catch (FileNotFoundException e) {
1048 Log.e(LOG_TAG, "Couldn't find icon file", e);
1049 }
1050 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001051 }
1052
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001053 public void makeInitialized(int userId) {
1054 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001055 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001056 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001057 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001058 userData = mUsers.get(userId);
1059 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001060 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001061 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001062 }
Amith Yamasani12747872015-12-07 14:19:49 -08001063 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1064 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001065 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001066 }
1067 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001068 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001069 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001070 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001071 }
1072
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001073 /**
1074 * If default guest restrictions haven't been initialized yet, add the basic
1075 * restrictions.
1076 */
1077 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001078 synchronized (mGuestRestrictions) {
1079 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001080 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001081 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001082 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1083 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1084 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001085 }
1086 }
1087
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001088 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301089 public Bundle getDefaultGuestRestrictions() {
1090 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001091 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301092 return new Bundle(mGuestRestrictions);
1093 }
1094 }
1095
1096 @Override
1097 public void setDefaultGuestRestrictions(Bundle restrictions) {
1098 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001099 synchronized (mGuestRestrictions) {
1100 mGuestRestrictions.clear();
1101 mGuestRestrictions.putAll(restrictions);
1102 }
1103 synchronized (mPackagesLock) {
1104 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301105 }
1106 }
1107
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001108 /**
1109 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1110 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001111 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001112 @Nullable Bundle global) {
1113 Preconditions.checkNotNull(local);
1114 boolean globalChanged = false;
1115 boolean localChanged;
1116 synchronized (mRestrictionsLock) {
1117 if (global != null) {
1118 // Update global.
1119 globalChanged = !UserRestrictionsUtils.areEqual(
1120 mDevicePolicyGlobalUserRestrictions, global);
1121 if (globalChanged) {
1122 mDevicePolicyGlobalUserRestrictions = global;
1123 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001124 // Remember the global restriction owner userId to be able to make a distinction
1125 // in getUserRestrictionSource on who set local policies.
1126 mGlobalRestrictionOwnerUserId = userId;
1127 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001128 if (mGlobalRestrictionOwnerUserId == userId) {
1129 // When profile owner sets restrictions it passes null global bundle and we
1130 // reset global restriction owner userId.
1131 // This means this user used to have DO, but now the DO is gone and the user
1132 // instead has PO.
1133 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1134 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001135 }
1136 {
1137 // Update local.
1138 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1139 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1140 if (localChanged) {
1141 mDevicePolicyLocalUserRestrictions.put(userId, local);
1142 }
1143 }
1144 }
1145 if (DBG) {
1146 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1147 + " global=" + global + (globalChanged ? " (changed)" : "")
1148 + " local=" + local + (localChanged ? " (changed)" : "")
1149 );
1150 }
1151 // Don't call them within the mRestrictionsLock.
1152 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001153 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001154 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001155 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001156 if (globalChanged) {
1157 writeUserListLP();
1158 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001159 }
1160
1161 synchronized (mRestrictionsLock) {
1162 if (globalChanged) {
1163 applyUserRestrictionsForAllUsersLR();
1164 } else if (localChanged) {
1165 applyUserRestrictionsLR(userId);
1166 }
1167 }
1168 }
1169
Makoto Onuki068c54a2015-10-13 14:34:03 -07001170 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001171 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001172 final Bundle baseRestrictions =
1173 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1174 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1175 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001176
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001177 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1178 // Common case first.
1179 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001180 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001181 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1182 UserRestrictionsUtils.merge(effective, global);
1183 UserRestrictionsUtils.merge(effective, local);
1184
Makoto Onuki068c54a2015-10-13 14:34:03 -07001185 return effective;
1186 }
1187
1188 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001189 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001190 if (DBG) {
1191 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1192 }
1193 mCachedEffectiveUserRestrictions.remove(userId);
1194 }
1195
1196 private Bundle getEffectiveUserRestrictions(int userId) {
1197 synchronized (mRestrictionsLock) {
1198 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1199 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001200 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001201 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1202 }
1203 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001204 }
1205 }
1206
Makoto Onuki068c54a2015-10-13 14:34:03 -07001207 /** @return a specific user restriction that's in effect currently. */
1208 @Override
1209 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001210 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1211 return false;
1212 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001213 Bundle restrictions = getEffectiveUserRestrictions(userId);
1214 return restrictions != null && restrictions.getBoolean(restrictionKey);
1215 }
1216
1217 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001218 * @hide
1219 *
1220 * Returns who set a user restriction on a user.
1221 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1222 * @param restrictionKey the string key representing the restriction
1223 * @param userId the id of the user for whom to retrieve the restrictions.
1224 * @return The source of user restriction. Any combination of
1225 * {@link UserManager#RESTRICTION_NOT_SET},
1226 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1227 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1228 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1229 */
1230 @Override
1231 public int getUserRestrictionSource(String restrictionKey, int userId) {
1232 checkManageUsersPermission("getUserRestrictionSource");
1233 int result = UserManager.RESTRICTION_NOT_SET;
1234
1235 // Shortcut for the most common case
1236 if (!hasUserRestriction(restrictionKey, userId)) {
1237 return result;
1238 }
1239
1240 if (hasBaseUserRestriction(restrictionKey, userId)) {
1241 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1242 }
1243
1244 synchronized(mRestrictionsLock) {
1245 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1246 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1247 && localRestrictions.getBoolean(restrictionKey)) {
1248 // Local restrictions may have been set by device owner the userId of which is
1249 // stored in mGlobalRestrictionOwnerUserId.
1250 if (mGlobalRestrictionOwnerUserId == userId) {
1251 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1252 } else {
1253 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1254 }
1255 }
1256 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1257 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1258 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1259 }
1260 }
1261
1262 return result;
1263 }
1264
1265 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001266 * @return UserRestrictions that are in effect currently. This always returns a new
1267 * {@link Bundle}.
1268 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001269 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001270 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001271 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001272 }
1273
1274 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001275 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1276 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001277 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1278 return false;
1279 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001280 synchronized (mRestrictionsLock) {
1281 Bundle bundle = mBaseUserRestrictions.get(userId);
1282 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1283 }
1284 }
1285
1286 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001287 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001288 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001289 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1290 return;
1291 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001292 synchronized (mRestrictionsLock) {
1293 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1294 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001295 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1296 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001297 newRestrictions.putBoolean(key, value);
1298
Fyodor Kupolov82402752015-10-28 14:54:51 -07001299 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001300 }
1301 }
1302
Makoto Onuki068c54a2015-10-13 14:34:03 -07001303 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001304 * Optionally updating user restrictions, calculate the effective user restrictions and also
1305 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001306 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001307 * @param newRestrictions User restrictions to set.
1308 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001309 * @param userId target user ID.
1310 */
1311 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001312 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001313 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001314
1315 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1316 mAppliedUserRestrictions.get(userId));
1317
1318 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001319 if (newRestrictions != null) {
1320 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001321 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1322
1323 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001324 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1325 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001326
1327 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1328 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001329 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001330 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001331 }
1332
Fyodor Kupolov82402752015-10-28 14:54:51 -07001333 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001334
Makoto Onuki759a7632015-10-28 16:43:10 -07001335 mCachedEffectiveUserRestrictions.put(userId, effective);
1336
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001337 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001338 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001339 debug("Applying user restrictions: userId=" + userId
1340 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001341 }
1342
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001343 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001344 mHandler.post(new Runnable() {
1345 @Override
1346 public void run() {
1347 try {
1348 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1349 } catch (RemoteException e) {
1350 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1351 }
1352 }
1353 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001354 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001355
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001356 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001357
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001358 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001359 }
1360
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001361 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001362 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001363 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1364 // actually, but we still need some kind of synchronization otherwise we might end up
1365 // calling listeners out-of-order, thus "LR".
1366
1367 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1368 return;
1369 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001370
1371 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1372 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1373
1374 mHandler.post(new Runnable() {
1375 @Override
1376 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001377 UserRestrictionsUtils.applyUserRestrictions(
1378 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001379
Makoto Onukid45a4a22015-11-02 17:17:38 -08001380 final UserRestrictionsListener[] listeners;
1381 synchronized (mUserRestrictionsListeners) {
1382 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1383 mUserRestrictionsListeners.toArray(listeners);
1384 }
1385 for (int i = 0; i < listeners.length; i++) {
1386 listeners[i].onUserRestrictionsChanged(userId,
1387 newRestrictionsFinal, prevRestrictionsFinal);
1388 }
1389 }
1390 });
1391 }
1392
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001393 // Package private for the inner class.
1394 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001395 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001396 }
1397
1398 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001399 // Package private for the inner class.
1400 void applyUserRestrictionsForAllUsersLR() {
1401 if (DBG) {
1402 debug("applyUserRestrictionsForAllUsersLR");
1403 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001404 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001405 mCachedEffectiveUserRestrictions.clear();
1406
Makoto Onuki068c54a2015-10-13 14:34:03 -07001407 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1408 // it on a handler.
1409 final Runnable r = new Runnable() {
1410 @Override
1411 public void run() {
1412 // Then get the list of running users.
1413 final int[] runningUsers;
1414 try {
1415 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1416 } catch (RemoteException e) {
1417 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1418 return;
1419 }
1420 // Then re-calculate the effective restrictions and apply, only for running users.
1421 // It's okay if a new user has started after the getRunningUserIds() call,
1422 // because we'll do the same thing (re-calculate the restrictions and apply)
1423 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001424 synchronized (mRestrictionsLock) {
1425 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001426 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001427 }
1428 }
1429 }
1430 };
1431 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001432 }
1433
Amith Yamasani258848d2012-08-10 17:06:33 -07001434 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001435 * Check if we've hit the limit of how many users can be created.
1436 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001437 private boolean isUserLimitReached() {
1438 int count;
1439 synchronized (mUsersLock) {
1440 count = getAliveUsersExcludingGuestsCountLU();
1441 }
1442 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001443 }
1444
1445 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001446 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001447 checkManageUsersPermission("check if more managed profiles can be added.");
1448 if (ActivityManager.isLowRamDeviceStatic()) {
1449 return false;
1450 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001451 if (!mContext.getPackageManager().hasSystemFeature(
1452 PackageManager.FEATURE_MANAGED_USERS)) {
1453 return false;
1454 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001455 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001456 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1457 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1458 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001459 return false;
1460 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001461 synchronized(mUsersLock) {
1462 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001463 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001464 return false;
1465 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001466 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1467 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001468 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001469 return usersCountAfterRemoving == 1
1470 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001471 }
1472 }
1473
Fyodor Kupolov82402752015-10-28 14:54:51 -07001474 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001475 int aliveUserCount = 0;
1476 final int totalUserCount = mUsers.size();
1477 // Skip over users being removed
1478 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001479 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001480 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001481 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001482 aliveUserCount++;
1483 }
1484 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001485 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001486 }
1487
1488 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001489 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001490 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1491 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1492 * permissions can make certain calls to the UserManager.
1493 *
1494 * @param message used as message if SecurityException is thrown
1495 * @throws SecurityException if the caller does not have enough privilege.
1496 */
1497 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1498 final int uid = Binder.getCallingUid();
1499 if (uid != Process.SYSTEM_UID && uid != 0
1500 && ActivityManager.checkComponentPermission(
1501 Manifest.permission.MANAGE_USERS,
1502 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1503 && ActivityManager.checkComponentPermission(
1504 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1505 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1506 throw new SecurityException(
1507 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1508 + message);
1509 }
1510 }
1511
1512 /**
1513 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001514 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001515 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001516 *
1517 * @param message used as message if SecurityException is thrown
1518 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001519 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001520 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001521 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001522 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001523 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1524 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001525 }
1526
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001527 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001528 * Enforces that only the system UID or root's UID or apps that have the
1529 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1530 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1531 * can make certain calls to the UserManager.
1532 *
1533 * @param message used as message if SecurityException is thrown
1534 * @throws SecurityException if the caller is not system or root
1535 * @see #hasManageOrCreateUsersPermission()
1536 */
1537 private static final void checkManageOrCreateUsersPermission(String message) {
1538 if (!hasManageOrCreateUsersPermission()) {
1539 throw new SecurityException(
1540 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1541 }
1542 }
1543
1544 /**
1545 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1546 * to create user/profiles other than what is allowed for
1547 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1548 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1549 */
1550 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1551 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1552 if (!hasManageOrCreateUsersPermission()) {
1553 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1554 + "permission to create an user with flags: " + creationFlags);
1555 }
1556 } else if (!hasManageUsersPermission()) {
1557 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1558 + " with flags: " + creationFlags);
1559 }
1560 }
1561
1562 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001563 * @return whether the calling UID is system UID or root's UID or the calling app has the
1564 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1565 */
1566 private static final boolean hasManageUsersPermission() {
1567 final int callingUid = Binder.getCallingUid();
1568 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1569 || callingUid == Process.ROOT_UID
1570 || ActivityManager.checkComponentPermission(
1571 android.Manifest.permission.MANAGE_USERS,
1572 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1573 }
1574
1575 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001576 * @return whether the calling UID is system UID or root's UID or the calling app has the
1577 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1578 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1579 */
1580 private static final boolean hasManageOrCreateUsersPermission() {
1581 final int callingUid = Binder.getCallingUid();
1582 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1583 || callingUid == Process.ROOT_UID
1584 || ActivityManager.checkComponentPermission(
1585 android.Manifest.permission.MANAGE_USERS,
1586 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1587 || ActivityManager.checkComponentPermission(
1588 android.Manifest.permission.CREATE_USERS,
1589 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1590 }
1591
1592 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001593 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1594 * UserManager.
1595 *
1596 * @param message used as message if SecurityException is thrown
1597 * @throws SecurityException if the caller is not system or root
1598 */
1599 private static void checkSystemOrRoot(String message) {
1600 final int uid = Binder.getCallingUid();
1601 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1602 throw new SecurityException("Only system may: " + message);
1603 }
1604 }
1605
Fyodor Kupolov82402752015-10-28 14:54:51 -07001606 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001607 try {
1608 File dir = new File(mUsersDir, Integer.toString(info.id));
1609 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001610 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001611 if (!dir.exists()) {
1612 dir.mkdir();
1613 FileUtils.setPermissions(
1614 dir.getPath(),
1615 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1616 -1, -1);
1617 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001618 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001619 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001620 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001621 info.iconPath = file.getAbsolutePath();
1622 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001623 try {
1624 os.close();
1625 } catch (IOException ioe) {
1626 // What the ... !
1627 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001628 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001629 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001630 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001631 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001632 }
1633
Amith Yamasani0b285492011-04-14 17:35:23 -07001634 /**
1635 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1636 * cache it elsewhere.
1637 * @return the array of user ids.
1638 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001639 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001640 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001641 return mUserIds;
1642 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001643 }
1644
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001645 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001646 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001647 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001648 return;
1649 }
1650 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001651 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001652 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001653 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001654 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001655 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656 int type;
1657 while ((type = parser.next()) != XmlPullParser.START_TAG
1658 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001659 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001660 }
1661
1662 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001663 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001664 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001665 return;
1666 }
1667
Amith Yamasani2a003292012-08-14 18:25:45 -07001668 mNextSerialNumber = -1;
1669 if (parser.getName().equals(TAG_USERS)) {
1670 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1671 if (lastSerialNumber != null) {
1672 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1673 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001674 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1675 if (versionNumber != null) {
1676 mUserVersion = Integer.parseInt(versionNumber);
1677 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001678 }
1679
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001680 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1681
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001682 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301683 if (type == XmlPullParser.START_TAG) {
1684 final String name = parser.getName();
1685 if (name.equals(TAG_USER)) {
1686 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001687
Amith Yamasani12747872015-12-07 14:19:49 -08001688 UserData userData = readUserLP(Integer.parseInt(id));
1689
1690 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001691 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001692 mUsers.put(userData.info.id, userData);
1693 if (mNextSerialNumber < 0
1694 || mNextSerialNumber <= userData.info.id) {
1695 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001696 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301697 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001698 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301699 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001700 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1701 && type != XmlPullParser.END_TAG) {
1702 if (type == XmlPullParser.START_TAG) {
1703 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001704 synchronized (mGuestRestrictions) {
1705 UserRestrictionsUtils
1706 .readRestrictions(parser, mGuestRestrictions);
1707 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001708 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1709 ) {
1710 UserRestrictionsUtils.readRestrictions(parser,
1711 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001712 }
1713 break;
1714 }
1715 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001716 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1717 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1718 if (ownerUserId != null) {
1719 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1720 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001721 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001722 }
1723 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001724 synchronized (mRestrictionsLock) {
1725 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1726 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001727 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001728 upgradeIfNecessaryLP();
1729 } catch (IOException | XmlPullParserException e) {
1730 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001731 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001732 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001733 }
1734 }
1735
Amith Yamasani6f34b412012-10-22 18:19:27 -07001736 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001737 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001738 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001739 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001740 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001741 int userVersion = mUserVersion;
1742 if (userVersion < 1) {
1743 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001744 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1745 if ("Primary".equals(userData.info.name)) {
1746 userData.info.name =
1747 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1748 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001749 }
1750 userVersion = 1;
1751 }
1752
Amith Yamasanibc9625052012-11-15 14:39:18 -08001753 if (userVersion < 2) {
1754 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001755 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1756 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1757 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1758 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001759 }
1760 userVersion = 2;
1761 }
1762
Amith Yamasani350962c2013-08-06 11:18:53 -07001763
Amith Yamasani5e486f52013-08-07 11:06:44 -07001764 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001765 userVersion = 4;
1766 }
1767
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001768 if (userVersion < 5) {
1769 initDefaultGuestRestrictions();
1770 userVersion = 5;
1771 }
1772
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001773 if (userVersion < 6) {
1774 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001775 synchronized (mUsersLock) {
1776 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001777 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001778 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001779 if (!splitSystemUser && userData.info.isRestricted()
1780 && (userData.info.restrictedProfileParentId
1781 == UserInfo.NO_PROFILE_GROUP_ID)) {
1782 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1783 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001784 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001785 }
1786 }
1787 userVersion = 6;
1788 }
1789
Amith Yamasani6f34b412012-10-22 18:19:27 -07001790 if (userVersion < USER_VERSION) {
1791 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1792 + USER_VERSION);
1793 } else {
1794 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001795
1796 if (originalVersion < mUserVersion) {
1797 writeUserListLP();
1798 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001799 }
1800 }
1801
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001802 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001803 int flags = UserInfo.FLAG_INITIALIZED;
1804 // In split system user mode, the admin and primary flags are assigned to the first human
1805 // user.
1806 if (!UserManager.isSplitSystemUser()) {
1807 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1808 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001809 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001810 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001811 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001812 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001813 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001814
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001815 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001816 try {
1817 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1818 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1819 for (String userRestriction : defaultFirstUserRestrictions) {
1820 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1821 restrictions.putBoolean(userRestriction, true);
1822 }
1823 }
1824 } catch (Resources.NotFoundException e) {
1825 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1826 }
1827
Makoto Onuki068c54a2015-10-13 14:34:03 -07001828 synchronized (mRestrictionsLock) {
1829 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1830 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001831
Fyodor Kupolov82402752015-10-28 14:54:51 -07001832 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001833 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001834
Amith Yamasani12747872015-12-07 14:19:49 -08001835 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001836 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001837 }
1838
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001839 private String getOwnerName() {
1840 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1841 }
1842
Amith Yamasani12747872015-12-07 14:19:49 -08001843 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001844 if (DBG) {
1845 debug("scheduleWriteUser");
1846 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001847 // No need to wrap it within a lock -- worst case, we'll just post the same message
1848 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001849 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1850 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001851 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1852 }
1853 }
1854
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001855 /*
1856 * Writes the user file in this format:
1857 *
1858 * <user flags="20039023" id="0">
1859 * <name>Primary</name>
1860 * </user>
1861 */
Amith Yamasani12747872015-12-07 14:19:49 -08001862 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001863 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001864 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001865 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001866 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001867 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001868 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001869 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001870 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1871
1872 // XmlSerializer serializer = XmlUtils.serializerInstance();
1873 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001874 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001875 serializer.startDocument(null, true);
1876 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1877
Amith Yamasani12747872015-12-07 14:19:49 -08001878 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001879 serializer.startTag(null, TAG_USER);
1880 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001881 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001882 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001883 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1884 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1885 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001886 if (userInfo.lastLoggedInFingerprint != null) {
1887 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1888 userInfo.lastLoggedInFingerprint);
1889 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001890 if (userInfo.iconPath != null) {
1891 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1892 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001893 if (userInfo.partial) {
1894 serializer.attribute(null, ATTR_PARTIAL, "true");
1895 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001896 if (userInfo.guestToRemove) {
1897 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1898 }
Kenny Guy2a764942014-04-02 13:29:20 +01001899 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1900 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1901 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001902 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001903 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1904 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1905 Integer.toString(userInfo.restrictedProfileParentId));
1906 }
Amith Yamasani12747872015-12-07 14:19:49 -08001907 // Write seed data
1908 if (userData.persistSeedData) {
1909 if (userData.seedAccountName != null) {
1910 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1911 }
1912 if (userData.seedAccountType != null) {
1913 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1914 }
1915 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001916 if (userInfo.name != null) {
1917 serializer.startTag(null, TAG_NAME);
1918 serializer.text(userInfo.name);
1919 serializer.endTag(null, TAG_NAME);
1920 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001921 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001922 UserRestrictionsUtils.writeRestrictions(serializer,
1923 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1924 UserRestrictionsUtils.writeRestrictions(serializer,
1925 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1926 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001927 }
Amith Yamasani12747872015-12-07 14:19:49 -08001928
1929 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001930 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001931 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001932 serializer.endTag(null, TAG_ACCOUNT);
1933 }
1934
Amith Yamasani12747872015-12-07 14:19:49 -08001935 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1936 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1937 userData.seedAccountOptions.saveToXml(serializer);
1938 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1939 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001940 serializer.endTag(null, TAG_USER);
1941
1942 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001943 userFile.finishWrite(fos);
1944 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001945 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001946 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001947 }
1948 }
1949
1950 /*
1951 * Writes the user list file in this format:
1952 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001953 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001954 * <user id="0"></user>
1955 * <user id="2"></user>
1956 * </users>
1957 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001958 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001959 if (DBG) {
1960 debug("writeUserList");
1961 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001962 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001963 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001964 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001965 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001966 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1967
1968 // XmlSerializer serializer = XmlUtils.serializerInstance();
1969 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001970 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001971 serializer.startDocument(null, true);
1972 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1973
1974 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001975 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001976 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001977
Adam Lesinskieddeb492014-09-08 17:50:03 -07001978 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001979 synchronized (mGuestRestrictions) {
1980 UserRestrictionsUtils
1981 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1982 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301983 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001984 synchronized (mRestrictionsLock) {
1985 UserRestrictionsUtils.writeRestrictions(serializer,
1986 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1987 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001988 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1989 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1990 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001991 int[] userIdsToWrite;
1992 synchronized (mUsersLock) {
1993 userIdsToWrite = new int[mUsers.size()];
1994 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001995 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001996 userIdsToWrite[i] = user.id;
1997 }
1998 }
1999 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002000 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002001 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002002 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002003 }
2004
2005 serializer.endTag(null, TAG_USERS);
2006
2007 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002008 userListFile.finishWrite(fos);
2009 } catch (Exception e) {
2010 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002011 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002012 }
2013 }
2014
Amith Yamasani12747872015-12-07 14:19:49 -08002015 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002016 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002017 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002018 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002019 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002020 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002021 long creationTime = 0L;
2022 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002023 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002024 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002025 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002026 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002027 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002028 boolean persistSeedData = false;
2029 String seedAccountName = null;
2030 String seedAccountType = null;
2031 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002032 Bundle baseRestrictions = new Bundle();
2033 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002034
2035 FileInputStream fis = null;
2036 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002037 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002038 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002039 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002040 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002041 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002042 int type;
2043 while ((type = parser.next()) != XmlPullParser.START_TAG
2044 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002045 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002046 }
2047
2048 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002049 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002050 return null;
2051 }
2052
2053 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002054 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2055 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002056 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002057 return null;
2058 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002059 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2060 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002061 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002062 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2063 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002064 lastLoggedInFingerprint = parser.getAttributeValue(null,
2065 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002066 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2067 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002068 restrictedProfileParentId = readIntAttribute(parser,
2069 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002070 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2071 if ("true".equals(valueString)) {
2072 partial = true;
2073 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002074 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2075 if ("true".equals(valueString)) {
2076 guestToRemove = true;
2077 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002078
Amith Yamasani12747872015-12-07 14:19:49 -08002079 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2080 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2081 if (seedAccountName != null || seedAccountType != null) {
2082 persistSeedData = true;
2083 }
2084
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002085 int outerDepth = parser.getDepth();
2086 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2087 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2088 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2089 continue;
2090 }
2091 String tag = parser.getName();
2092 if (TAG_NAME.equals(tag)) {
2093 type = parser.next();
2094 if (type == XmlPullParser.TEXT) {
2095 name = parser.getText();
2096 }
2097 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002098 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2099 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2100 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002101 } else if (TAG_ACCOUNT.equals(tag)) {
2102 type = parser.next();
2103 if (type == XmlPullParser.TEXT) {
2104 account = parser.getText();
2105 }
Amith Yamasani12747872015-12-07 14:19:49 -08002106 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2107 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2108 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002109 }
2110 }
2111 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002112
Amith Yamasani12747872015-12-07 14:19:49 -08002113 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002114 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002115 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002116 userInfo.creationTime = creationTime;
2117 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002118 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002119 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002120 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002121 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002122 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002123
2124 // Create the UserData object that's internal to this class
2125 UserData userData = new UserData();
2126 userData.info = userInfo;
2127 userData.account = account;
2128 userData.seedAccountName = seedAccountName;
2129 userData.seedAccountType = seedAccountType;
2130 userData.persistSeedData = persistSeedData;
2131 userData.seedAccountOptions = seedAccountOptions;
2132
Makoto Onuki068c54a2015-10-13 14:34:03 -07002133 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002134 mBaseUserRestrictions.put(id, baseRestrictions);
2135 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002136 }
Amith Yamasani12747872015-12-07 14:19:49 -08002137 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002138 } catch (IOException ioe) {
2139 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002140 } finally {
2141 if (fis != null) {
2142 try {
2143 fis.close();
2144 } catch (IOException e) {
2145 }
2146 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002147 }
2148 return null;
2149 }
2150
Amith Yamasani920ace02012-09-20 22:15:37 -07002151 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2152 String valueString = parser.getAttributeValue(null, attr);
2153 if (valueString == null) return defaultValue;
2154 try {
2155 return Integer.parseInt(valueString);
2156 } catch (NumberFormatException nfe) {
2157 return defaultValue;
2158 }
2159 }
2160
2161 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2162 String valueString = parser.getAttributeValue(null, attr);
2163 if (valueString == null) return defaultValue;
2164 try {
2165 return Long.parseLong(valueString);
2166 } catch (NumberFormatException nfe) {
2167 return defaultValue;
2168 }
2169 }
2170
Amith Yamasanib82add22013-07-09 11:24:44 -07002171 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002172 * Removes the app restrictions file for a specific package and user id, if it exists.
2173 */
2174 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2175 synchronized (mPackagesLock) {
2176 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002177 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002178 if (resFile.exists()) {
2179 resFile.delete();
2180 }
2181 }
2182 }
2183
Kenny Guya52dc3e2014-02-11 15:33:14 +00002184 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002185 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002186 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002187 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002188 }
2189
Amith Yamasani258848d2012-08-10 17:06:33 -07002190 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002191 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002192 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002193 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002194 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002195
Jessica Hummelbe81c802014-04-22 15:49:22 +01002196 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002197 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002198 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2199 return null;
2200 }
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002201 DeviceStorageMonitorInternal dsm = LocalServices
2202 .getService(DeviceStorageMonitorInternal.class);
2203 if (dsm.isMemoryLow()) {
2204 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2205 return null;
2206 }
phweisse9c44062016-02-10 12:57:38 +01002207 return createUserInternalUnchecked(name, flags, parentId);
2208 }
2209
2210 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002211 if (ActivityManager.isLowRamDeviceStatic()) {
2212 return null;
2213 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002214 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002215 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002216 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002217 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002218 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002219 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002220 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002221 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002222 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002223 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002224 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002225 if (parentId != UserHandle.USER_NULL) {
2226 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002227 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002228 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002229 if (parent == null) return null;
2230 }
2231 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2232 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2233 return null;
2234 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002235 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2236 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002237 // been reached, cannot add a user.
2238 return null;
2239 }
2240 // If we're adding a guest and there already exists one, bail.
2241 if (isGuest && findCurrentGuestUser() != null) {
2242 return null;
2243 }
2244 // In legacy mode, restricted profile's parent can only be the owner user
2245 if (isRestricted && !UserManager.isSplitSystemUser()
2246 && (parentId != UserHandle.USER_SYSTEM)) {
2247 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2248 return null;
2249 }
2250 if (isRestricted && UserManager.isSplitSystemUser()) {
2251 if (parent == null) {
2252 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2253 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002254 return null;
2255 }
Amith Yamasani12747872015-12-07 14:19:49 -08002256 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002257 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2258 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002259 return null;
2260 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002261 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002262 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2263 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002264 Log.e(LOG_TAG,
2265 "Ephemeral users are supported on split-system-user systems only.");
2266 return null;
2267 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002268 // In split system user mode, we assign the first human user the primary flag.
2269 // And if there is no device owner, we also assign the admin flag to primary user.
2270 if (UserManager.isSplitSystemUser()
2271 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2272 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002273 synchronized (mUsersLock) {
2274 if (!mIsDeviceManaged) {
2275 flags |= UserInfo.FLAG_ADMIN;
2276 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002277 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002278 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002279
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002280 userId = getNextAvailableId();
2281 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002282 boolean ephemeralGuests = Resources.getSystem()
2283 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002284
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002285 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002286 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2287 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2288 || (parent != null && parent.info.isEphemeral())) {
2289 flags |= UserInfo.FLAG_EPHEMERAL;
2290 }
2291
2292 userInfo = new UserInfo(userId, name, null, flags);
2293 userInfo.serialNumber = mNextSerialNumber++;
2294 long now = System.currentTimeMillis();
2295 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2296 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002297 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002298 userData = new UserData();
2299 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002300 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002301 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002302 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002303 writeUserListLP();
2304 if (parent != null) {
2305 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002306 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2307 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002308 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002309 }
Amith Yamasani12747872015-12-07 14:19:49 -08002310 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002311 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002312 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2313 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002314 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002315 }
Amith Yamasani12747872015-12-07 14:19:49 -08002316 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002317 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002318 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002319 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002320 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002321 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002322 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002323 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002324 mPm.createNewUser(userId);
2325 userInfo.partial = false;
2326 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002327 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002328 }
2329 updateUserIds();
2330 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002331 if (isGuest) {
2332 synchronized (mGuestRestrictions) {
2333 restrictions.putAll(mGuestRestrictions);
2334 }
2335 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002336 synchronized (mRestrictionsLock) {
2337 mBaseUserRestrictions.append(userId, restrictions);
2338 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002339 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002340 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2341 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2342 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2343 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002344 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002345 } finally {
2346 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002347 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002348 return userInfo;
2349 }
2350
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002351 @VisibleForTesting
2352 UserData putUserInfo(UserInfo userInfo) {
2353 final UserData userData = new UserData();
2354 userData.info = userInfo;
2355 synchronized (mUsers) {
2356 mUsers.put(userInfo.id, userData);
2357 }
2358 return userData;
2359 }
2360
2361 @VisibleForTesting
2362 void removeUserInfo(int userId) {
2363 synchronized (mUsers) {
2364 mUsers.remove(userId);
2365 }
2366 }
2367
Amith Yamasani0b285492011-04-14 17:35:23 -07002368 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002369 * @hide
2370 */
Amith Yamasani12747872015-12-07 14:19:49 -08002371 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002372 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002373 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002374 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2375 if (user == null) {
2376 return null;
2377 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002378 long identity = Binder.clearCallingIdentity();
2379 try {
2380 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2381 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2382 // the putIntForUser() will fail.
2383 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2384 android.provider.Settings.Secure.LOCATION_MODE,
2385 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2386 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2387 } finally {
2388 Binder.restoreCallingIdentity(identity);
2389 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002390 return user;
2391 }
2392
2393 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002394 * Find the current guest user. If the Guest user is partial,
2395 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002396 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002397 private UserInfo findCurrentGuestUser() {
2398 synchronized (mUsersLock) {
2399 final int size = mUsers.size();
2400 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002401 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002402 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2403 return user;
2404 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002405 }
2406 }
2407 return null;
2408 }
2409
2410 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002411 * Mark this guest user for deletion to allow us to create another guest
2412 * and switch to that user before actually removing this guest.
2413 * @param userHandle the userid of the current guest
2414 * @return whether the user could be marked for deletion
2415 */
Amith Yamasani12747872015-12-07 14:19:49 -08002416 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002417 public boolean markGuestForDeletion(int userHandle) {
2418 checkManageUsersPermission("Only the system can remove users");
2419 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2420 UserManager.DISALLOW_REMOVE_USER, false)) {
2421 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2422 return false;
2423 }
2424
2425 long ident = Binder.clearCallingIdentity();
2426 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002427 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002428 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002429 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002430 userData = mUsers.get(userHandle);
2431 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002432 return false;
2433 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002434 }
Amith Yamasani12747872015-12-07 14:19:49 -08002435 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002436 return false;
2437 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002438 // We set this to a guest user that is to be removed. This is a temporary state
2439 // where we are allowed to add new Guest users, even if this one is still not
2440 // removed. This user will still show up in getUserInfo() calls.
2441 // If we don't get around to removing this Guest user, it will be purged on next
2442 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002443 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002444 // Mark it as disabled, so that it isn't returned any more when
2445 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002446 userData.info.flags |= UserInfo.FLAG_DISABLED;
2447 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002448 }
2449 } finally {
2450 Binder.restoreCallingIdentity(ident);
2451 }
2452 return true;
2453 }
2454
2455 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002456 * Removes a user and all data directories created for that user. This method should be called
2457 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002458 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002459 */
Amith Yamasani12747872015-12-07 14:19:49 -08002460 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002461 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002462 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002463 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2464 UserManager.DISALLOW_REMOVE_USER, false)) {
2465 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2466 return false;
2467 }
2468
Kenny Guyee58b4f2014-05-23 15:19:53 +01002469 long ident = Binder.clearCallingIdentity();
2470 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002471 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002472 int currentUser = ActivityManager.getCurrentUser();
2473 if (currentUser == userHandle) {
2474 Log.w(LOG_TAG, "Current user cannot be removed");
2475 return false;
2476 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002477 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002478 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002479 userData = mUsers.get(userHandle);
2480 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002481 return false;
2482 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002483
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002484 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002485 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002486
Kenny Guyee58b4f2014-05-23 15:19:53 +01002487 try {
2488 mAppOpsService.removeUser(userHandle);
2489 } catch (RemoteException e) {
2490 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2491 }
2492 // Set this to a partially created user, so that the user will be purged
2493 // on next startup, in case the runtime stops now before stopping and
2494 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002495 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002496 // Mark it as disabled, so that it isn't returned any more when
2497 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002498 userData.info.flags |= UserInfo.FLAG_DISABLED;
2499 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002500 }
2501
Amith Yamasani12747872015-12-07 14:19:49 -08002502 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2503 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002504 // Send broadcast to notify system that the user removed was a
2505 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002506 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002507 }
2508
2509 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2510 int res;
2511 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002512 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2513 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002514 @Override
2515 public void userStopped(int userId) {
2516 finishRemoveUser(userId);
2517 }
2518 @Override
2519 public void userStopAborted(int userId) {
2520 }
2521 });
2522 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002523 return false;
2524 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002525 return res == ActivityManager.USER_OP_SUCCESS;
2526 } finally {
2527 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002528 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002529 }
2530
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002531 @VisibleForTesting
2532 void addRemovingUserIdLocked(int userId) {
2533 // We remember deleted user IDs to prevent them from being
2534 // reused during the current boot; they can still be reused
2535 // after a reboot or recycling of userIds.
2536 mRemovingUserIds.put(userId, true);
2537 mRecentlyRemovedIds.add(userId);
2538 // Keep LRU queue of recently removed IDs for recycling
2539 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2540 mRecentlyRemovedIds.removeFirst();
2541 }
2542 }
2543
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002544 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002545 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002546 // Let other services shutdown any activity and clean up their state before completely
2547 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002548 long ident = Binder.clearCallingIdentity();
2549 try {
2550 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2551 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002552 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2553 android.Manifest.permission.MANAGE_USERS,
2554
2555 new BroadcastReceiver() {
2556 @Override
2557 public void onReceive(Context context, Intent intent) {
2558 if (DBG) {
2559 Slog.i(LOG_TAG,
2560 "USER_REMOVED broadcast sent, cleaning up user data "
2561 + userHandle);
2562 }
2563 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002564 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002565 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002566 // Clean up any ActivityManager state
2567 LocalServices.getService(ActivityManagerInternal.class)
2568 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002569 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002570 }
2571 }.start();
2572 }
2573 },
2574
2575 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002576 } finally {
2577 Binder.restoreCallingIdentity(ident);
2578 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002579 }
2580
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002581 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002582 try {
2583 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2584 } catch (IllegalStateException e) {
2585 // This may be simply because the user was partially created.
2586 Slog.i(LOG_TAG,
2587 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2588 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002589
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002590 // Cleanup gatekeeper secure user id
2591 try {
2592 final IGateKeeperService gk = GateKeeper.getService();
2593 if (gk != null) {
2594 gk.clearSecureUserId(userHandle);
2595 }
2596 } catch (Exception ex) {
2597 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2598 }
2599
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002600 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002601 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002602
2603 // Clean up all data before removing metadata
2604 mPm.destroyUserData(userHandle,
2605 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2606
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002607 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002608 synchronized (mUsersLock) {
2609 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002610 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002611 }
2612 synchronized (mUserStates) {
2613 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002614 }
2615 synchronized (mRestrictionsLock) {
2616 mBaseUserRestrictions.remove(userHandle);
2617 mAppliedUserRestrictions.remove(userHandle);
2618 mCachedEffectiveUserRestrictions.remove(userHandle);
2619 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002620 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002621 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002622 synchronized (mPackagesLock) {
2623 writeUserListLP();
2624 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002625 // Remove user file
2626 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2627 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002628 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002629 if (RELEASE_DELETED_USER_ID) {
2630 synchronized (mUsers) {
2631 mRemovingUserIds.delete(userHandle);
2632 }
2633 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002634 }
2635
Kenny Guyf8d3a232014-05-15 16:09:52 +01002636 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002637 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002638 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2639 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002640 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002641 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002642 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002643 }
2644
Amith Yamasani2a003292012-08-14 18:25:45 -07002645 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002646 public Bundle getApplicationRestrictions(String packageName) {
2647 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2648 }
2649
2650 @Override
2651 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002652 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002653 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002654 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002655 }
2656 synchronized (mPackagesLock) {
2657 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002658 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002659 }
2660 }
2661
2662 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002663 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002664 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002665 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002666 if (restrictions != null) {
2667 restrictions.setDefusable(true);
2668 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002669 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002670 if (restrictions == null || restrictions.isEmpty()) {
2671 cleanAppRestrictionsForPackage(packageName, userId);
2672 } else {
2673 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002674 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002675 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002676 }
Robin Lee66e5d962014-04-09 16:44:21 +01002677
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002678 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2679 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2680 changeIntent.setPackage(packageName);
2681 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2682 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002683 }
2684
2685 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002686 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002687 try {
2688 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002689 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002690 } catch (NameNotFoundException nnfe) {
2691 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002692 } finally {
2693 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002694 }
2695 }
2696
Fyodor Kupolov82402752015-10-28 14:54:51 -07002697 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002698 AtomicFile restrictionsFile =
2699 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2700 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002701 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002702 }
2703
2704 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002705 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002706 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002707 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002708 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002709 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002710 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002711
2712 FileInputStream fis = null;
2713 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002714 fis = restrictionsFile.openRead();
2715 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002716 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002717 XmlUtils.nextElement(parser);
2718 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002719 Slog.e(LOG_TAG, "Unable to read restrictions file "
2720 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002721 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002722 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002723 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2724 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002725 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002726 } catch (IOException|XmlPullParserException e) {
2727 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002728 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002729 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002730 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002731 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002732 }
2733
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002734 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2735 XmlPullParser parser) throws XmlPullParserException, IOException {
2736 int type = parser.getEventType();
2737 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2738 String key = parser.getAttributeValue(null, ATTR_KEY);
2739 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2740 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2741 if (multiple != null) {
2742 values.clear();
2743 int count = Integer.parseInt(multiple);
2744 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2745 if (type == XmlPullParser.START_TAG
2746 && parser.getName().equals(TAG_VALUE)) {
2747 values.add(parser.nextText().trim());
2748 count--;
2749 }
2750 }
2751 String [] valueStrings = new String[values.size()];
2752 values.toArray(valueStrings);
2753 restrictions.putStringArray(key, valueStrings);
2754 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2755 restrictions.putBundle(key, readBundleEntry(parser, values));
2756 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2757 final int outerDepth = parser.getDepth();
2758 ArrayList<Bundle> bundleList = new ArrayList<>();
2759 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2760 Bundle childBundle = readBundleEntry(parser, values);
2761 bundleList.add(childBundle);
2762 }
2763 restrictions.putParcelableArray(key,
2764 bundleList.toArray(new Bundle[bundleList.size()]));
2765 } else {
2766 String value = parser.nextText().trim();
2767 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2768 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2769 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2770 restrictions.putInt(key, Integer.parseInt(value));
2771 } else {
2772 restrictions.putString(key, value);
2773 }
2774 }
2775 }
2776 }
2777
2778 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2779 throws IOException, XmlPullParserException {
2780 Bundle childBundle = new Bundle();
2781 final int outerDepth = parser.getDepth();
2782 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2783 readEntry(childBundle, values, parser);
2784 }
2785 return childBundle;
2786 }
2787
Fyodor Kupolov82402752015-10-28 14:54:51 -07002788 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002789 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002790 AtomicFile restrictionsFile = new AtomicFile(
2791 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002792 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002793 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002794 }
2795
2796 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002797 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002798 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002799 try {
2800 fos = restrictionsFile.startWrite();
2801 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2802
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002803 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002804 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002805 serializer.startDocument(null, true);
2806 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2807
2808 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002809 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002810 serializer.endTag(null, TAG_RESTRICTIONS);
2811
2812 serializer.endDocument();
2813 restrictionsFile.finishWrite(fos);
2814 } catch (Exception e) {
2815 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002816 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2817 }
2818 }
2819
2820 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2821 throws IOException {
2822 for (String key : restrictions.keySet()) {
2823 Object value = restrictions.get(key);
2824 serializer.startTag(null, TAG_ENTRY);
2825 serializer.attribute(null, ATTR_KEY, key);
2826
2827 if (value instanceof Boolean) {
2828 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2829 serializer.text(value.toString());
2830 } else if (value instanceof Integer) {
2831 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2832 serializer.text(value.toString());
2833 } else if (value == null || value instanceof String) {
2834 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2835 serializer.text(value != null ? (String) value : "");
2836 } else if (value instanceof Bundle) {
2837 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2838 writeBundle((Bundle) value, serializer);
2839 } else if (value instanceof Parcelable[]) {
2840 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2841 Parcelable[] array = (Parcelable[]) value;
2842 for (Parcelable parcelable : array) {
2843 if (!(parcelable instanceof Bundle)) {
2844 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2845 }
2846 serializer.startTag(null, TAG_ENTRY);
2847 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2848 writeBundle((Bundle) parcelable, serializer);
2849 serializer.endTag(null, TAG_ENTRY);
2850 }
2851 } else {
2852 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2853 String[] values = (String[]) value;
2854 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2855 for (String choice : values) {
2856 serializer.startTag(null, TAG_VALUE);
2857 serializer.text(choice != null ? choice : "");
2858 serializer.endTag(null, TAG_VALUE);
2859 }
2860 }
2861 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002862 }
2863 }
2864
2865 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002866 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002867 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002868 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002869 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002870 }
2871 }
2872
2873 @Override
2874 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002875 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002876 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002877 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002878 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002879 }
2880 // Not found
2881 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002882 }
2883 }
2884
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002885 @Override
2886 public long getUserCreationTime(int userHandle) {
2887 int callingUserId = UserHandle.getCallingUserId();
2888 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002889 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002890 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002892 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002893 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002894 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002895 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002896 }
2897 }
2898 }
2899 if (userInfo == null) {
2900 throw new SecurityException("userHandle can only be the calling user or a managed "
2901 + "profile associated with this user");
2902 }
2903 return userInfo.creationTime;
2904 }
2905
Amith Yamasani0b285492011-04-14 17:35:23 -07002906 /**
2907 * Caches the list of user ids in an array, adjusting the array size when necessary.
2908 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002909 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002910 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002911 synchronized (mUsersLock) {
2912 final int userSize = mUsers.size();
2913 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002914 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002915 num++;
2916 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002917 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002918 final int[] newUsers = new int[num];
2919 int n = 0;
2920 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002921 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002922 newUsers[n++] = mUsers.keyAt(i);
2923 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002924 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002925 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002926 }
2927 }
2928
2929 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002930 * Called right before a user is started. This gives us a chance to prepare
2931 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002932 */
2933 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002934 UserInfo userInfo = getUserInfo(userId);
2935 if (userInfo == null) {
2936 return;
2937 }
2938 final int userSerial = userInfo.serialNumber;
2939 // Migrate only if build fingerprints mismatch
2940 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002941 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002942 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002943
2944 if (userId != UserHandle.USER_SYSTEM) {
2945 synchronized (mRestrictionsLock) {
2946 applyUserRestrictionsLR(userId);
2947 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002948 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002949
2950 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002951 }
2952
2953 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002954 * Called right before a user is unlocked. This gives us a chance to prepare
2955 * app storage.
2956 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002957 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002958 UserInfo userInfo = getUserInfo(userId);
2959 if (userInfo == null) {
2960 return;
2961 }
2962 final int userSerial = userInfo.serialNumber;
2963 // Migrate only if build fingerprints mismatch
2964 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002965 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002966 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002967 }
2968
2969 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002970 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002971 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002972 * @param userId the user that was just foregrounded
2973 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002974 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002975 UserData userData = getUserDataNoChecks(userId);
2976 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002977 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2978 return;
2979 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002980
2981 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002982 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002983 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002984 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002985 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2986 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002987 }
2988
Amith Yamasanieb437d42016-04-29 09:31:25 -07002989 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07002990 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07002991 String demoLauncher =
2992 mContext.getResources().getString(
2993 com.android.internal.R.string.config_demoModeLauncherComponent);
2994 if (!TextUtils.isEmpty(demoLauncher)) {
2995 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07002996 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00002997 try {
2998 final IPackageManager iPm = AppGlobals.getPackageManager();
2999 iPm.setComponentEnabledSetting(componentToEnable,
3000 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3001 /* userId= */ userId);
3002 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3003 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3004 /* userId= */ userId, null);
3005 } catch (RemoteException re) {
3006 // Internal, shouldn't happen
3007 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003008 }
3009 }
3010 }
3011
Amith Yamasani920ace02012-09-20 22:15:37 -07003012 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003013 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003014 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003015 @VisibleForTesting
3016 int getNextAvailableId() {
3017 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003018 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003019 nextId = scanNextAvailableIdLocked();
3020 if (nextId >= 0) {
3021 return nextId;
3022 }
3023 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3024 // except most recently removed
3025 if (mRemovingUserIds.size() > 0) {
3026 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3027 mRemovingUserIds.clear();
3028 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3029 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003030 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003031 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003032 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003033 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003034 if (nextId < 0) {
3035 throw new IllegalStateException("No user id available!");
3036 }
3037 return nextId;
3038 }
3039
3040 private int scanNextAvailableIdLocked() {
3041 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3042 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3043 return i;
3044 }
3045 }
3046 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003047 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003048
Amith Yamasanifc95e702013-09-26 13:20:17 -07003049 private String packageToRestrictionsFileName(String packageName) {
3050 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3051 }
3052
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003053 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003054 * Enforce that serial number stored in user directory inode matches the
3055 * given expected value. Gracefully sets the serial number if currently
3056 * undefined.
3057 *
3058 * @throws IOException when problem extracting serial number, or serial
3059 * number is mismatched.
3060 */
3061 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003062 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3063 // When we're emulating FBE, the directory may have been chmod
3064 // 000'ed, meaning we can't read the serial number to enforce it;
3065 // instead of destroying the user, just log a warning.
3066 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3067 return;
3068 }
3069
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003070 final int foundSerial = getSerialNumber(file);
3071 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3072
3073 if (foundSerial == -1) {
3074 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3075 try {
3076 setSerialNumber(file, serialNumber);
3077 } catch (IOException e) {
3078 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3079 }
3080
3081 } else if (foundSerial != serialNumber) {
3082 throw new IOException("Found serial number " + foundSerial
3083 + " doesn't match expected " + serialNumber);
3084 }
3085 }
3086
3087 /**
3088 * Set serial number stored in user directory inode.
3089 *
3090 * @throws IOException if serial number was already set
3091 */
3092 private static void setSerialNumber(File file, int serialNumber)
3093 throws IOException {
3094 try {
3095 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3096 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3097 } catch (ErrnoException e) {
3098 throw e.rethrowAsIOException();
3099 }
3100 }
3101
3102 /**
3103 * Return serial number stored in user directory inode.
3104 *
3105 * @return parsed serial number, or -1 if not set
3106 */
3107 private static int getSerialNumber(File file) throws IOException {
3108 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003109 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3110 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003111 try {
3112 return Integer.parseInt(serial);
3113 } catch (NumberFormatException e) {
3114 throw new IOException("Bad serial number: " + serial);
3115 }
3116 } catch (ErrnoException e) {
3117 if (e.errno == OsConstants.ENODATA) {
3118 return -1;
3119 } else {
3120 throw e.rethrowAsIOException();
3121 }
3122 }
3123 }
3124
Amith Yamasani920ace02012-09-20 22:15:37 -07003125 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003126 public void setSeedAccountData(int userId, String accountName, String accountType,
3127 PersistableBundle accountOptions, boolean persist) {
3128 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3129 synchronized (mPackagesLock) {
3130 final UserData userData;
3131 synchronized (mUsersLock) {
3132 userData = getUserDataLU(userId);
3133 if (userData == null) {
3134 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3135 return;
3136 }
3137 userData.seedAccountName = accountName;
3138 userData.seedAccountType = accountType;
3139 userData.seedAccountOptions = accountOptions;
3140 userData.persistSeedData = persist;
3141 }
3142 if (persist) {
3143 writeUserLP(userData);
3144 }
3145 }
3146 }
3147
3148 @Override
3149 public String getSeedAccountName() throws RemoteException {
3150 checkManageUsersPermission("Cannot get seed account information");
3151 synchronized (mUsersLock) {
3152 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3153 return userData.seedAccountName;
3154 }
3155 }
3156
3157 @Override
3158 public String getSeedAccountType() throws RemoteException {
3159 checkManageUsersPermission("Cannot get seed account information");
3160 synchronized (mUsersLock) {
3161 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3162 return userData.seedAccountType;
3163 }
3164 }
3165
3166 @Override
3167 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3168 checkManageUsersPermission("Cannot get seed account information");
3169 synchronized (mUsersLock) {
3170 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3171 return userData.seedAccountOptions;
3172 }
3173 }
3174
3175 @Override
3176 public void clearSeedAccountData() throws RemoteException {
3177 checkManageUsersPermission("Cannot clear seed account information");
3178 synchronized (mPackagesLock) {
3179 UserData userData;
3180 synchronized (mUsersLock) {
3181 userData = getUserDataLU(UserHandle.getCallingUserId());
3182 if (userData == null) return;
3183 userData.clearSeedAccountData();
3184 }
3185 writeUserLP(userData);
3186 }
3187 }
3188
3189 @Override
3190 public boolean someUserHasSeedAccount(String accountName, String accountType)
3191 throws RemoteException {
3192 checkManageUsersPermission("Cannot check seed account information");
3193 synchronized (mUsersLock) {
3194 final int userSize = mUsers.size();
3195 for (int i = 0; i < userSize; i++) {
3196 final UserData data = mUsers.valueAt(i);
3197 if (data.info.isInitialized()) continue;
3198 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3199 continue;
3200 }
3201 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3202 continue;
3203 }
3204 return true;
3205 }
3206 }
3207 return false;
3208 }
3209
3210 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003211 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3212 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3213 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3214 }
3215
3216 int onShellCommand(Shell shell, String cmd) {
3217 if (cmd == null) {
3218 return shell.handleDefaultCommands(cmd);
3219 }
3220
3221 final PrintWriter pw = shell.getOutPrintWriter();
3222 try {
3223 switch(cmd) {
3224 case "list":
3225 return runList(pw);
3226 }
3227 } catch (RemoteException e) {
3228 pw.println("Remote exception: " + e);
3229 }
3230 return -1;
3231 }
3232
3233 private int runList(PrintWriter pw) throws RemoteException {
3234 final IActivityManager am = ActivityManagerNative.getDefault();
3235 final List<UserInfo> users = getUsers(false);
3236 if (users == null) {
3237 pw.println("Error: couldn't get users");
3238 return 1;
3239 } else {
3240 pw.println("Users:");
3241 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003242 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003243 pw.println("\t" + users.get(i).toString() + running);
3244 }
3245 return 0;
3246 }
3247 }
3248
3249 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003250 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3251 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3252 != PackageManager.PERMISSION_GRANTED) {
3253 pw.println("Permission Denial: can't dump UserManager from from pid="
3254 + Binder.getCallingPid()
3255 + ", uid=" + Binder.getCallingUid()
3256 + " without permission "
3257 + android.Manifest.permission.DUMP);
3258 return;
3259 }
3260
3261 long now = System.currentTimeMillis();
3262 StringBuilder sb = new StringBuilder();
3263 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003264 synchronized (mUsersLock) {
3265 pw.println("Users:");
3266 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003267 UserData userData = mUsers.valueAt(i);
3268 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003269 continue;
3270 }
Amith Yamasani12747872015-12-07 14:19:49 -08003271 UserInfo userInfo = userData.info;
3272 final int userId = userInfo.id;
3273 pw.print(" "); pw.print(userInfo);
3274 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003275 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003276 pw.print(" <removing> ");
3277 }
Amith Yamasani12747872015-12-07 14:19:49 -08003278 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003279 pw.print(" <partial>");
3280 }
3281 pw.println();
3282 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003283 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003284 pw.println("<unknown>");
3285 } else {
3286 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003287 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003288 sb.append(" ago");
3289 pw.println(sb);
3290 }
3291 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003292 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003293 pw.println("<unknown>");
3294 } else {
3295 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003296 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003297 sb.append(" ago");
3298 pw.println(sb);
3299 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003300 pw.print(" Last logged in fingerprint: ");
3301 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003302 pw.print(" Has profile owner: ");
3303 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003304 pw.println(" Restrictions:");
3305 synchronized (mRestrictionsLock) {
3306 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003307 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003308 pw.println(" Device policy local restrictions:");
3309 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003310 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003311 pw.println(" Effective restrictions:");
3312 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003313 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003314 }
Amith Yamasani12747872015-12-07 14:19:49 -08003315
3316 if (userData.account != null) {
3317 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003318 pw.println();
3319 }
Amith Yamasani12747872015-12-07 14:19:49 -08003320
3321 if (userData.seedAccountName != null) {
3322 pw.print(" Seed account name: " + userData.seedAccountName);
3323 pw.println();
3324 if (userData.seedAccountType != null) {
3325 pw.print(" account type: " + userData.seedAccountType);
3326 pw.println();
3327 }
3328 if (userData.seedAccountOptions != null) {
3329 pw.print(" account options exist");
3330 pw.println();
3331 }
3332 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003333 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003334 }
Amith Yamasani12747872015-12-07 14:19:49 -08003335 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003336 pw.println(" Device policy global restrictions:");
3337 synchronized (mRestrictionsLock) {
3338 UserRestrictionsUtils
3339 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3340 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003341 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003342 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3343 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003344 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003345 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003346 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003347 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003348 synchronized (mUsersLock) {
3349 pw.println();
3350 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003351 if (mRemovingUserIds.size() > 0) {
3352 pw.println();
3353 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3354 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003355 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003356 synchronized (mUserStates) {
3357 pw.println(" Started users state: " + mUserStates);
3358 }
Amith Yamasani12747872015-12-07 14:19:49 -08003359 // Dump some capabilities
3360 pw.println();
3361 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3362 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003363 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3364 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003365 }
3366 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003367
3368 final class MainHandler extends Handler {
3369
3370 @Override
3371 public void handleMessage(Message msg) {
3372 switch (msg.what) {
3373 case WRITE_USER_MSG:
3374 removeMessages(WRITE_USER_MSG, msg.obj);
3375 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003376 int userId = ((UserData) msg.obj).info.id;
3377 UserData userData = getUserDataNoChecks(userId);
3378 if (userData != null) {
3379 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003380 }
3381 }
3382 }
3383 }
3384 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003385
3386 /**
3387 * @param userId
3388 * @return whether the user has been initialized yet
3389 */
3390 boolean isInitialized(int userId) {
3391 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3392 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003393
3394 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003395 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003396 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3397 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003398 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003399 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003400 }
3401
3402 @Override
3403 public Bundle getBaseUserRestrictions(int userId) {
3404 synchronized (mRestrictionsLock) {
3405 return mBaseUserRestrictions.get(userId);
3406 }
3407 }
3408
3409 @Override
3410 public void setBaseUserRestrictionsByDpmsForMigration(
3411 int userId, Bundle baseRestrictions) {
3412 synchronized (mRestrictionsLock) {
3413 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003414 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003415 }
3416
Amith Yamasani12747872015-12-07 14:19:49 -08003417 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003418 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003419 if (userData != null) {
3420 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003421 } else {
3422 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3423 }
3424 }
3425 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003426
3427 @Override
3428 public boolean getUserRestriction(int userId, String key) {
3429 return getUserRestrictions(userId).getBoolean(key);
3430 }
3431
3432 @Override
3433 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3434 synchronized (mUserRestrictionsListeners) {
3435 mUserRestrictionsListeners.add(listener);
3436 }
3437 }
3438
3439 @Override
3440 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3441 synchronized (mUserRestrictionsListeners) {
3442 mUserRestrictionsListeners.remove(listener);
3443 }
3444 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003445
3446 @Override
3447 public void setDeviceManaged(boolean isManaged) {
3448 synchronized (mUsersLock) {
3449 mIsDeviceManaged = isManaged;
3450 }
3451 }
3452
3453 @Override
3454 public void setUserManaged(int userId, boolean isManaged) {
3455 synchronized (mUsersLock) {
3456 mIsUserManaged.put(userId, isManaged);
3457 }
3458 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003459
3460 @Override
3461 public void setUserIcon(int userId, Bitmap bitmap) {
3462 long ident = Binder.clearCallingIdentity();
3463 try {
3464 synchronized (mPackagesLock) {
3465 UserData userData = getUserDataNoChecks(userId);
3466 if (userData == null || userData.info.partial) {
3467 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3468 return;
3469 }
3470 writeBitmapLP(userData.info, bitmap);
3471 writeUserLP(userData);
3472 }
3473 sendUserInfoChangedBroadcast(userId);
3474 } finally {
3475 Binder.restoreCallingIdentity(ident);
3476 }
3477 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003478
3479 @Override
3480 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3481 synchronized (mUsersLock) {
3482 mForceEphemeralUsers = forceEphemeralUsers;
3483 }
3484 }
3485
3486 @Override
3487 public void removeAllUsers() {
3488 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3489 // Remove the non-system users straight away.
3490 removeNonSystemUsers();
3491 } else {
3492 // Switch to the system user first and then remove the other users.
3493 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3494 @Override
3495 public void onReceive(Context context, Intent intent) {
3496 int userId =
3497 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3498 if (userId != UserHandle.USER_SYSTEM) {
3499 return;
3500 }
3501 mContext.unregisterReceiver(this);
3502 removeNonSystemUsers();
3503 }
3504 };
3505 IntentFilter userSwitchedFilter = new IntentFilter();
3506 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3507 mContext.registerReceiver(
3508 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3509
3510 // Switch to the system user.
3511 ActivityManager am =
3512 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3513 am.switchUser(UserHandle.USER_SYSTEM);
3514 }
3515 }
phweisse9c44062016-02-10 12:57:38 +01003516
3517 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003518 public void onEphemeralUserStop(int userId) {
3519 synchronized (mUsersLock) {
3520 UserInfo userInfo = getUserInfoLU(userId);
3521 if (userInfo != null && userInfo.isEphemeral()) {
3522 // Do not allow switching back to the ephemeral user again as the user is going
3523 // to be deleted.
3524 userInfo.flags |= UserInfo.FLAG_DISABLED;
3525 if (userInfo.isGuest()) {
3526 // Indicate that the guest will be deleted after it stops.
3527 userInfo.guestToRemove = true;
3528 }
3529 }
3530 }
3531 }
3532
3533 @Override
phweisse9c44062016-02-10 12:57:38 +01003534 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3535 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3536 // Keep this in sync with UserManager.createUser
3537 if (user != null && !user.isAdmin()) {
3538 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3539 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3540 }
3541 return user;
3542 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003543
3544 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003545 public boolean isUserRunning(int userId) {
3546 synchronized (mUserStates) {
3547 return mUserStates.get(userId, -1) >= 0;
3548 }
3549 }
3550
3551 @Override
3552 public void setUserState(int userId, int userState) {
3553 synchronized (mUserStates) {
3554 mUserStates.put(userId, userState);
3555 }
3556 }
3557
3558 @Override
3559 public void removeUserState(int userId) {
3560 synchronized (mUserStates) {
3561 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003562 }
3563 }
3564
3565 @Override
3566 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003567 synchronized (mUserStates) {
3568 int state = mUserStates.get(userId, -1);
3569 return (state == UserState.STATE_RUNNING_UNLOCKING)
3570 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003571 }
3572 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003573 }
3574
3575 /* Remove all the users except of the system one. */
3576 private void removeNonSystemUsers() {
3577 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3578 synchronized (mUsersLock) {
3579 final int userSize = mUsers.size();
3580 for (int i = 0; i < userSize; i++) {
3581 UserInfo ui = mUsers.valueAt(i).info;
3582 if (ui.id != UserHandle.USER_SYSTEM) {
3583 usersToRemove.add(ui);
3584 }
3585 }
3586 }
3587 for (UserInfo ui: usersToRemove) {
3588 removeUser(ui.id);
3589 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003590 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003591
3592 private class Shell extends ShellCommand {
3593 @Override
3594 public int onCommand(String cmd) {
3595 return onShellCommand(this, cmd);
3596 }
3597
3598 @Override
3599 public void onHelp() {
3600 final PrintWriter pw = getOutPrintWriter();
3601 pw.println("User manager (user) commands:");
3602 pw.println(" help");
3603 pw.println(" Print this help text.");
3604 pw.println("");
3605 pw.println(" list");
3606 pw.println(" Prints all users on the system.");
3607 }
3608 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003609
3610 private static void debug(String message) {
3611 Log.d(LOG_TAG, message +
3612 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3613 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003614}