blob: af055da2b9e69efa81a117b151cd6a71e95c1b9c [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;
Amith Yamasanieb437d42016-04-29 09:31:25 -070030import 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 Shanka194e4152016-07-06 17:49:37 -070041import 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;
Jeff Sharkey47f71082016-02-01 17:03:54 -070098
99import 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;
116import java.util.List;
117
Makoto Onuki068c54a2015-10-13 14:34:03 -0700118/**
119 * Service for {@link UserManager}.
120 *
121 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700122 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800123 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700124 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
125 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
126 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700127 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700128public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700129
Amith Yamasani2a003292012-08-14 18:25:45 -0700130 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800131 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800132 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700133
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800135 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700137 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700139 private static final String ATTR_CREATION_TIME = "created";
140 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600141 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700142 private static final String ATTR_SERIAL_NO = "serialNumber";
143 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700144 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700145 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700146 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100147 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700148 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800149 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
150 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530151 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800154 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800155 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100156 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800157 private static final String TAG_ENTRY = "entry";
158 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800159 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700161 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800162 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700163
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700164 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
165 private static final String ATTR_TYPE_STRING = "s";
166 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700167 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700168 private static final String ATTR_TYPE_BUNDLE = "B";
169 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700170
Amith Yamasani0b285492011-04-14 17:35:23 -0700171 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700173 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100174 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700175
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700177 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700179 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
180 UserInfo.FLAG_MANAGED_PROFILE
181 | UserInfo.FLAG_EPHEMERAL
182 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700183 | UserInfo.FLAG_GUEST
184 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700185
Amith Yamasani634cf312012-10-04 17:34:21 -0700186 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700187 // We need to keep process uid within Integer.MAX_VALUE.
188 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700189
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700190 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700191
Amith Yamasani920ace02012-09-20 22:15:37 -0700192 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
193
Nicolas Prevotb8186812015-08-06 15:00:03 +0100194 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700195 // without first making sure that the rest of the framework is prepared for it.
196 private static final int MAX_MANAGED_PROFILES = 1;
197
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800198 static final int WRITE_USER_MSG = 1;
199 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530200
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700201 private static final String XATTR_SERIAL = "user.serial";
202
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800203 // Tron counters
204 private static final String TRON_GUEST_CREATED = "users_guest_created";
205 private static final String TRON_USER_CREATED = "users_user_created";
206
Dianne Hackborn4428e172012-08-24 17:43:05 -0700207 private final Context mContext;
208 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700209 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700210 // Short-term lock for internal state, when interaction/sync with PM is not required
211 private final Object mUsersLock = new Object();
212 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700213
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800214 private final Handler mHandler;
215
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700216 private final File mUsersDir;
217 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700218
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800219 private static final IBinder mUserRestriconToken = new Binder();
220
Makoto Onuki068c54a2015-10-13 14:34:03 -0700221 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800222 * User-related information that is used for persisting to flash. Only UserInfo is
223 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800224 */
Amith Yamasani12747872015-12-07 14:19:49 -0800225 private static class UserData {
226 // Basic user information and properties
227 UserInfo info;
228 // Account name used when there is a strong association between a user and an account
229 String account;
230 // Account information for seeding into a newly created user. This could also be
231 // used for login validation for an existing user, for updating their credentials.
232 // In the latter case, data may not need to be persisted as it is only valid for the
233 // current login session.
234 String seedAccountName;
235 String seedAccountType;
236 PersistableBundle seedAccountOptions;
237 // Whether to perist the seed account information to be available after a boot
238 boolean persistSeedData;
239
240 void clearSeedAccountData() {
241 seedAccountName = null;
242 seedAccountType = null;
243 seedAccountOptions = null;
244 persistSeedData = false;
245 }
246 }
247
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800248 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800249 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800250
251 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700252 * User restrictions set via UserManager. This doesn't include restrictions set by
253 * device owner / profile owners.
254 *
255 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
256 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
257 * maybe shared between {@link #mBaseUserRestrictions} and
258 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
259 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700260 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700261 */
262 @GuardedBy("mRestrictionsLock")
263 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
264
265 /**
266 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
267 * with device / profile owner restrictions. We'll initialize it lazily; use
268 * {@link #getEffectiveUserRestrictions} to access it.
269 *
270 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
271 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
272 * maybe shared between {@link #mBaseUserRestrictions} and
273 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
274 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700275 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700276 */
277 @GuardedBy("mRestrictionsLock")
278 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
279
Makoto Onuki4f160732015-10-27 17:15:38 -0700280 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800281 * User restrictions that have already been applied in
282 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
283 * that have changed since the last
284 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700285 */
286 @GuardedBy("mRestrictionsLock")
287 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
288
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800289 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800290 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
291 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800292 */
293 @GuardedBy("mRestrictionsLock")
294 private Bundle mDevicePolicyGlobalUserRestrictions;
295
296 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100297 * Id of the user that set global restrictions.
298 */
299 @GuardedBy("mRestrictionsLock")
300 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
301
302 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800303 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
304 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800305 */
306 @GuardedBy("mRestrictionsLock")
307 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
308
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800309 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530310 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800311
312 /**
313 * Set of user IDs being actively removed. Removed IDs linger in this set
314 * for several seconds to work around a VFS caching issue.
315 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700316 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800317 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700318
Fyodor Kupolov82402752015-10-28 14:54:51 -0700319 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700320 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800321 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700322 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700323 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700324
Jason Monk62062992014-05-06 09:55:28 -0400325 private IAppOpsService mAppOpsService;
326
Makoto Onuki068c54a2015-10-13 14:34:03 -0700327 private final LocalService mLocalService;
328
Makoto Onukie7927da2015-11-25 10:05:17 -0800329 @GuardedBy("mUsersLock")
330 private boolean mIsDeviceManaged;
331
332 @GuardedBy("mUsersLock")
333 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
334
Makoto Onukid45a4a22015-11-02 17:17:38 -0800335 @GuardedBy("mUserRestrictionsListeners")
336 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
337 new ArrayList<>();
338
Clara Bayarria1771112015-12-18 16:29:18 +0000339 private final LockPatternUtils mLockPatternUtils;
340
Ricky Waib1dd80b2016-06-07 18:00:55 +0100341 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
342 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
343
344 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
345 @Override
346 public void onReceive(Context context, Intent intent) {
347 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
348 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
349 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
350 setQuietModeEnabled(userHandle, false);
351 if (target != null) {
352 try {
353 mContext.startIntentSender(target, null, 0, 0, 0);
354 } catch (IntentSender.SendIntentException e) {
355 /* ignore */
356 }
357 }
358 }
359 }
360 };
361
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100362 /**
363 * Whether all users should be created ephemeral.
364 */
365 @GuardedBy("mUsersLock")
366 private boolean mForceEphemeralUsers;
367
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000368 @GuardedBy("mUserStates")
369 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700370
Amith Yamasani258848d2012-08-10 17:06:33 -0700371 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700372
Dianne Hackborn4428e172012-08-24 17:43:05 -0700373 public static UserManagerService getInstance() {
374 synchronized (UserManagerService.class) {
375 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700376 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700377 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700378
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700379 public static class LifeCycle extends SystemService {
380
381 private UserManagerService mUms;
382
383 /**
384 * @param context
385 */
386 public LifeCycle(Context context) {
387 super(context);
388 }
389
390 @Override
391 public void onStart() {
392 mUms = UserManagerService.getInstance();
393 publishBinderService(Context.USER_SERVICE, mUms);
394 }
395
396 @Override
397 public void onBootPhase(int phase) {
398 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
399 mUms.cleanupPartialUsers();
400 }
401 }
402 }
403
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800404 @VisibleForTesting
405 UserManagerService(File dataDir) {
406 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700407 }
408
Dianne Hackborn4428e172012-08-24 17:43:05 -0700409 /**
410 * Called by package manager to create the service. This is closely
411 * associated with the package manager, and the given lock is the
412 * package manager's own lock.
413 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800414 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
415 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700416 }
417
Dianne Hackborn4428e172012-08-24 17:43:05 -0700418 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800419 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700420 mContext = context;
421 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700422 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800423 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800424 synchronized (mPackagesLock) {
425 mUsersDir = new File(dataDir, USER_INFO_DIR);
426 mUsersDir.mkdirs();
427 // Make zeroth user directory, for services to migrate their files to that location
428 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
429 userZeroDir.mkdirs();
430 FileUtils.setPermissions(mUsersDir.toString(),
431 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
432 -1, -1);
433 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
434 initDefaultGuestRestrictions();
435 readUserListLP();
436 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700437 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700438 mLocalService = new LocalService();
439 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000440 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000441 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700442 }
443
444 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400445 mAppOpsService = IAppOpsService.Stub.asInterface(
446 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800447
448 synchronized (mRestrictionsLock) {
449 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400450 }
Samuel Tand9453b82016-03-14 15:57:02 -0700451
452 UserInfo currentGuestUser = findCurrentGuestUser();
453 if (currentGuestUser != null && !hasUserRestriction(
454 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
455 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
456 // to it, in case this guest was created in a previous version where this
457 // user restriction was not a default guest restriction.
458 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
459 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700460
Ricky Waib1dd80b2016-06-07 18:00:55 +0100461 mContext.registerReceiver(mDisableQuietModeCallback,
462 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
463 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700464 }
465
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700466 void cleanupPartialUsers() {
467 // Prune out any partially created, partially removed and ephemeral users.
468 ArrayList<UserInfo> partials = new ArrayList<>();
469 synchronized (mUsersLock) {
470 final int userSize = mUsers.size();
471 for (int i = 0; i < userSize; i++) {
472 UserInfo ui = mUsers.valueAt(i).info;
473 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
474 partials.add(ui);
Amith Yamasaniae261892016-06-27 10:40:09 -0700475 mRemovingUserIds.append(ui.id, true);
476 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700477 }
478 }
479 }
480 final int partialsSize = partials.size();
481 for (int i = 0; i < partialsSize; i++) {
482 UserInfo ui = partials.get(i);
483 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
484 + " (name=" + ui.name + ")");
485 removeUserState(ui.id);
486 }
487 }
488
Amith Yamasani258848d2012-08-10 17:06:33 -0700489 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800490 public String getUserAccount(int userId) {
491 checkManageUserAndAcrossUsersFullPermission("get user account");
492 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800493 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800494 }
495 }
496
497 @Override
498 public void setUserAccount(int userId, String accountName) {
499 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800500 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800501 synchronized (mPackagesLock) {
502 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800503 final UserData userData = mUsers.get(userId);
504 if (userData == null) {
505 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
506 return;
507 }
508 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800509 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800510 userData.account = accountName;
511 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800512 }
513 }
514
515 if (userToUpdate != null) {
516 writeUserLP(userToUpdate);
517 }
518 }
519 }
520
521 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700522 public UserInfo getPrimaryUser() {
523 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700524 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700525 final int userSize = mUsers.size();
526 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800527 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800528 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700529 return ui;
530 }
531 }
532 }
533 return null;
534 }
535
536 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700537 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700538 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700539 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700540 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700541 final int userSize = mUsers.size();
542 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800543 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700544 if (ui.partial) {
545 continue;
546 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800547 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700548 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700549 }
Amith Yamasani13593602012-03-22 16:16:17 -0700550 }
551 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700552 }
Amith Yamasani13593602012-03-22 16:16:17 -0700553 }
554
Amith Yamasani258848d2012-08-10 17:06:33 -0700555 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100556 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700557 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800558 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700559 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700560 } else {
561 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800562 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700563 final long ident = Binder.clearCallingIdentity();
564 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700565 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700566 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100567 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700568 } finally {
569 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000570 }
571 }
572
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700573 @Override
574 public int[] getProfileIds(int userId, boolean enabledOnly) {
575 if (userId != UserHandle.getCallingUserId()) {
576 checkManageUsersPermission("getting profiles related to user " + userId);
577 }
578 final long ident = Binder.clearCallingIdentity();
579 try {
580 synchronized (mUsersLock) {
581 return getProfileIdsLU(userId, enabledOnly).toArray();
582 }
583 } finally {
584 Binder.restoreCallingIdentity(ident);
585 }
586 }
587
Amith Yamasanibe465322014-04-24 13:45:17 -0700588 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700589 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700590 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
591 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
592 for (int i = 0; i < profileIds.size(); i++) {
593 int profileId = profileIds.get(i);
594 UserInfo userInfo = mUsers.get(profileId).info;
595 // If full info is not required - clear PII data to prevent 3P apps from reading it
596 if (!fullInfo) {
597 userInfo = new UserInfo(userInfo);
598 userInfo.name = null;
599 userInfo.iconPath = null;
600 } else {
601 userInfo = userWithName(userInfo);
602 }
603 users.add(userInfo);
604 }
605 return users;
606 }
607
608 /**
609 * Assume permissions already checked and caller's identity cleared
610 */
611 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700612 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700613 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700614 if (user == null) {
615 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700616 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700617 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700618 final int userSize = mUsers.size();
619 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800620 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700621 if (!isProfileOf(user, profile)) {
622 continue;
623 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100624 if (enabledOnly && !profile.isEnabled()) {
625 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700626 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700627 if (mRemovingUserIds.get(profile.id)) {
628 continue;
629 }
Tony Mak80189cd2016-04-05 17:21:42 +0100630 if (profile.partial) {
631 continue;
632 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700633 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700634 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700635 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700636 }
637
Jessica Hummelbe81c802014-04-22 15:49:22 +0100638 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700639 public int getCredentialOwnerProfile(int userHandle) {
640 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000641 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700642 synchronized (mUsersLock) {
643 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700644 if (profileParent != null) {
645 return profileParent.id;
646 }
647 }
648 }
649
650 return userHandle;
651 }
652
653 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700654 public boolean isSameProfileGroup(int userId, int otherUserId) {
655 if (userId == otherUserId) return true;
656 checkManageUsersPermission("check if in the same profile group");
657 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700658 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700659 }
660 }
661
Fyodor Kupolov82402752015-10-28 14:54:51 -0700662 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
663 synchronized (mUsersLock) {
664 UserInfo userInfo = getUserInfoLU(userId);
665 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
666 return false;
667 }
668 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
669 if (otherUserInfo == null
670 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
671 return false;
672 }
673 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700674 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700675 }
676
677 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100678 public UserInfo getProfileParent(int userHandle) {
679 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700680 synchronized (mUsersLock) {
681 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700682 }
683 }
684
Fyodor Kupolov82402752015-10-28 14:54:51 -0700685 private UserInfo getProfileParentLU(int userHandle) {
686 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700687 if (profile == null) {
688 return null;
689 }
690 int parentUserId = profile.profileGroupId;
691 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
692 return null;
693 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700694 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100695 }
696 }
697
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100699 return user.id == profile.id ||
700 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
701 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000702 }
703
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000704 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000705 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100706 Intent intent = new Intent();
707 if (inQuietMode) {
708 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
709 } else {
710 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
711 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000712 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
713 intent.putExtra(Intent.EXTRA_USER, profileHandle);
714 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000715 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000716 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000717 }
718
719 @Override
720 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
721 checkManageUsersPermission("silence profile");
722 boolean changed = false;
723 UserInfo profile, parent;
724 synchronized (mPackagesLock) {
725 synchronized (mUsersLock) {
726 profile = getUserInfoLU(userHandle);
727 parent = getProfileParentLU(userHandle);
728
729 }
730 if (profile == null || !profile.isManagedProfile()) {
731 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
732 }
733 if (profile.isQuietModeEnabled() != enableQuietMode) {
734 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800735 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000736 changed = true;
737 }
738 }
739 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000740 long identity = Binder.clearCallingIdentity();
741 try {
742 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100743 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100744 LocalServices.getService(ActivityManagerInternal.class)
745 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000746 } else {
747 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
748 }
749 } catch (RemoteException e) {
750 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
751 } finally {
752 Binder.restoreCallingIdentity(identity);
753 }
754
755 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
756 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000757 }
758 }
759
760 @Override
761 public boolean isQuietModeEnabled(int userHandle) {
762 synchronized (mPackagesLock) {
763 UserInfo info;
764 synchronized (mUsersLock) {
765 info = getUserInfoLU(userHandle);
766 }
767 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000768 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000769 }
770 return info.isQuietModeEnabled();
771 }
772 }
773
Kenny Guya52dc3e2014-02-11 15:33:14 +0000774 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100775 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100776 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600777 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100778 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100779 // if the user is already unlocked, no need to show a profile challenge
780 setQuietModeEnabled(userHandle, false);
781 return true;
782 }
783
784 long identity = Binder.clearCallingIdentity();
785 try {
786 // otherwise, we show a profile challenge to trigger decryption of the user
787 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
788 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100789 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
790 // lock, confirm screenlock page will know and show personal challenge, and unlock
791 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100792 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
793 userHandle);
794 if (unlockIntent == null) {
795 return false;
796 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100797 final Intent callBackIntent = new Intent(
798 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100799 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100800 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100801 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100802 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
803 callBackIntent.setPackage(mContext.getPackageName());
804 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
805 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
806 mContext,
807 0,
808 callBackIntent,
809 PendingIntent.FLAG_CANCEL_CURRENT |
810 PendingIntent.FLAG_ONE_SHOT |
811 PendingIntent.FLAG_IMMUTABLE);
812 // After unlocking the challenge, it will disable quiet mode and run the original
813 // intentSender
814 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100815 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
816 mContext.startActivity(unlockIntent);
817 } finally {
818 Binder.restoreCallingIdentity(identity);
819 }
820 return false;
821 }
822
823 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100824 public void setUserEnabled(int userId) {
825 checkManageUsersPermission("enable user");
826 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700827 UserInfo info;
828 synchronized (mUsersLock) {
829 info = getUserInfoLU(userId);
830 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100831 if (info != null && !info.isEnabled()) {
832 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800833 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100834 }
835 }
836 }
837
838 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700839 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700840 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000841 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700842 return userWithName(getUserInfoLU(userId));
843 }
844 }
845
846 /**
847 * Returns a UserInfo object with the name filled in, for Owner, or the original
848 * if the name is already set.
849 */
850 private UserInfo userWithName(UserInfo orig) {
851 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
852 UserInfo withName = new UserInfo(orig);
853 withName.name = getOwnerName();
854 return withName;
855 } else {
856 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000857 }
858 }
859
860 @Override
861 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000862 int callingUserId = UserHandle.getCallingUserId();
863 if (callingUserId != userId && !hasManageUsersPermission()) {
864 synchronized (mPackagesLock) {
865 if (!isSameProfileGroupLP(callingUserId, userId)) {
866 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000867 "You need MANAGE_USERS permission to: check if specified user a " +
868 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000869 }
870 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000871 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700872 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700873 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000874 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700875 }
876 }
877
Amith Yamasani71e6c692013-03-24 17:39:28 -0700878 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700879 public boolean isDemoUser(int userId) {
880 int callingUserId = UserHandle.getCallingUserId();
881 if (callingUserId != userId && !hasManageUsersPermission()) {
882 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
883 + " is a demo user");
884 }
885 synchronized (mUsersLock) {
886 UserInfo userInfo = getUserInfoLU(userId);
887 return userInfo != null && userInfo.isDemo();
888 }
889 }
890
891 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700892 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700893 synchronized (mUsersLock) {
894 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700895 }
896 }
897
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700898 @Override
899 public boolean canHaveRestrictedProfile(int userId) {
900 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700901 synchronized (mUsersLock) {
902 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700903 if (userInfo == null || !userInfo.canHaveProfile()) {
904 return false;
905 }
906 if (!userInfo.isAdmin()) {
907 return false;
908 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800909 // restricted profile can be created if there is no DO set and the admin user has no PO;
910 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700911 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700912 }
913
Amith Yamasani195263742012-08-21 15:40:12 -0700914 /*
915 * Should be locked on mUsers before calling this.
916 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700917 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800918 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700919 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800920 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700921 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
922 return null;
923 }
Amith Yamasani12747872015-12-07 14:19:49 -0800924 return userData != null ? userData.info : null;
925 }
926
927 private UserData getUserDataLU(int userId) {
928 final UserData userData = mUsers.get(userId);
929 // If it is partial and not in the process of being removed, return as unknown user.
930 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
931 return null;
932 }
933 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700934 }
935
Fyodor Kupolov82402752015-10-28 14:54:51 -0700936 /**
937 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
938 * <p>No permissions checking or any addition checks are made</p>
939 */
940 private UserInfo getUserInfoNoChecks(int userId) {
941 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800942 final UserData userData = mUsers.get(userId);
943 return userData != null ? userData.info : null;
944 }
945 }
946
947 /**
948 * Obtains {@link #mUsersLock} and return UserData from mUsers.
949 * <p>No permissions checking or any addition checks are made</p>
950 */
951 private UserData getUserDataNoChecks(int userId) {
952 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700953 return mUsers.get(userId);
954 }
955 }
956
Amith Yamasani236b2b52015-08-18 14:32:14 -0700957 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700958 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700959 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700960 }
961
Amith Yamasani258848d2012-08-10 17:06:33 -0700962 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700963 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700964 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700965 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700966 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800967 UserData userData = getUserDataNoChecks(userId);
968 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700969 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
970 return;
971 }
Amith Yamasani12747872015-12-07 14:19:49 -0800972 if (name != null && !name.equals(userData.info.name)) {
973 userData.info.name = name;
974 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700975 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700976 }
977 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700978 if (changed) {
979 sendUserInfoChangedBroadcast(userId);
980 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700981 }
982
Amith Yamasani258848d2012-08-10 17:06:33 -0700983 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700984 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700985 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100986 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
987 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
988 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700989 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100990 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700991 }
992
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100993
994
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700995 private void sendUserInfoChangedBroadcast(int userId) {
996 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
997 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
998 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700999 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001000 }
1001
Amith Yamasani258848d2012-08-10 17:06:33 -07001002 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001003 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001004 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001005 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001006 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1007 if (targetUserInfo == null || targetUserInfo.partial) {
1008 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001009 return null;
1010 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001011
1012 final int callingUserId = UserHandle.getCallingUserId();
1013 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1014 final int targetGroupId = targetUserInfo.profileGroupId;
1015 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1016 && callingGroupId == targetGroupId);
1017 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001018 checkManageUsersPermission("get the icon of a user who is not related");
1019 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001020
1021 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001022 return null;
1023 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001024 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001025 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001026
1027 try {
1028 return ParcelFileDescriptor.open(
1029 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1030 } catch (FileNotFoundException e) {
1031 Log.e(LOG_TAG, "Couldn't find icon file", e);
1032 }
1033 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001034 }
1035
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001036 public void makeInitialized(int userId) {
1037 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001038 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001039 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001040 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001041 userData = mUsers.get(userId);
1042 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001043 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001044 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001045 }
Amith Yamasani12747872015-12-07 14:19:49 -08001046 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1047 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001048 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001049 }
1050 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001051 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001052 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001053 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001054 }
1055
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001056 /**
1057 * If default guest restrictions haven't been initialized yet, add the basic
1058 * restrictions.
1059 */
1060 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001061 synchronized (mGuestRestrictions) {
1062 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001063 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001064 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001065 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1066 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1067 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001068 }
1069 }
1070
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001071 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301072 public Bundle getDefaultGuestRestrictions() {
1073 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001074 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301075 return new Bundle(mGuestRestrictions);
1076 }
1077 }
1078
1079 @Override
1080 public void setDefaultGuestRestrictions(Bundle restrictions) {
1081 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001082 synchronized (mGuestRestrictions) {
1083 mGuestRestrictions.clear();
1084 mGuestRestrictions.putAll(restrictions);
1085 }
1086 synchronized (mPackagesLock) {
1087 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301088 }
1089 }
1090
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001091 /**
1092 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1093 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001094 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001095 @Nullable Bundle global) {
1096 Preconditions.checkNotNull(local);
1097 boolean globalChanged = false;
1098 boolean localChanged;
1099 synchronized (mRestrictionsLock) {
1100 if (global != null) {
1101 // Update global.
1102 globalChanged = !UserRestrictionsUtils.areEqual(
1103 mDevicePolicyGlobalUserRestrictions, global);
1104 if (globalChanged) {
1105 mDevicePolicyGlobalUserRestrictions = global;
1106 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001107 // Remember the global restriction owner userId to be able to make a distinction
1108 // in getUserRestrictionSource on who set local policies.
1109 mGlobalRestrictionOwnerUserId = userId;
1110 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001111 if (mGlobalRestrictionOwnerUserId == userId) {
1112 // When profile owner sets restrictions it passes null global bundle and we
1113 // reset global restriction owner userId.
1114 // This means this user used to have DO, but now the DO is gone and the user
1115 // instead has PO.
1116 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1117 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001118 }
1119 {
1120 // Update local.
1121 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1122 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1123 if (localChanged) {
1124 mDevicePolicyLocalUserRestrictions.put(userId, local);
1125 }
1126 }
1127 }
1128 if (DBG) {
1129 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1130 + " global=" + global + (globalChanged ? " (changed)" : "")
1131 + " local=" + local + (localChanged ? " (changed)" : "")
1132 );
1133 }
1134 // Don't call them within the mRestrictionsLock.
1135 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001136 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001137 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001138 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001139 if (globalChanged) {
1140 writeUserListLP();
1141 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001142 }
1143
1144 synchronized (mRestrictionsLock) {
1145 if (globalChanged) {
1146 applyUserRestrictionsForAllUsersLR();
1147 } else if (localChanged) {
1148 applyUserRestrictionsLR(userId);
1149 }
1150 }
1151 }
1152
Makoto Onuki068c54a2015-10-13 14:34:03 -07001153 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001154 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001155 final Bundle baseRestrictions =
1156 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1157 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1158 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001159
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001160 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1161 // Common case first.
1162 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001163 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001164 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1165 UserRestrictionsUtils.merge(effective, global);
1166 UserRestrictionsUtils.merge(effective, local);
1167
Makoto Onuki068c54a2015-10-13 14:34:03 -07001168 return effective;
1169 }
1170
1171 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001172 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001173 if (DBG) {
1174 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1175 }
1176 mCachedEffectiveUserRestrictions.remove(userId);
1177 }
1178
1179 private Bundle getEffectiveUserRestrictions(int userId) {
1180 synchronized (mRestrictionsLock) {
1181 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1182 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001183 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001184 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1185 }
1186 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001187 }
1188 }
1189
Makoto Onuki068c54a2015-10-13 14:34:03 -07001190 /** @return a specific user restriction that's in effect currently. */
1191 @Override
1192 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001193 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1194 return false;
1195 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001196 Bundle restrictions = getEffectiveUserRestrictions(userId);
1197 return restrictions != null && restrictions.getBoolean(restrictionKey);
1198 }
1199
1200 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001201 * @hide
1202 *
1203 * Returns who set a user restriction on a user.
1204 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1205 * @param restrictionKey the string key representing the restriction
1206 * @param userId the id of the user for whom to retrieve the restrictions.
1207 * @return The source of user restriction. Any combination of
1208 * {@link UserManager#RESTRICTION_NOT_SET},
1209 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1210 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1211 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1212 */
1213 @Override
1214 public int getUserRestrictionSource(String restrictionKey, int userId) {
1215 checkManageUsersPermission("getUserRestrictionSource");
1216 int result = UserManager.RESTRICTION_NOT_SET;
1217
1218 // Shortcut for the most common case
1219 if (!hasUserRestriction(restrictionKey, userId)) {
1220 return result;
1221 }
1222
1223 if (hasBaseUserRestriction(restrictionKey, userId)) {
1224 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1225 }
1226
1227 synchronized(mRestrictionsLock) {
1228 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1229 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1230 && localRestrictions.getBoolean(restrictionKey)) {
1231 // Local restrictions may have been set by device owner the userId of which is
1232 // stored in mGlobalRestrictionOwnerUserId.
1233 if (mGlobalRestrictionOwnerUserId == userId) {
1234 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1235 } else {
1236 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1237 }
1238 }
1239 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1240 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1241 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1242 }
1243 }
1244
1245 return result;
1246 }
1247
1248 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001249 * @return UserRestrictions that are in effect currently. This always returns a new
1250 * {@link Bundle}.
1251 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001252 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001253 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001254 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001255 }
1256
1257 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001258 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1259 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001260 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1261 return false;
1262 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001263 synchronized (mRestrictionsLock) {
1264 Bundle bundle = mBaseUserRestrictions.get(userId);
1265 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1266 }
1267 }
1268
1269 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001270 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001271 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001272 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1273 return;
1274 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001275 synchronized (mRestrictionsLock) {
1276 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1277 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001278 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1279 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001280 newRestrictions.putBoolean(key, value);
1281
Fyodor Kupolov82402752015-10-28 14:54:51 -07001282 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001283 }
1284 }
1285
Makoto Onuki068c54a2015-10-13 14:34:03 -07001286 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001287 * Optionally updating user restrictions, calculate the effective user restrictions and also
1288 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001289 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001290 * @param newRestrictions User restrictions to set.
1291 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001292 * @param userId target user ID.
1293 */
1294 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001295 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001296 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001297
1298 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1299 mAppliedUserRestrictions.get(userId));
1300
1301 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001302 if (newRestrictions != null) {
1303 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001304 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1305
1306 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001307 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1308 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001309
1310 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1311 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001312 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001313 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001314 }
1315
Fyodor Kupolov82402752015-10-28 14:54:51 -07001316 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001317
Makoto Onuki759a7632015-10-28 16:43:10 -07001318 mCachedEffectiveUserRestrictions.put(userId, effective);
1319
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001320 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001321 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001322 debug("Applying user restrictions: userId=" + userId
1323 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001324 }
1325
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001326 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001327 mHandler.post(new Runnable() {
1328 @Override
1329 public void run() {
1330 try {
1331 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1332 } catch (RemoteException e) {
1333 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1334 }
1335 }
1336 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001337 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001338
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001339 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001340
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001341 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001342 }
1343
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001344 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001345 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001346 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1347 // actually, but we still need some kind of synchronization otherwise we might end up
1348 // calling listeners out-of-order, thus "LR".
1349
1350 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1351 return;
1352 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001353
1354 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1355 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1356
1357 mHandler.post(new Runnable() {
1358 @Override
1359 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001360 UserRestrictionsUtils.applyUserRestrictions(
1361 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001362
Makoto Onukid45a4a22015-11-02 17:17:38 -08001363 final UserRestrictionsListener[] listeners;
1364 synchronized (mUserRestrictionsListeners) {
1365 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1366 mUserRestrictionsListeners.toArray(listeners);
1367 }
1368 for (int i = 0; i < listeners.length; i++) {
1369 listeners[i].onUserRestrictionsChanged(userId,
1370 newRestrictionsFinal, prevRestrictionsFinal);
1371 }
1372 }
1373 });
1374 }
1375
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001376 // Package private for the inner class.
1377 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001378 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001379 }
1380
1381 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001382 // Package private for the inner class.
1383 void applyUserRestrictionsForAllUsersLR() {
1384 if (DBG) {
1385 debug("applyUserRestrictionsForAllUsersLR");
1386 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001387 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001388 mCachedEffectiveUserRestrictions.clear();
1389
Makoto Onuki068c54a2015-10-13 14:34:03 -07001390 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1391 // it on a handler.
1392 final Runnable r = new Runnable() {
1393 @Override
1394 public void run() {
1395 // Then get the list of running users.
1396 final int[] runningUsers;
1397 try {
1398 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1399 } catch (RemoteException e) {
1400 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1401 return;
1402 }
1403 // Then re-calculate the effective restrictions and apply, only for running users.
1404 // It's okay if a new user has started after the getRunningUserIds() call,
1405 // because we'll do the same thing (re-calculate the restrictions and apply)
1406 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001407 synchronized (mRestrictionsLock) {
1408 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001409 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001410 }
1411 }
1412 }
1413 };
1414 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001415 }
1416
Amith Yamasani258848d2012-08-10 17:06:33 -07001417 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001418 * Check if we've hit the limit of how many users can be created.
1419 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001420 private boolean isUserLimitReached() {
1421 int count;
1422 synchronized (mUsersLock) {
1423 count = getAliveUsersExcludingGuestsCountLU();
1424 }
1425 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001426 }
1427
1428 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001429 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001430 checkManageUsersPermission("check if more managed profiles can be added.");
1431 if (ActivityManager.isLowRamDeviceStatic()) {
1432 return false;
1433 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001434 if (!mContext.getPackageManager().hasSystemFeature(
1435 PackageManager.FEATURE_MANAGED_USERS)) {
1436 return false;
1437 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001438 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001439 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1440 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1441 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001442 return false;
1443 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001444 synchronized(mUsersLock) {
1445 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001446 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001447 return false;
1448 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001449 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1450 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001451 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001452 return usersCountAfterRemoving == 1
1453 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001454 }
1455 }
1456
Fyodor Kupolov82402752015-10-28 14:54:51 -07001457 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001458 int aliveUserCount = 0;
1459 final int totalUserCount = mUsers.size();
1460 // Skip over users being removed
1461 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001462 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001463 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001464 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001465 aliveUserCount++;
1466 }
1467 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001468 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001469 }
1470
1471 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001472 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001473 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1474 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1475 * permissions can make certain calls to the UserManager.
1476 *
1477 * @param message used as message if SecurityException is thrown
1478 * @throws SecurityException if the caller does not have enough privilege.
1479 */
1480 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1481 final int uid = Binder.getCallingUid();
1482 if (uid != Process.SYSTEM_UID && uid != 0
1483 && ActivityManager.checkComponentPermission(
1484 Manifest.permission.MANAGE_USERS,
1485 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1486 && ActivityManager.checkComponentPermission(
1487 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1488 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1489 throw new SecurityException(
1490 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1491 + message);
1492 }
1493 }
1494
1495 /**
1496 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001497 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001498 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001499 *
1500 * @param message used as message if SecurityException is thrown
1501 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001502 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001503 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001504 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001505 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001506 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1507 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001508 }
1509
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001510 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001511 * Enforces that only the system UID or root's UID or apps that have the
1512 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1513 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1514 * can make certain calls to the UserManager.
1515 *
1516 * @param message used as message if SecurityException is thrown
1517 * @throws SecurityException if the caller is not system or root
1518 * @see #hasManageOrCreateUsersPermission()
1519 */
1520 private static final void checkManageOrCreateUsersPermission(String message) {
1521 if (!hasManageOrCreateUsersPermission()) {
1522 throw new SecurityException(
1523 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1524 }
1525 }
1526
1527 /**
1528 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1529 * to create user/profiles other than what is allowed for
1530 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1531 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1532 */
1533 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1534 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1535 if (!hasManageOrCreateUsersPermission()) {
1536 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1537 + "permission to create an user with flags: " + creationFlags);
1538 }
1539 } else if (!hasManageUsersPermission()) {
1540 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1541 + " with flags: " + creationFlags);
1542 }
1543 }
1544
1545 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001546 * @return whether the calling UID is system UID or root's UID or the calling app has the
1547 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1548 */
1549 private static final boolean hasManageUsersPermission() {
1550 final int callingUid = Binder.getCallingUid();
1551 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1552 || callingUid == Process.ROOT_UID
1553 || ActivityManager.checkComponentPermission(
1554 android.Manifest.permission.MANAGE_USERS,
1555 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1556 }
1557
1558 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001559 * @return whether the calling UID is system UID or root's UID or the calling app has the
1560 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1561 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1562 */
1563 private static final boolean hasManageOrCreateUsersPermission() {
1564 final int callingUid = Binder.getCallingUid();
1565 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1566 || callingUid == Process.ROOT_UID
1567 || ActivityManager.checkComponentPermission(
1568 android.Manifest.permission.MANAGE_USERS,
1569 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1570 || ActivityManager.checkComponentPermission(
1571 android.Manifest.permission.CREATE_USERS,
1572 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1573 }
1574
1575 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001576 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1577 * UserManager.
1578 *
1579 * @param message used as message if SecurityException is thrown
1580 * @throws SecurityException if the caller is not system or root
1581 */
1582 private static void checkSystemOrRoot(String message) {
1583 final int uid = Binder.getCallingUid();
1584 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1585 throw new SecurityException("Only system may: " + message);
1586 }
1587 }
1588
Fyodor Kupolov82402752015-10-28 14:54:51 -07001589 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001590 try {
1591 File dir = new File(mUsersDir, Integer.toString(info.id));
1592 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001593 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001594 if (!dir.exists()) {
1595 dir.mkdir();
1596 FileUtils.setPermissions(
1597 dir.getPath(),
1598 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1599 -1, -1);
1600 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001601 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001602 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001603 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001604 info.iconPath = file.getAbsolutePath();
1605 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001606 try {
1607 os.close();
1608 } catch (IOException ioe) {
1609 // What the ... !
1610 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001611 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001612 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001613 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001614 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001615 }
1616
Amith Yamasani0b285492011-04-14 17:35:23 -07001617 /**
1618 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1619 * cache it elsewhere.
1620 * @return the array of user ids.
1621 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001622 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001623 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001624 return mUserIds;
1625 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001626 }
1627
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001628 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001629 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001630 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001631 return;
1632 }
1633 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001634 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001635 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001636 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001637 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001638 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001639 int type;
1640 while ((type = parser.next()) != XmlPullParser.START_TAG
1641 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001642 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001643 }
1644
1645 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001646 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001647 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001648 return;
1649 }
1650
Amith Yamasani2a003292012-08-14 18:25:45 -07001651 mNextSerialNumber = -1;
1652 if (parser.getName().equals(TAG_USERS)) {
1653 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1654 if (lastSerialNumber != null) {
1655 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1656 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001657 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1658 if (versionNumber != null) {
1659 mUserVersion = Integer.parseInt(versionNumber);
1660 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001661 }
1662
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001663 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1664
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001665 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301666 if (type == XmlPullParser.START_TAG) {
1667 final String name = parser.getName();
1668 if (name.equals(TAG_USER)) {
1669 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001670
Amith Yamasani12747872015-12-07 14:19:49 -08001671 UserData userData = readUserLP(Integer.parseInt(id));
1672
1673 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001674 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001675 mUsers.put(userData.info.id, userData);
1676 if (mNextSerialNumber < 0
1677 || mNextSerialNumber <= userData.info.id) {
1678 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001679 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301680 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001681 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301682 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001683 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1684 && type != XmlPullParser.END_TAG) {
1685 if (type == XmlPullParser.START_TAG) {
1686 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001687 synchronized (mGuestRestrictions) {
1688 UserRestrictionsUtils
1689 .readRestrictions(parser, mGuestRestrictions);
1690 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1692 ) {
1693 UserRestrictionsUtils.readRestrictions(parser,
1694 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001695 }
1696 break;
1697 }
1698 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001699 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1700 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1701 if (ownerUserId != null) {
1702 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1703 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001704 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001705 }
1706 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707 synchronized (mRestrictionsLock) {
1708 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1709 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001710 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001711 upgradeIfNecessaryLP();
1712 } catch (IOException | XmlPullParserException e) {
1713 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001714 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001715 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001716 }
1717 }
1718
Amith Yamasani6f34b412012-10-22 18:19:27 -07001719 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001720 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001721 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001722 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001724 int userVersion = mUserVersion;
1725 if (userVersion < 1) {
1726 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001727 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1728 if ("Primary".equals(userData.info.name)) {
1729 userData.info.name =
1730 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1731 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001732 }
1733 userVersion = 1;
1734 }
1735
Amith Yamasanibc9625052012-11-15 14:39:18 -08001736 if (userVersion < 2) {
1737 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001738 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1739 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1740 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1741 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001742 }
1743 userVersion = 2;
1744 }
1745
Amith Yamasani350962c2013-08-06 11:18:53 -07001746
Amith Yamasani5e486f52013-08-07 11:06:44 -07001747 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001748 userVersion = 4;
1749 }
1750
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001751 if (userVersion < 5) {
1752 initDefaultGuestRestrictions();
1753 userVersion = 5;
1754 }
1755
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001756 if (userVersion < 6) {
1757 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001758 synchronized (mUsersLock) {
1759 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001760 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001761 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001762 if (!splitSystemUser && userData.info.isRestricted()
1763 && (userData.info.restrictedProfileParentId
1764 == UserInfo.NO_PROFILE_GROUP_ID)) {
1765 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1766 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001767 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001768 }
1769 }
1770 userVersion = 6;
1771 }
1772
Amith Yamasani6f34b412012-10-22 18:19:27 -07001773 if (userVersion < USER_VERSION) {
1774 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1775 + USER_VERSION);
1776 } else {
1777 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001778
1779 if (originalVersion < mUserVersion) {
1780 writeUserListLP();
1781 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001782 }
1783 }
1784
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001785 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001786 int flags = UserInfo.FLAG_INITIALIZED;
1787 // In split system user mode, the admin and primary flags are assigned to the first human
1788 // user.
1789 if (!UserManager.isSplitSystemUser()) {
1790 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1791 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001792 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001793 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001794 UserData userData = new UserData();
1795 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001796 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001797 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001798 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001799 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001800 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001801
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001802 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001803 try {
1804 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1805 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1806 for (String userRestriction : defaultFirstUserRestrictions) {
1807 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1808 restrictions.putBoolean(userRestriction, true);
1809 }
1810 }
1811 } catch (Resources.NotFoundException e) {
1812 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1813 }
1814
Makoto Onuki068c54a2015-10-13 14:34:03 -07001815 synchronized (mRestrictionsLock) {
1816 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1817 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001818
Fyodor Kupolov82402752015-10-28 14:54:51 -07001819 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001820 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001821
Amith Yamasani12747872015-12-07 14:19:49 -08001822 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001823 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001824 }
1825
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001826 private String getOwnerName() {
1827 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1828 }
1829
Amith Yamasani12747872015-12-07 14:19:49 -08001830 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001831 if (DBG) {
1832 debug("scheduleWriteUser");
1833 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001834 // No need to wrap it within a lock -- worst case, we'll just post the same message
1835 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001836 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1837 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001838 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1839 }
1840 }
1841
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001842 /*
1843 * Writes the user file in this format:
1844 *
1845 * <user flags="20039023" id="0">
1846 * <name>Primary</name>
1847 * </user>
1848 */
Amith Yamasani12747872015-12-07 14:19:49 -08001849 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001850 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001851 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001852 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001853 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001854 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001855 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001856 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001857 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1858
1859 // XmlSerializer serializer = XmlUtils.serializerInstance();
1860 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001861 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001862 serializer.startDocument(null, true);
1863 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1864
Amith Yamasani12747872015-12-07 14:19:49 -08001865 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001866 serializer.startTag(null, TAG_USER);
1867 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001868 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001869 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001870 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1871 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1872 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001873 if (userInfo.lastLoggedInFingerprint != null) {
1874 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1875 userInfo.lastLoggedInFingerprint);
1876 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001877 if (userInfo.iconPath != null) {
1878 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1879 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001880 if (userInfo.partial) {
1881 serializer.attribute(null, ATTR_PARTIAL, "true");
1882 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001883 if (userInfo.guestToRemove) {
1884 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1885 }
Kenny Guy2a764942014-04-02 13:29:20 +01001886 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1887 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1888 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001889 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001890 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1891 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1892 Integer.toString(userInfo.restrictedProfileParentId));
1893 }
Amith Yamasani12747872015-12-07 14:19:49 -08001894 // Write seed data
1895 if (userData.persistSeedData) {
1896 if (userData.seedAccountName != null) {
1897 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1898 }
1899 if (userData.seedAccountType != null) {
1900 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1901 }
1902 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001903 if (userInfo.name != null) {
1904 serializer.startTag(null, TAG_NAME);
1905 serializer.text(userInfo.name);
1906 serializer.endTag(null, TAG_NAME);
1907 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001908 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001909 UserRestrictionsUtils.writeRestrictions(serializer,
1910 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1911 UserRestrictionsUtils.writeRestrictions(serializer,
1912 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1913 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001914 }
Amith Yamasani12747872015-12-07 14:19:49 -08001915
1916 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001917 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001918 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001919 serializer.endTag(null, TAG_ACCOUNT);
1920 }
1921
Amith Yamasani12747872015-12-07 14:19:49 -08001922 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1923 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1924 userData.seedAccountOptions.saveToXml(serializer);
1925 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1926 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001927 serializer.endTag(null, TAG_USER);
1928
1929 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001930 userFile.finishWrite(fos);
1931 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001932 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001933 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001934 }
1935 }
1936
1937 /*
1938 * Writes the user list file in this format:
1939 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001940 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001941 * <user id="0"></user>
1942 * <user id="2"></user>
1943 * </users>
1944 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001945 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001946 if (DBG) {
1947 debug("writeUserList");
1948 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001949 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001950 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001951 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001952 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001953 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1954
1955 // XmlSerializer serializer = XmlUtils.serializerInstance();
1956 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001957 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001958 serializer.startDocument(null, true);
1959 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1960
1961 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001962 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001963 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001964
Adam Lesinskieddeb492014-09-08 17:50:03 -07001965 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001966 synchronized (mGuestRestrictions) {
1967 UserRestrictionsUtils
1968 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1969 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301970 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001971 synchronized (mRestrictionsLock) {
1972 UserRestrictionsUtils.writeRestrictions(serializer,
1973 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1974 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001975 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1976 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1977 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001978 int[] userIdsToWrite;
1979 synchronized (mUsersLock) {
1980 userIdsToWrite = new int[mUsers.size()];
1981 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001982 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001983 userIdsToWrite[i] = user.id;
1984 }
1985 }
1986 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001987 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001988 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001989 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001990 }
1991
1992 serializer.endTag(null, TAG_USERS);
1993
1994 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001995 userListFile.finishWrite(fos);
1996 } catch (Exception e) {
1997 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001998 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001999 }
2000 }
2001
Amith Yamasani12747872015-12-07 14:19:49 -08002002 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002003 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002004 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002005 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002006 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002007 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002008 long creationTime = 0L;
2009 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002010 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002011 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002012 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002013 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002014 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002015 boolean persistSeedData = false;
2016 String seedAccountName = null;
2017 String seedAccountType = null;
2018 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002019 Bundle baseRestrictions = new Bundle();
2020 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002021
2022 FileInputStream fis = null;
2023 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002024 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002025 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002026 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002027 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002028 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002029 int type;
2030 while ((type = parser.next()) != XmlPullParser.START_TAG
2031 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002032 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002033 }
2034
2035 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002036 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002037 return null;
2038 }
2039
2040 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002041 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2042 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002043 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002044 return null;
2045 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002046 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2047 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002048 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002049 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2050 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002051 lastLoggedInFingerprint = parser.getAttributeValue(null,
2052 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002053 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2054 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002055 restrictedProfileParentId = readIntAttribute(parser,
2056 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002057 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2058 if ("true".equals(valueString)) {
2059 partial = true;
2060 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002061 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2062 if ("true".equals(valueString)) {
2063 guestToRemove = true;
2064 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002065
Amith Yamasani12747872015-12-07 14:19:49 -08002066 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2067 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2068 if (seedAccountName != null || seedAccountType != null) {
2069 persistSeedData = true;
2070 }
2071
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002072 int outerDepth = parser.getDepth();
2073 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2074 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2075 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2076 continue;
2077 }
2078 String tag = parser.getName();
2079 if (TAG_NAME.equals(tag)) {
2080 type = parser.next();
2081 if (type == XmlPullParser.TEXT) {
2082 name = parser.getText();
2083 }
2084 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002085 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2086 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2087 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002088 } else if (TAG_ACCOUNT.equals(tag)) {
2089 type = parser.next();
2090 if (type == XmlPullParser.TEXT) {
2091 account = parser.getText();
2092 }
Amith Yamasani12747872015-12-07 14:19:49 -08002093 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2094 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2095 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002096 }
2097 }
2098 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002099
Amith Yamasani12747872015-12-07 14:19:49 -08002100 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002101 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002102 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002103 userInfo.creationTime = creationTime;
2104 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002105 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002106 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002107 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002108 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002109 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002110
2111 // Create the UserData object that's internal to this class
2112 UserData userData = new UserData();
2113 userData.info = userInfo;
2114 userData.account = account;
2115 userData.seedAccountName = seedAccountName;
2116 userData.seedAccountType = seedAccountType;
2117 userData.persistSeedData = persistSeedData;
2118 userData.seedAccountOptions = seedAccountOptions;
2119
Makoto Onuki068c54a2015-10-13 14:34:03 -07002120 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002121 mBaseUserRestrictions.put(id, baseRestrictions);
2122 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002123 }
Amith Yamasani12747872015-12-07 14:19:49 -08002124 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002125 } catch (IOException ioe) {
2126 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002127 } finally {
2128 if (fis != null) {
2129 try {
2130 fis.close();
2131 } catch (IOException e) {
2132 }
2133 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002134 }
2135 return null;
2136 }
2137
Amith Yamasani920ace02012-09-20 22:15:37 -07002138 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2139 String valueString = parser.getAttributeValue(null, attr);
2140 if (valueString == null) return defaultValue;
2141 try {
2142 return Integer.parseInt(valueString);
2143 } catch (NumberFormatException nfe) {
2144 return defaultValue;
2145 }
2146 }
2147
2148 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2149 String valueString = parser.getAttributeValue(null, attr);
2150 if (valueString == null) return defaultValue;
2151 try {
2152 return Long.parseLong(valueString);
2153 } catch (NumberFormatException nfe) {
2154 return defaultValue;
2155 }
2156 }
2157
Amith Yamasanib82add22013-07-09 11:24:44 -07002158 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002159 * Removes the app restrictions file for a specific package and user id, if it exists.
2160 */
2161 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2162 synchronized (mPackagesLock) {
2163 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002164 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002165 if (resFile.exists()) {
2166 resFile.delete();
2167 }
2168 }
2169 }
2170
Kenny Guya52dc3e2014-02-11 15:33:14 +00002171 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002172 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002173 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002174 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002175 }
2176
Amith Yamasani258848d2012-08-10 17:06:33 -07002177 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002178 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002179 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002180 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002181 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002182
Jessica Hummelbe81c802014-04-22 15:49:22 +01002183 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002184 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002185 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2186 return null;
2187 }
phweisse9c44062016-02-10 12:57:38 +01002188 return createUserInternalUnchecked(name, flags, parentId);
2189 }
2190
2191 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002192 if (ActivityManager.isLowRamDeviceStatic()) {
2193 return null;
2194 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002195 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002196 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002197 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002198 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002199 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002200 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002201 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002202 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002203 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002204 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002205 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002206 if (parentId != UserHandle.USER_NULL) {
2207 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002208 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002209 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002210 if (parent == null) return null;
2211 }
2212 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2213 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2214 return null;
2215 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002216 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2217 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002218 // been reached, cannot add a user.
2219 return null;
2220 }
2221 // If we're adding a guest and there already exists one, bail.
2222 if (isGuest && findCurrentGuestUser() != null) {
2223 return null;
2224 }
2225 // In legacy mode, restricted profile's parent can only be the owner user
2226 if (isRestricted && !UserManager.isSplitSystemUser()
2227 && (parentId != UserHandle.USER_SYSTEM)) {
2228 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2229 return null;
2230 }
2231 if (isRestricted && UserManager.isSplitSystemUser()) {
2232 if (parent == null) {
2233 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2234 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002235 return null;
2236 }
Amith Yamasani12747872015-12-07 14:19:49 -08002237 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002238 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2239 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002240 return null;
2241 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002242 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002243 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2244 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002245 Log.e(LOG_TAG,
2246 "Ephemeral users are supported on split-system-user systems only.");
2247 return null;
2248 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002249 // In split system user mode, we assign the first human user the primary flag.
2250 // And if there is no device owner, we also assign the admin flag to primary user.
2251 if (UserManager.isSplitSystemUser()
2252 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2253 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002254 synchronized (mUsersLock) {
2255 if (!mIsDeviceManaged) {
2256 flags |= UserInfo.FLAG_ADMIN;
2257 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002258 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002259 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002260
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002261 userId = getNextAvailableId();
2262 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002263 boolean ephemeralGuests = Resources.getSystem()
2264 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002265
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002266 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002267 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2268 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2269 || (parent != null && parent.info.isEphemeral())) {
2270 flags |= UserInfo.FLAG_EPHEMERAL;
2271 }
2272
2273 userInfo = new UserInfo(userId, name, null, flags);
2274 userInfo.serialNumber = mNextSerialNumber++;
2275 long now = System.currentTimeMillis();
2276 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2277 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002278 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002279 userData = new UserData();
2280 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002281 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002282 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002283 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002284 writeUserListLP();
2285 if (parent != null) {
2286 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002287 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2288 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002289 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002290 }
Amith Yamasani12747872015-12-07 14:19:49 -08002291 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002292 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002293 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2294 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002295 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002296 }
Amith Yamasani12747872015-12-07 14:19:49 -08002297 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002298 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002299 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002300 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002301 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002302 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002303 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002304 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002305 mPm.createNewUser(userId);
2306 userInfo.partial = false;
2307 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002308 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002309 }
2310 updateUserIds();
2311 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002312 if (isGuest) {
2313 synchronized (mGuestRestrictions) {
2314 restrictions.putAll(mGuestRestrictions);
2315 }
2316 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002317 synchronized (mRestrictionsLock) {
2318 mBaseUserRestrictions.append(userId, restrictions);
2319 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002320 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002321 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2322 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2323 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2324 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002325 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002326 } finally {
2327 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002328 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002329 return userInfo;
2330 }
2331
Amith Yamasani0b285492011-04-14 17:35:23 -07002332 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002333 * @hide
2334 */
Amith Yamasani12747872015-12-07 14:19:49 -08002335 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002336 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002337 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002338 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2339 if (user == null) {
2340 return null;
2341 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002342 long identity = Binder.clearCallingIdentity();
2343 try {
2344 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2345 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2346 // the putIntForUser() will fail.
2347 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2348 android.provider.Settings.Secure.LOCATION_MODE,
2349 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2350 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2351 } finally {
2352 Binder.restoreCallingIdentity(identity);
2353 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002354 return user;
2355 }
2356
2357 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002358 * Find the current guest user. If the Guest user is partial,
2359 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002360 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002361 private UserInfo findCurrentGuestUser() {
2362 synchronized (mUsersLock) {
2363 final int size = mUsers.size();
2364 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002365 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002366 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2367 return user;
2368 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002369 }
2370 }
2371 return null;
2372 }
2373
2374 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002375 * Mark this guest user for deletion to allow us to create another guest
2376 * and switch to that user before actually removing this guest.
2377 * @param userHandle the userid of the current guest
2378 * @return whether the user could be marked for deletion
2379 */
Amith Yamasani12747872015-12-07 14:19:49 -08002380 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002381 public boolean markGuestForDeletion(int userHandle) {
2382 checkManageUsersPermission("Only the system can remove users");
2383 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2384 UserManager.DISALLOW_REMOVE_USER, false)) {
2385 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2386 return false;
2387 }
2388
2389 long ident = Binder.clearCallingIdentity();
2390 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002391 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002392 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002393 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002394 userData = mUsers.get(userHandle);
2395 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002396 return false;
2397 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002398 }
Amith Yamasani12747872015-12-07 14:19:49 -08002399 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002400 return false;
2401 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002402 // We set this to a guest user that is to be removed. This is a temporary state
2403 // where we are allowed to add new Guest users, even if this one is still not
2404 // removed. This user will still show up in getUserInfo() calls.
2405 // If we don't get around to removing this Guest user, it will be purged on next
2406 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002407 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002408 // Mark it as disabled, so that it isn't returned any more when
2409 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002410 userData.info.flags |= UserInfo.FLAG_DISABLED;
2411 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002412 }
2413 } finally {
2414 Binder.restoreCallingIdentity(ident);
2415 }
2416 return true;
2417 }
2418
2419 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002420 * Removes a user and all data directories created for that user. This method should be called
2421 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002422 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002423 */
Amith Yamasani12747872015-12-07 14:19:49 -08002424 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002425 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002426 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002427 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2428 UserManager.DISALLOW_REMOVE_USER, false)) {
2429 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2430 return false;
2431 }
2432
Kenny Guyee58b4f2014-05-23 15:19:53 +01002433 long ident = Binder.clearCallingIdentity();
2434 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002435 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002436 int currentUser = ActivityManager.getCurrentUser();
2437 if (currentUser == userHandle) {
2438 Log.w(LOG_TAG, "Current user cannot be removed");
2439 return false;
2440 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002441 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002442 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002443 userData = mUsers.get(userHandle);
2444 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002445 return false;
2446 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002447
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 // We remember deleted user IDs to prevent them from being
2449 // reused during the current boot; they can still be reused
2450 // after a reboot.
2451 mRemovingUserIds.put(userHandle, true);
2452 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002453
Kenny Guyee58b4f2014-05-23 15:19:53 +01002454 try {
2455 mAppOpsService.removeUser(userHandle);
2456 } catch (RemoteException e) {
2457 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2458 }
2459 // Set this to a partially created user, so that the user will be purged
2460 // on next startup, in case the runtime stops now before stopping and
2461 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002462 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002463 // Mark it as disabled, so that it isn't returned any more when
2464 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002465 userData.info.flags |= UserInfo.FLAG_DISABLED;
2466 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002467 }
2468
Amith Yamasani12747872015-12-07 14:19:49 -08002469 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2470 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002471 // Send broadcast to notify system that the user removed was a
2472 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002473 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002474 }
2475
2476 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2477 int res;
2478 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002479 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2480 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002481 @Override
2482 public void userStopped(int userId) {
2483 finishRemoveUser(userId);
2484 }
2485 @Override
2486 public void userStopAborted(int userId) {
2487 }
2488 });
2489 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002490 return false;
2491 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002492 return res == ActivityManager.USER_OP_SUCCESS;
2493 } finally {
2494 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002495 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002496 }
2497
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002498 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002499 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002500 // Let other services shutdown any activity and clean up their state before completely
2501 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002502 long ident = Binder.clearCallingIdentity();
2503 try {
2504 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2505 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002506 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2507 android.Manifest.permission.MANAGE_USERS,
2508
2509 new BroadcastReceiver() {
2510 @Override
2511 public void onReceive(Context context, Intent intent) {
2512 if (DBG) {
2513 Slog.i(LOG_TAG,
2514 "USER_REMOVED broadcast sent, cleaning up user data "
2515 + userHandle);
2516 }
2517 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002518 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002519 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002520 // Clean up any ActivityManager state
2521 LocalServices.getService(ActivityManagerInternal.class)
2522 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002523 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002524 }
2525 }.start();
2526 }
2527 },
2528
2529 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002530 } finally {
2531 Binder.restoreCallingIdentity(ident);
2532 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002533 }
2534
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002535 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002536 try {
2537 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2538 } catch (IllegalStateException e) {
2539 // This may be simply because the user was partially created.
2540 Slog.i(LOG_TAG,
2541 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2542 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002543
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002544 // Cleanup gatekeeper secure user id
2545 try {
2546 final IGateKeeperService gk = GateKeeper.getService();
2547 if (gk != null) {
2548 gk.clearSecureUserId(userHandle);
2549 }
2550 } catch (Exception ex) {
2551 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2552 }
2553
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002554 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002555 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002556
2557 // Clean up all data before removing metadata
2558 mPm.destroyUserData(userHandle,
2559 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2560
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002561 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002562 synchronized (mUsersLock) {
2563 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002564 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002565 }
2566 synchronized (mUserStates) {
2567 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002568 }
2569 synchronized (mRestrictionsLock) {
2570 mBaseUserRestrictions.remove(userHandle);
2571 mAppliedUserRestrictions.remove(userHandle);
2572 mCachedEffectiveUserRestrictions.remove(userHandle);
2573 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002574 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002575 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002576 synchronized (mPackagesLock) {
2577 writeUserListLP();
2578 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002579 // Remove user file
2580 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2581 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002582 updateUserIds();
Amith Yamasani61f57372012-08-31 12:12:28 -07002583 }
2584
Kenny Guyf8d3a232014-05-15 16:09:52 +01002585 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002586 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002587 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2588 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002589 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002590 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002591 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002592 }
2593
Amith Yamasani2a003292012-08-14 18:25:45 -07002594 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002595 public Bundle getApplicationRestrictions(String packageName) {
2596 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2597 }
2598
2599 @Override
2600 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002601 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002602 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002603 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002604 }
2605 synchronized (mPackagesLock) {
2606 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002607 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002608 }
2609 }
2610
2611 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002612 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002613 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002614 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002615 if (restrictions != null) {
2616 restrictions.setDefusable(true);
2617 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002618 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002619 if (restrictions == null || restrictions.isEmpty()) {
2620 cleanAppRestrictionsForPackage(packageName, userId);
2621 } else {
2622 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002623 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002624 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002625 }
Robin Lee66e5d962014-04-09 16:44:21 +01002626
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002627 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2628 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2629 changeIntent.setPackage(packageName);
2630 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2631 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002632 }
2633
2634 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002635 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002636 try {
2637 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002638 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002639 } catch (NameNotFoundException nnfe) {
2640 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002641 } finally {
2642 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002643 }
2644 }
2645
Fyodor Kupolov82402752015-10-28 14:54:51 -07002646 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002647 AtomicFile restrictionsFile =
2648 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2649 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002650 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002651 }
2652
2653 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002654 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002655 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002656 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002657 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002658 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002659 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002660
2661 FileInputStream fis = null;
2662 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002663 fis = restrictionsFile.openRead();
2664 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002665 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002666 XmlUtils.nextElement(parser);
2667 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002668 Slog.e(LOG_TAG, "Unable to read restrictions file "
2669 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002670 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002671 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002672 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2673 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002674 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002675 } catch (IOException|XmlPullParserException e) {
2676 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002677 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002678 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002679 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002680 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002681 }
2682
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002683 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2684 XmlPullParser parser) throws XmlPullParserException, IOException {
2685 int type = parser.getEventType();
2686 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2687 String key = parser.getAttributeValue(null, ATTR_KEY);
2688 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2689 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2690 if (multiple != null) {
2691 values.clear();
2692 int count = Integer.parseInt(multiple);
2693 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2694 if (type == XmlPullParser.START_TAG
2695 && parser.getName().equals(TAG_VALUE)) {
2696 values.add(parser.nextText().trim());
2697 count--;
2698 }
2699 }
2700 String [] valueStrings = new String[values.size()];
2701 values.toArray(valueStrings);
2702 restrictions.putStringArray(key, valueStrings);
2703 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2704 restrictions.putBundle(key, readBundleEntry(parser, values));
2705 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2706 final int outerDepth = parser.getDepth();
2707 ArrayList<Bundle> bundleList = new ArrayList<>();
2708 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2709 Bundle childBundle = readBundleEntry(parser, values);
2710 bundleList.add(childBundle);
2711 }
2712 restrictions.putParcelableArray(key,
2713 bundleList.toArray(new Bundle[bundleList.size()]));
2714 } else {
2715 String value = parser.nextText().trim();
2716 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2717 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2718 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2719 restrictions.putInt(key, Integer.parseInt(value));
2720 } else {
2721 restrictions.putString(key, value);
2722 }
2723 }
2724 }
2725 }
2726
2727 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2728 throws IOException, XmlPullParserException {
2729 Bundle childBundle = new Bundle();
2730 final int outerDepth = parser.getDepth();
2731 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2732 readEntry(childBundle, values, parser);
2733 }
2734 return childBundle;
2735 }
2736
Fyodor Kupolov82402752015-10-28 14:54:51 -07002737 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002738 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002739 AtomicFile restrictionsFile = new AtomicFile(
2740 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002741 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002742 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002743 }
2744
2745 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002746 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002747 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002748 try {
2749 fos = restrictionsFile.startWrite();
2750 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2751
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002752 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002753 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002754 serializer.startDocument(null, true);
2755 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2756
2757 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002758 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002759 serializer.endTag(null, TAG_RESTRICTIONS);
2760
2761 serializer.endDocument();
2762 restrictionsFile.finishWrite(fos);
2763 } catch (Exception e) {
2764 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002765 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2766 }
2767 }
2768
2769 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2770 throws IOException {
2771 for (String key : restrictions.keySet()) {
2772 Object value = restrictions.get(key);
2773 serializer.startTag(null, TAG_ENTRY);
2774 serializer.attribute(null, ATTR_KEY, key);
2775
2776 if (value instanceof Boolean) {
2777 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2778 serializer.text(value.toString());
2779 } else if (value instanceof Integer) {
2780 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2781 serializer.text(value.toString());
2782 } else if (value == null || value instanceof String) {
2783 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2784 serializer.text(value != null ? (String) value : "");
2785 } else if (value instanceof Bundle) {
2786 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2787 writeBundle((Bundle) value, serializer);
2788 } else if (value instanceof Parcelable[]) {
2789 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2790 Parcelable[] array = (Parcelable[]) value;
2791 for (Parcelable parcelable : array) {
2792 if (!(parcelable instanceof Bundle)) {
2793 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2794 }
2795 serializer.startTag(null, TAG_ENTRY);
2796 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2797 writeBundle((Bundle) parcelable, serializer);
2798 serializer.endTag(null, TAG_ENTRY);
2799 }
2800 } else {
2801 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2802 String[] values = (String[]) value;
2803 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2804 for (String choice : values) {
2805 serializer.startTag(null, TAG_VALUE);
2806 serializer.text(choice != null ? choice : "");
2807 serializer.endTag(null, TAG_VALUE);
2808 }
2809 }
2810 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002811 }
2812 }
2813
2814 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002815 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002816 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002817 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002818 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002819 }
2820 }
2821
2822 @Override
2823 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002824 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002825 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002826 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002827 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002828 }
2829 // Not found
2830 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002831 }
2832 }
2833
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002834 @Override
2835 public long getUserCreationTime(int userHandle) {
2836 int callingUserId = UserHandle.getCallingUserId();
2837 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002838 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002839 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002840 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002841 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002842 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002843 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002844 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002845 }
2846 }
2847 }
2848 if (userInfo == null) {
2849 throw new SecurityException("userHandle can only be the calling user or a managed "
2850 + "profile associated with this user");
2851 }
2852 return userInfo.creationTime;
2853 }
2854
Amith Yamasani0b285492011-04-14 17:35:23 -07002855 /**
2856 * Caches the list of user ids in an array, adjusting the array size when necessary.
2857 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002858 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002859 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002860 synchronized (mUsersLock) {
2861 final int userSize = mUsers.size();
2862 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002863 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002864 num++;
2865 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002866 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002867 final int[] newUsers = new int[num];
2868 int n = 0;
2869 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002870 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002871 newUsers[n++] = mUsers.keyAt(i);
2872 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002873 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002874 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002875 }
2876 }
2877
2878 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002879 * Called right before a user is started. This gives us a chance to prepare
2880 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002881 */
2882 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002883 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002884 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002885 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002886
2887 if (userId != UserHandle.USER_SYSTEM) {
2888 synchronized (mRestrictionsLock) {
2889 applyUserRestrictionsLR(userId);
2890 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002891 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002892
2893 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002894 }
2895
2896 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002897 * Called right before a user is unlocked. This gives us a chance to prepare
2898 * app storage.
2899 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002900 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002901 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002902 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002903 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002904 }
2905
2906 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002907 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002908 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002909 * @param userId the user that was just foregrounded
2910 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002911 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002912 UserData userData = getUserDataNoChecks(userId);
2913 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002914 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2915 return;
2916 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002917
2918 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002919 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002920 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002921 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002922 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2923 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002924 }
2925
Amith Yamasanieb437d42016-04-29 09:31:25 -07002926 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07002927 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07002928 String demoLauncher =
2929 mContext.getResources().getString(
2930 com.android.internal.R.string.config_demoModeLauncherComponent);
2931 if (!TextUtils.isEmpty(demoLauncher)) {
2932 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07002933 String demoLauncherPkg = componentToEnable.getPackageName();
Amith Yamasanieb437d42016-04-29 09:31:25 -07002934 try {
Sudheer Shanka194e4152016-07-06 17:49:37 -07002935 final IPackageManager iPm = AppGlobals.getPackageManager();
2936 iPm.setComponentEnabledSetting(componentToEnable,
Amith Yamasanieb437d42016-04-29 09:31:25 -07002937 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2938 /* userId= */ userId);
Sudheer Shanka194e4152016-07-06 17:49:37 -07002939 iPm.setApplicationEnabledSetting(demoLauncherPkg,
2940 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2941 /* userId= */ userId, null);
Amith Yamasanieb437d42016-04-29 09:31:25 -07002942 } catch (RemoteException re) {
2943 // Internal, shouldn't happen
2944 }
2945 }
2946 }
2947 }
2948
Amith Yamasani920ace02012-09-20 22:15:37 -07002949 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002950 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002951 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2952 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002953 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002954 private int getNextAvailableId() {
2955 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002956 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002957 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002958 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002959 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002960 }
2961 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002962 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002963 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002964 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002965 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002966
Amith Yamasanifc95e702013-09-26 13:20:17 -07002967 private String packageToRestrictionsFileName(String packageName) {
2968 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2969 }
2970
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002971 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002972 * Enforce that serial number stored in user directory inode matches the
2973 * given expected value. Gracefully sets the serial number if currently
2974 * undefined.
2975 *
2976 * @throws IOException when problem extracting serial number, or serial
2977 * number is mismatched.
2978 */
2979 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06002980 if (StorageManager.isFileEncryptedEmulatedOnly()) {
2981 // When we're emulating FBE, the directory may have been chmod
2982 // 000'ed, meaning we can't read the serial number to enforce it;
2983 // instead of destroying the user, just log a warning.
2984 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
2985 return;
2986 }
2987
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002988 final int foundSerial = getSerialNumber(file);
2989 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2990
2991 if (foundSerial == -1) {
2992 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2993 try {
2994 setSerialNumber(file, serialNumber);
2995 } catch (IOException e) {
2996 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2997 }
2998
2999 } else if (foundSerial != serialNumber) {
3000 throw new IOException("Found serial number " + foundSerial
3001 + " doesn't match expected " + serialNumber);
3002 }
3003 }
3004
3005 /**
3006 * Set serial number stored in user directory inode.
3007 *
3008 * @throws IOException if serial number was already set
3009 */
3010 private static void setSerialNumber(File file, int serialNumber)
3011 throws IOException {
3012 try {
3013 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3014 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3015 } catch (ErrnoException e) {
3016 throw e.rethrowAsIOException();
3017 }
3018 }
3019
3020 /**
3021 * Return serial number stored in user directory inode.
3022 *
3023 * @return parsed serial number, or -1 if not set
3024 */
3025 private static int getSerialNumber(File file) throws IOException {
3026 try {
3027 final byte[] buf = new byte[256];
3028 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
3029 final String serial = new String(buf, 0, len);
3030 try {
3031 return Integer.parseInt(serial);
3032 } catch (NumberFormatException e) {
3033 throw new IOException("Bad serial number: " + serial);
3034 }
3035 } catch (ErrnoException e) {
3036 if (e.errno == OsConstants.ENODATA) {
3037 return -1;
3038 } else {
3039 throw e.rethrowAsIOException();
3040 }
3041 }
3042 }
3043
Amith Yamasani920ace02012-09-20 22:15:37 -07003044 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003045 public void setSeedAccountData(int userId, String accountName, String accountType,
3046 PersistableBundle accountOptions, boolean persist) {
3047 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3048 synchronized (mPackagesLock) {
3049 final UserData userData;
3050 synchronized (mUsersLock) {
3051 userData = getUserDataLU(userId);
3052 if (userData == null) {
3053 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3054 return;
3055 }
3056 userData.seedAccountName = accountName;
3057 userData.seedAccountType = accountType;
3058 userData.seedAccountOptions = accountOptions;
3059 userData.persistSeedData = persist;
3060 }
3061 if (persist) {
3062 writeUserLP(userData);
3063 }
3064 }
3065 }
3066
3067 @Override
3068 public String getSeedAccountName() throws RemoteException {
3069 checkManageUsersPermission("Cannot get seed account information");
3070 synchronized (mUsersLock) {
3071 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3072 return userData.seedAccountName;
3073 }
3074 }
3075
3076 @Override
3077 public String getSeedAccountType() throws RemoteException {
3078 checkManageUsersPermission("Cannot get seed account information");
3079 synchronized (mUsersLock) {
3080 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3081 return userData.seedAccountType;
3082 }
3083 }
3084
3085 @Override
3086 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3087 checkManageUsersPermission("Cannot get seed account information");
3088 synchronized (mUsersLock) {
3089 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3090 return userData.seedAccountOptions;
3091 }
3092 }
3093
3094 @Override
3095 public void clearSeedAccountData() throws RemoteException {
3096 checkManageUsersPermission("Cannot clear seed account information");
3097 synchronized (mPackagesLock) {
3098 UserData userData;
3099 synchronized (mUsersLock) {
3100 userData = getUserDataLU(UserHandle.getCallingUserId());
3101 if (userData == null) return;
3102 userData.clearSeedAccountData();
3103 }
3104 writeUserLP(userData);
3105 }
3106 }
3107
3108 @Override
3109 public boolean someUserHasSeedAccount(String accountName, String accountType)
3110 throws RemoteException {
3111 checkManageUsersPermission("Cannot check seed account information");
3112 synchronized (mUsersLock) {
3113 final int userSize = mUsers.size();
3114 for (int i = 0; i < userSize; i++) {
3115 final UserData data = mUsers.valueAt(i);
3116 if (data.info.isInitialized()) continue;
3117 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3118 continue;
3119 }
3120 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3121 continue;
3122 }
3123 return true;
3124 }
3125 }
3126 return false;
3127 }
3128
3129 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003130 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3131 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3132 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3133 }
3134
3135 int onShellCommand(Shell shell, String cmd) {
3136 if (cmd == null) {
3137 return shell.handleDefaultCommands(cmd);
3138 }
3139
3140 final PrintWriter pw = shell.getOutPrintWriter();
3141 try {
3142 switch(cmd) {
3143 case "list":
3144 return runList(pw);
3145 }
3146 } catch (RemoteException e) {
3147 pw.println("Remote exception: " + e);
3148 }
3149 return -1;
3150 }
3151
3152 private int runList(PrintWriter pw) throws RemoteException {
3153 final IActivityManager am = ActivityManagerNative.getDefault();
3154 final List<UserInfo> users = getUsers(false);
3155 if (users == null) {
3156 pw.println("Error: couldn't get users");
3157 return 1;
3158 } else {
3159 pw.println("Users:");
3160 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003161 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003162 pw.println("\t" + users.get(i).toString() + running);
3163 }
3164 return 0;
3165 }
3166 }
3167
3168 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003169 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3170 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3171 != PackageManager.PERMISSION_GRANTED) {
3172 pw.println("Permission Denial: can't dump UserManager from from pid="
3173 + Binder.getCallingPid()
3174 + ", uid=" + Binder.getCallingUid()
3175 + " without permission "
3176 + android.Manifest.permission.DUMP);
3177 return;
3178 }
3179
3180 long now = System.currentTimeMillis();
3181 StringBuilder sb = new StringBuilder();
3182 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003183 synchronized (mUsersLock) {
3184 pw.println("Users:");
3185 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003186 UserData userData = mUsers.valueAt(i);
3187 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003188 continue;
3189 }
Amith Yamasani12747872015-12-07 14:19:49 -08003190 UserInfo userInfo = userData.info;
3191 final int userId = userInfo.id;
3192 pw.print(" "); pw.print(userInfo);
3193 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003194 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003195 pw.print(" <removing> ");
3196 }
Amith Yamasani12747872015-12-07 14:19:49 -08003197 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003198 pw.print(" <partial>");
3199 }
3200 pw.println();
3201 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003202 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003203 pw.println("<unknown>");
3204 } else {
3205 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003206 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003207 sb.append(" ago");
3208 pw.println(sb);
3209 }
3210 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003211 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003212 pw.println("<unknown>");
3213 } else {
3214 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003215 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003216 sb.append(" ago");
3217 pw.println(sb);
3218 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003219 pw.print(" Last logged in fingerprint: ");
3220 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003221 pw.print(" Has profile owner: ");
3222 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003223 pw.println(" Restrictions:");
3224 synchronized (mRestrictionsLock) {
3225 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003226 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003227 pw.println(" Device policy local restrictions:");
3228 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003229 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003230 pw.println(" Effective restrictions:");
3231 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003232 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003233 }
Amith Yamasani12747872015-12-07 14:19:49 -08003234
3235 if (userData.account != null) {
3236 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003237 pw.println();
3238 }
Amith Yamasani12747872015-12-07 14:19:49 -08003239
3240 if (userData.seedAccountName != null) {
3241 pw.print(" Seed account name: " + userData.seedAccountName);
3242 pw.println();
3243 if (userData.seedAccountType != null) {
3244 pw.print(" account type: " + userData.seedAccountType);
3245 pw.println();
3246 }
3247 if (userData.seedAccountOptions != null) {
3248 pw.print(" account options exist");
3249 pw.println();
3250 }
3251 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003252 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003253 }
Amith Yamasani12747872015-12-07 14:19:49 -08003254 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003255 pw.println(" Device policy global restrictions:");
3256 synchronized (mRestrictionsLock) {
3257 UserRestrictionsUtils
3258 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3259 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003260 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003261 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3262 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003263 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003264 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003265 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003266 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003267 synchronized (mUsersLock) {
3268 pw.println();
3269 pw.println(" Device managed: " + mIsDeviceManaged);
3270 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003271 synchronized (mUserStates) {
3272 pw.println(" Started users state: " + mUserStates);
3273 }
Amith Yamasani12747872015-12-07 14:19:49 -08003274 // Dump some capabilities
3275 pw.println();
3276 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3277 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003278 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3279 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003280 }
3281 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003282
3283 final class MainHandler extends Handler {
3284
3285 @Override
3286 public void handleMessage(Message msg) {
3287 switch (msg.what) {
3288 case WRITE_USER_MSG:
3289 removeMessages(WRITE_USER_MSG, msg.obj);
3290 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003291 int userId = ((UserData) msg.obj).info.id;
3292 UserData userData = getUserDataNoChecks(userId);
3293 if (userData != null) {
3294 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003295 }
3296 }
3297 }
3298 }
3299 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003300
3301 /**
3302 * @param userId
3303 * @return whether the user has been initialized yet
3304 */
3305 boolean isInitialized(int userId) {
3306 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3307 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003308
3309 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003310 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003311 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3312 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003313 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003314 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003315 }
3316
3317 @Override
3318 public Bundle getBaseUserRestrictions(int userId) {
3319 synchronized (mRestrictionsLock) {
3320 return mBaseUserRestrictions.get(userId);
3321 }
3322 }
3323
3324 @Override
3325 public void setBaseUserRestrictionsByDpmsForMigration(
3326 int userId, Bundle baseRestrictions) {
3327 synchronized (mRestrictionsLock) {
3328 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003329 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003330 }
3331
Amith Yamasani12747872015-12-07 14:19:49 -08003332 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003333 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003334 if (userData != null) {
3335 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003336 } else {
3337 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3338 }
3339 }
3340 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003341
3342 @Override
3343 public boolean getUserRestriction(int userId, String key) {
3344 return getUserRestrictions(userId).getBoolean(key);
3345 }
3346
3347 @Override
3348 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3349 synchronized (mUserRestrictionsListeners) {
3350 mUserRestrictionsListeners.add(listener);
3351 }
3352 }
3353
3354 @Override
3355 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3356 synchronized (mUserRestrictionsListeners) {
3357 mUserRestrictionsListeners.remove(listener);
3358 }
3359 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003360
3361 @Override
3362 public void setDeviceManaged(boolean isManaged) {
3363 synchronized (mUsersLock) {
3364 mIsDeviceManaged = isManaged;
3365 }
3366 }
3367
3368 @Override
3369 public void setUserManaged(int userId, boolean isManaged) {
3370 synchronized (mUsersLock) {
3371 mIsUserManaged.put(userId, isManaged);
3372 }
3373 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003374
3375 @Override
3376 public void setUserIcon(int userId, Bitmap bitmap) {
3377 long ident = Binder.clearCallingIdentity();
3378 try {
3379 synchronized (mPackagesLock) {
3380 UserData userData = getUserDataNoChecks(userId);
3381 if (userData == null || userData.info.partial) {
3382 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3383 return;
3384 }
3385 writeBitmapLP(userData.info, bitmap);
3386 writeUserLP(userData);
3387 }
3388 sendUserInfoChangedBroadcast(userId);
3389 } finally {
3390 Binder.restoreCallingIdentity(ident);
3391 }
3392 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003393
3394 @Override
3395 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3396 synchronized (mUsersLock) {
3397 mForceEphemeralUsers = forceEphemeralUsers;
3398 }
3399 }
3400
3401 @Override
3402 public void removeAllUsers() {
3403 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3404 // Remove the non-system users straight away.
3405 removeNonSystemUsers();
3406 } else {
3407 // Switch to the system user first and then remove the other users.
3408 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3409 @Override
3410 public void onReceive(Context context, Intent intent) {
3411 int userId =
3412 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3413 if (userId != UserHandle.USER_SYSTEM) {
3414 return;
3415 }
3416 mContext.unregisterReceiver(this);
3417 removeNonSystemUsers();
3418 }
3419 };
3420 IntentFilter userSwitchedFilter = new IntentFilter();
3421 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3422 mContext.registerReceiver(
3423 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3424
3425 // Switch to the system user.
3426 ActivityManager am =
3427 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3428 am.switchUser(UserHandle.USER_SYSTEM);
3429 }
3430 }
phweisse9c44062016-02-10 12:57:38 +01003431
3432 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003433 public void onEphemeralUserStop(int userId) {
3434 synchronized (mUsersLock) {
3435 UserInfo userInfo = getUserInfoLU(userId);
3436 if (userInfo != null && userInfo.isEphemeral()) {
3437 // Do not allow switching back to the ephemeral user again as the user is going
3438 // to be deleted.
3439 userInfo.flags |= UserInfo.FLAG_DISABLED;
3440 if (userInfo.isGuest()) {
3441 // Indicate that the guest will be deleted after it stops.
3442 userInfo.guestToRemove = true;
3443 }
3444 }
3445 }
3446 }
3447
3448 @Override
phweisse9c44062016-02-10 12:57:38 +01003449 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3450 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3451 // Keep this in sync with UserManager.createUser
3452 if (user != null && !user.isAdmin()) {
3453 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3454 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3455 }
3456 return user;
3457 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003458
3459 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003460 public boolean isUserRunning(int userId) {
3461 synchronized (mUserStates) {
3462 return mUserStates.get(userId, -1) >= 0;
3463 }
3464 }
3465
3466 @Override
3467 public void setUserState(int userId, int userState) {
3468 synchronized (mUserStates) {
3469 mUserStates.put(userId, userState);
3470 }
3471 }
3472
3473 @Override
3474 public void removeUserState(int userId) {
3475 synchronized (mUserStates) {
3476 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003477 }
3478 }
3479
3480 @Override
3481 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003482 synchronized (mUserStates) {
3483 int state = mUserStates.get(userId, -1);
3484 return (state == UserState.STATE_RUNNING_UNLOCKING)
3485 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003486 }
3487 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003488 }
3489
3490 /* Remove all the users except of the system one. */
3491 private void removeNonSystemUsers() {
3492 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3493 synchronized (mUsersLock) {
3494 final int userSize = mUsers.size();
3495 for (int i = 0; i < userSize; i++) {
3496 UserInfo ui = mUsers.valueAt(i).info;
3497 if (ui.id != UserHandle.USER_SYSTEM) {
3498 usersToRemove.add(ui);
3499 }
3500 }
3501 }
3502 for (UserInfo ui: usersToRemove) {
3503 removeUser(ui.id);
3504 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003505 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003506
3507 private class Shell extends ShellCommand {
3508 @Override
3509 public int onCommand(String cmd) {
3510 return onShellCommand(this, cmd);
3511 }
3512
3513 @Override
3514 public void onHelp() {
3515 final PrintWriter pw = getOutPrintWriter();
3516 pw.println("User manager (user) commands:");
3517 pw.println(" help");
3518 pw.println(" Print this help text.");
3519 pw.println("");
3520 pw.println(" list");
3521 pw.println(" Prints all users on the system.");
3522 }
3523 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003524
3525 private static void debug(String message) {
3526 Log.d(LOG_TAG, message +
3527 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3528 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003529}