blob: 29b42b662c411162db7231b568850251446968e6 [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;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070053import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080054import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010055import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070056import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080057import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070058import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070059import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070060import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010061import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040062import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070063import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070064import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070065import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070066import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080067import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010068import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070069import android.security.GateKeeper;
70import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070071import android.system.ErrnoException;
72import android.system.Os;
73import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070074import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070075import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070076import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070077import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078import android.util.Slog;
79import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080080import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000081import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070082import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import android.util.Xml;
84
Makoto Onuki068c54a2015-10-13 14:34:03 -070085import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070086import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040087import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080088import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080089import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070090import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070091import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000092import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070093import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070094import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000095import com.android.server.am.UserState;
Jeff Sharkey47f71082016-02-01 17:03:54 -070096
97import libcore.io.IoUtils;
98import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080099
100import org.xmlpull.v1.XmlPullParser;
101import org.xmlpull.v1.XmlPullParserException;
102import org.xmlpull.v1.XmlSerializer;
103
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104import java.io.BufferedOutputStream;
105import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700106import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700108import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109import java.io.FileOutputStream;
110import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700111import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100112import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.util.ArrayList;
114import java.util.List;
115
Makoto Onuki068c54a2015-10-13 14:34:03 -0700116/**
117 * Service for {@link UserManager}.
118 *
119 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700120 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800121 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700122 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
123 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
124 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700125 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700126public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700127
Amith Yamasani2a003292012-08-14 18:25:45 -0700128 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800129 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800130 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700131
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800133 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700135 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700137 private static final String ATTR_CREATION_TIME = "created";
138 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600139 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700140 private static final String ATTR_SERIAL_NO = "serialNumber";
141 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700142 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700143 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700144 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100145 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700146 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800147 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
148 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530149 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700150 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700151 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800152 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800153 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100154 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800155 private static final String TAG_ENTRY = "entry";
156 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800157 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800158 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700159 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700162 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
163 private static final String ATTR_TYPE_STRING = "s";
164 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700165 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700166 private static final String ATTR_TYPE_BUNDLE = "B";
167 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700168
Amith Yamasani0b285492011-04-14 17:35:23 -0700169 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700171 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100172 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800174 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700175 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700177 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
178 UserInfo.FLAG_MANAGED_PROFILE
179 | UserInfo.FLAG_EPHEMERAL
180 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700181 | UserInfo.FLAG_GUEST
182 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700183
Amith Yamasani634cf312012-10-04 17:34:21 -0700184 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700185 // We need to keep process uid within Integer.MAX_VALUE.
186 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700187
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700188 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700189
Amith Yamasani920ace02012-09-20 22:15:37 -0700190 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
191
Nicolas Prevotb8186812015-08-06 15:00:03 +0100192 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700193 // without first making sure that the rest of the framework is prepared for it.
194 private static final int MAX_MANAGED_PROFILES = 1;
195
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800196 static final int WRITE_USER_MSG = 1;
197 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530198
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700199 private static final String XATTR_SERIAL = "user.serial";
200
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800201 // Tron counters
202 private static final String TRON_GUEST_CREATED = "users_guest_created";
203 private static final String TRON_USER_CREATED = "users_user_created";
204
Dianne Hackborn4428e172012-08-24 17:43:05 -0700205 private final Context mContext;
206 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700207 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700208 // Short-term lock for internal state, when interaction/sync with PM is not required
209 private final Object mUsersLock = new Object();
210 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700211
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800212 private final Handler mHandler;
213
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700214 private final File mUsersDir;
215 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700216
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800217 private static final IBinder mUserRestriconToken = new Binder();
218
Makoto Onuki068c54a2015-10-13 14:34:03 -0700219 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800220 * User-related information that is used for persisting to flash. Only UserInfo is
221 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800222 */
Amith Yamasani12747872015-12-07 14:19:49 -0800223 private static class UserData {
224 // Basic user information and properties
225 UserInfo info;
226 // Account name used when there is a strong association between a user and an account
227 String account;
228 // Account information for seeding into a newly created user. This could also be
229 // used for login validation for an existing user, for updating their credentials.
230 // In the latter case, data may not need to be persisted as it is only valid for the
231 // current login session.
232 String seedAccountName;
233 String seedAccountType;
234 PersistableBundle seedAccountOptions;
235 // Whether to perist the seed account information to be available after a boot
236 boolean persistSeedData;
237
238 void clearSeedAccountData() {
239 seedAccountName = null;
240 seedAccountType = null;
241 seedAccountOptions = null;
242 persistSeedData = false;
243 }
244 }
245
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800246 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800247 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800248
249 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700250 * User restrictions set via UserManager. This doesn't include restrictions set by
251 * device owner / profile owners.
252 *
253 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
254 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
255 * maybe shared between {@link #mBaseUserRestrictions} and
256 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
257 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700258 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700259 */
260 @GuardedBy("mRestrictionsLock")
261 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
262
263 /**
264 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
265 * with device / profile owner restrictions. We'll initialize it lazily; use
266 * {@link #getEffectiveUserRestrictions} to access it.
267 *
268 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
269 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
270 * maybe shared between {@link #mBaseUserRestrictions} and
271 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
272 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700273 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700274 */
275 @GuardedBy("mRestrictionsLock")
276 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
277
Makoto Onuki4f160732015-10-27 17:15:38 -0700278 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800279 * User restrictions that have already been applied in
280 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
281 * that have changed since the last
282 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700283 */
284 @GuardedBy("mRestrictionsLock")
285 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
286
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800287 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800288 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
289 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800290 */
291 @GuardedBy("mRestrictionsLock")
292 private Bundle mDevicePolicyGlobalUserRestrictions;
293
294 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100295 * Id of the user that set global restrictions.
296 */
297 @GuardedBy("mRestrictionsLock")
298 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
299
300 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800301 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
302 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800303 */
304 @GuardedBy("mRestrictionsLock")
305 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
306
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800307 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530308 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800309
310 /**
311 * Set of user IDs being actively removed. Removed IDs linger in this set
312 * for several seconds to work around a VFS caching issue.
313 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700314 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800315 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700316
Fyodor Kupolov82402752015-10-28 14:54:51 -0700317 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700318 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800319 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700320 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700321 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700322
Jason Monk62062992014-05-06 09:55:28 -0400323 private IAppOpsService mAppOpsService;
324
Makoto Onuki068c54a2015-10-13 14:34:03 -0700325 private final LocalService mLocalService;
326
Makoto Onukie7927da2015-11-25 10:05:17 -0800327 @GuardedBy("mUsersLock")
328 private boolean mIsDeviceManaged;
329
330 @GuardedBy("mUsersLock")
331 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
332
Makoto Onukid45a4a22015-11-02 17:17:38 -0800333 @GuardedBy("mUserRestrictionsListeners")
334 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
335 new ArrayList<>();
336
Clara Bayarria1771112015-12-18 16:29:18 +0000337 private final LockPatternUtils mLockPatternUtils;
338
Ricky Waib1dd80b2016-06-07 18:00:55 +0100339 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
340 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
341
342 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
343 @Override
344 public void onReceive(Context context, Intent intent) {
345 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
346 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
347 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
348 setQuietModeEnabled(userHandle, false);
349 if (target != null) {
350 try {
351 mContext.startIntentSender(target, null, 0, 0, 0);
352 } catch (IntentSender.SendIntentException e) {
353 /* ignore */
354 }
355 }
356 }
357 }
358 };
359
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100360 /**
361 * Whether all users should be created ephemeral.
362 */
363 @GuardedBy("mUsersLock")
364 private boolean mForceEphemeralUsers;
365
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000366 @GuardedBy("mUserStates")
367 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700368
Amith Yamasani258848d2012-08-10 17:06:33 -0700369 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700370
Dianne Hackborn4428e172012-08-24 17:43:05 -0700371 public static UserManagerService getInstance() {
372 synchronized (UserManagerService.class) {
373 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700374 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700375 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700376
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700377 public static class LifeCycle extends SystemService {
378
379 private UserManagerService mUms;
380
381 /**
382 * @param context
383 */
384 public LifeCycle(Context context) {
385 super(context);
386 }
387
388 @Override
389 public void onStart() {
390 mUms = UserManagerService.getInstance();
391 publishBinderService(Context.USER_SERVICE, mUms);
392 }
393
394 @Override
395 public void onBootPhase(int phase) {
396 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
397 mUms.cleanupPartialUsers();
398 }
399 }
400 }
401
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800402 @VisibleForTesting
403 UserManagerService(File dataDir) {
404 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700405 }
406
Dianne Hackborn4428e172012-08-24 17:43:05 -0700407 /**
408 * Called by package manager to create the service. This is closely
409 * associated with the package manager, and the given lock is the
410 * package manager's own lock.
411 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800412 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
413 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700414 }
415
Dianne Hackborn4428e172012-08-24 17:43:05 -0700416 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800417 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700418 mContext = context;
419 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700420 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800421 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800422 synchronized (mPackagesLock) {
423 mUsersDir = new File(dataDir, USER_INFO_DIR);
424 mUsersDir.mkdirs();
425 // Make zeroth user directory, for services to migrate their files to that location
426 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
427 userZeroDir.mkdirs();
428 FileUtils.setPermissions(mUsersDir.toString(),
429 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
430 -1, -1);
431 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
432 initDefaultGuestRestrictions();
433 readUserListLP();
434 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700435 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700436 mLocalService = new LocalService();
437 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000438 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000439 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700440 }
441
442 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400443 mAppOpsService = IAppOpsService.Stub.asInterface(
444 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800445
446 synchronized (mRestrictionsLock) {
447 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400448 }
Samuel Tand9453b82016-03-14 15:57:02 -0700449
450 UserInfo currentGuestUser = findCurrentGuestUser();
451 if (currentGuestUser != null && !hasUserRestriction(
452 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
453 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
454 // to it, in case this guest was created in a previous version where this
455 // user restriction was not a default guest restriction.
456 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
457 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700458
Ricky Waib1dd80b2016-06-07 18:00:55 +0100459 mContext.registerReceiver(mDisableQuietModeCallback,
460 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
461 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700462 }
463
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700464 void cleanupPartialUsers() {
465 // Prune out any partially created, partially removed and ephemeral users.
466 ArrayList<UserInfo> partials = new ArrayList<>();
467 synchronized (mUsersLock) {
468 final int userSize = mUsers.size();
469 for (int i = 0; i < userSize; i++) {
470 UserInfo ui = mUsers.valueAt(i).info;
471 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
472 partials.add(ui);
Amith Yamasaniae261892016-06-27 10:40:09 -0700473 mRemovingUserIds.append(ui.id, true);
474 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700475 }
476 }
477 }
478 final int partialsSize = partials.size();
479 for (int i = 0; i < partialsSize; i++) {
480 UserInfo ui = partials.get(i);
481 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
482 + " (name=" + ui.name + ")");
483 removeUserState(ui.id);
484 }
485 }
486
Amith Yamasani258848d2012-08-10 17:06:33 -0700487 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800488 public String getUserAccount(int userId) {
489 checkManageUserAndAcrossUsersFullPermission("get user account");
490 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800491 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800492 }
493 }
494
495 @Override
496 public void setUserAccount(int userId, String accountName) {
497 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800498 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800499 synchronized (mPackagesLock) {
500 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800501 final UserData userData = mUsers.get(userId);
502 if (userData == null) {
503 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
504 return;
505 }
506 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800507 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800508 userData.account = accountName;
509 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800510 }
511 }
512
513 if (userToUpdate != null) {
514 writeUserLP(userToUpdate);
515 }
516 }
517 }
518
519 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700520 public UserInfo getPrimaryUser() {
521 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700522 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700523 final int userSize = mUsers.size();
524 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800525 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800526 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700527 return ui;
528 }
529 }
530 }
531 return null;
532 }
533
534 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700535 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700536 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700537 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700538 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700539 final int userSize = mUsers.size();
540 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800541 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700542 if (ui.partial) {
543 continue;
544 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800545 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700546 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700547 }
Amith Yamasani13593602012-03-22 16:16:17 -0700548 }
549 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700550 }
Amith Yamasani13593602012-03-22 16:16:17 -0700551 }
552
Amith Yamasani258848d2012-08-10 17:06:33 -0700553 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100554 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700555 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800556 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700557 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700558 } else {
559 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800560 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700561 final long ident = Binder.clearCallingIdentity();
562 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700564 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100565 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700566 } finally {
567 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000568 }
569 }
570
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700571 @Override
572 public int[] getProfileIds(int userId, boolean enabledOnly) {
573 if (userId != UserHandle.getCallingUserId()) {
bohud91dd062016-09-26 16:20:07 -0700574 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700575 }
576 final long ident = Binder.clearCallingIdentity();
577 try {
578 synchronized (mUsersLock) {
579 return getProfileIdsLU(userId, enabledOnly).toArray();
580 }
581 } finally {
582 Binder.restoreCallingIdentity(ident);
583 }
584 }
585
Amith Yamasanibe465322014-04-24 13:45:17 -0700586 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700587 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700588 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
589 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
590 for (int i = 0; i < profileIds.size(); i++) {
591 int profileId = profileIds.get(i);
592 UserInfo userInfo = mUsers.get(profileId).info;
593 // If full info is not required - clear PII data to prevent 3P apps from reading it
594 if (!fullInfo) {
595 userInfo = new UserInfo(userInfo);
596 userInfo.name = null;
597 userInfo.iconPath = null;
598 } else {
599 userInfo = userWithName(userInfo);
600 }
601 users.add(userInfo);
602 }
603 return users;
604 }
605
606 /**
607 * Assume permissions already checked and caller's identity cleared
608 */
609 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700610 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700611 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700612 if (user == null) {
613 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700614 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700615 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700616 final int userSize = mUsers.size();
617 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800618 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700619 if (!isProfileOf(user, profile)) {
620 continue;
621 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100622 if (enabledOnly && !profile.isEnabled()) {
623 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700624 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700625 if (mRemovingUserIds.get(profile.id)) {
626 continue;
627 }
Tony Mak80189cd2016-04-05 17:21:42 +0100628 if (profile.partial) {
629 continue;
630 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700631 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700632 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700633 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700634 }
635
Jessica Hummelbe81c802014-04-22 15:49:22 +0100636 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700637 public int getCredentialOwnerProfile(int userHandle) {
638 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000639 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700640 synchronized (mUsersLock) {
641 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700642 if (profileParent != null) {
643 return profileParent.id;
644 }
645 }
646 }
647
648 return userHandle;
649 }
650
651 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700652 public boolean isSameProfileGroup(int userId, int otherUserId) {
653 if (userId == otherUserId) return true;
654 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov7a1e6822016-12-05 13:23:28 -0800655 return isSameProfileGroupNoChecks(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700656 }
657
Fyodor Kupolov7a1e6822016-12-05 13:23:28 -0800658 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700659 synchronized (mUsersLock) {
660 UserInfo userInfo = getUserInfoLU(userId);
661 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
662 return false;
663 }
664 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
665 if (otherUserInfo == null
666 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
667 return false;
668 }
669 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700670 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700671 }
672
673 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100674 public UserInfo getProfileParent(int userHandle) {
675 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700676 synchronized (mUsersLock) {
677 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700678 }
679 }
680
Fyodor Kupolov82402752015-10-28 14:54:51 -0700681 private UserInfo getProfileParentLU(int userHandle) {
682 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700683 if (profile == null) {
684 return null;
685 }
686 int parentUserId = profile.profileGroupId;
687 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
688 return null;
689 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700690 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100691 }
692 }
693
Fyodor Kupolov82402752015-10-28 14:54:51 -0700694 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100695 return user.id == profile.id ||
696 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
697 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000698 }
699
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000700 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000701 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100702 Intent intent = new Intent();
703 if (inQuietMode) {
704 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
705 } else {
706 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
707 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000708 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
709 intent.putExtra(Intent.EXTRA_USER, profileHandle);
710 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000711 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000712 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000713 }
714
715 @Override
716 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
717 checkManageUsersPermission("silence profile");
718 boolean changed = false;
719 UserInfo profile, parent;
720 synchronized (mPackagesLock) {
721 synchronized (mUsersLock) {
722 profile = getUserInfoLU(userHandle);
723 parent = getProfileParentLU(userHandle);
724
725 }
726 if (profile == null || !profile.isManagedProfile()) {
727 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
728 }
729 if (profile.isQuietModeEnabled() != enableQuietMode) {
730 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800731 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000732 changed = true;
733 }
734 }
735 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000736 long identity = Binder.clearCallingIdentity();
737 try {
738 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100739 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100740 LocalServices.getService(ActivityManagerInternal.class)
741 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000742 } else {
743 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
744 }
745 } catch (RemoteException e) {
746 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
747 } finally {
748 Binder.restoreCallingIdentity(identity);
749 }
750
751 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
752 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000753 }
754 }
755
756 @Override
757 public boolean isQuietModeEnabled(int userHandle) {
758 synchronized (mPackagesLock) {
759 UserInfo info;
760 synchronized (mUsersLock) {
761 info = getUserInfoLU(userHandle);
762 }
763 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000764 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000765 }
766 return info.isQuietModeEnabled();
767 }
768 }
769
Kenny Guya52dc3e2014-02-11 15:33:14 +0000770 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100771 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100772 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600773 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100774 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100775 // if the user is already unlocked, no need to show a profile challenge
776 setQuietModeEnabled(userHandle, false);
777 return true;
778 }
779
780 long identity = Binder.clearCallingIdentity();
781 try {
782 // otherwise, we show a profile challenge to trigger decryption of the user
783 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
784 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100785 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
786 // lock, confirm screenlock page will know and show personal challenge, and unlock
787 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100788 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
789 userHandle);
790 if (unlockIntent == null) {
791 return false;
792 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100793 final Intent callBackIntent = new Intent(
794 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100795 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100796 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100797 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100798 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
799 callBackIntent.setPackage(mContext.getPackageName());
800 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
801 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
802 mContext,
803 0,
804 callBackIntent,
805 PendingIntent.FLAG_CANCEL_CURRENT |
806 PendingIntent.FLAG_ONE_SHOT |
807 PendingIntent.FLAG_IMMUTABLE);
808 // After unlocking the challenge, it will disable quiet mode and run the original
809 // intentSender
810 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100811 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
812 mContext.startActivity(unlockIntent);
813 } finally {
814 Binder.restoreCallingIdentity(identity);
815 }
816 return false;
817 }
818
819 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100820 public void setUserEnabled(int userId) {
821 checkManageUsersPermission("enable user");
822 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700823 UserInfo info;
824 synchronized (mUsersLock) {
825 info = getUserInfoLU(userId);
826 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100827 if (info != null && !info.isEnabled()) {
828 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800829 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100830 }
831 }
832 }
833
834 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700835 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700836 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000837 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700838 return userWithName(getUserInfoLU(userId));
839 }
840 }
841
842 /**
843 * Returns a UserInfo object with the name filled in, for Owner, or the original
844 * if the name is already set.
845 */
846 private UserInfo userWithName(UserInfo orig) {
847 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
848 UserInfo withName = new UserInfo(orig);
849 withName.name = getOwnerName();
850 return withName;
851 } else {
852 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000853 }
854 }
855
856 @Override
857 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000858 int callingUserId = UserHandle.getCallingUserId();
859 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov7a1e6822016-12-05 13:23:28 -0800860 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
861 throw new SecurityException(
862 "You need MANAGE_USERS permission to: check if specified user a " +
863 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000864 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000865 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700866 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700867 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000868 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700869 }
870 }
871
Amith Yamasani71e6c692013-03-24 17:39:28 -0700872 @Override
Fyodor Kupolov7a1e6822016-12-05 13:23:28 -0800873 public boolean isUserUnlockingOrUnlocked(int userId) {
874 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
875 return mLocalService.isUserUnlockingOrUnlocked(userId);
876 }
877
878 @Override
879 public boolean isUserUnlocked(int userId) {
880 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
881 return mLocalService.isUserUnlockingOrUnlocked(userId);
882 }
883
884 @Override
885 public boolean isUserRunning(int userId) {
886 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
887 return mLocalService.isUserRunning(userId);
888 }
889
890 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
891 int callingUserId = UserHandle.getCallingUserId();
892 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
893 hasManageUsersPermission()) {
894 return;
895 }
896 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
897 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
898 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
899 + "to: check " + name);
900 }
901 }
902
903 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700904 public boolean isDemoUser(int userId) {
905 int callingUserId = UserHandle.getCallingUserId();
906 if (callingUserId != userId && !hasManageUsersPermission()) {
907 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
908 + " is a demo user");
909 }
910 synchronized (mUsersLock) {
911 UserInfo userInfo = getUserInfoLU(userId);
912 return userInfo != null && userInfo.isDemo();
913 }
914 }
915
916 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700917 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700918 synchronized (mUsersLock) {
919 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700920 }
921 }
922
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700923 @Override
924 public boolean canHaveRestrictedProfile(int userId) {
925 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700926 synchronized (mUsersLock) {
927 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700928 if (userInfo == null || !userInfo.canHaveProfile()) {
929 return false;
930 }
931 if (!userInfo.isAdmin()) {
932 return false;
933 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800934 // restricted profile can be created if there is no DO set and the admin user has no PO;
935 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700936 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700937 }
938
Amith Yamasani195263742012-08-21 15:40:12 -0700939 /*
940 * Should be locked on mUsers before calling this.
941 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700942 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800943 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700944 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800945 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700946 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
947 return null;
948 }
Amith Yamasani12747872015-12-07 14:19:49 -0800949 return userData != null ? userData.info : null;
950 }
951
952 private UserData getUserDataLU(int userId) {
953 final UserData userData = mUsers.get(userId);
954 // If it is partial and not in the process of being removed, return as unknown user.
955 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
956 return null;
957 }
958 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700959 }
960
Fyodor Kupolov82402752015-10-28 14:54:51 -0700961 /**
962 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
963 * <p>No permissions checking or any addition checks are made</p>
964 */
965 private UserInfo getUserInfoNoChecks(int userId) {
966 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800967 final UserData userData = mUsers.get(userId);
968 return userData != null ? userData.info : null;
969 }
970 }
971
972 /**
973 * Obtains {@link #mUsersLock} and return UserData from mUsers.
974 * <p>No permissions checking or any addition checks are made</p>
975 */
976 private UserData getUserDataNoChecks(int userId) {
977 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700978 return mUsers.get(userId);
979 }
980 }
981
Amith Yamasani236b2b52015-08-18 14:32:14 -0700982 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700983 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700984 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700985 }
986
Amith Yamasani258848d2012-08-10 17:06:33 -0700987 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700988 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700989 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700990 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700991 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800992 UserData userData = getUserDataNoChecks(userId);
993 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700994 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
995 return;
996 }
Amith Yamasani12747872015-12-07 14:19:49 -0800997 if (name != null && !name.equals(userData.info.name)) {
998 userData.info.name = name;
999 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001000 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001001 }
1002 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001003 if (changed) {
1004 sendUserInfoChangedBroadcast(userId);
1005 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001006 }
1007
Amith Yamasani258848d2012-08-10 17:06:33 -07001008 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001009 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001010 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001011 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1012 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1013 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001014 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001015 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001016 }
1017
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001018
1019
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001020 private void sendUserInfoChangedBroadcast(int userId) {
1021 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1022 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1023 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001024 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001025 }
1026
Amith Yamasani258848d2012-08-10 17:06:33 -07001027 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001028 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001029 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001030 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001031 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1032 if (targetUserInfo == null || targetUserInfo.partial) {
1033 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001034 return null;
1035 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001036
1037 final int callingUserId = UserHandle.getCallingUserId();
1038 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1039 final int targetGroupId = targetUserInfo.profileGroupId;
1040 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1041 && callingGroupId == targetGroupId);
1042 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001043 checkManageUsersPermission("get the icon of a user who is not related");
1044 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001045
1046 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001047 return null;
1048 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001049 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001050 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001051
1052 try {
1053 return ParcelFileDescriptor.open(
1054 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1055 } catch (FileNotFoundException e) {
1056 Log.e(LOG_TAG, "Couldn't find icon file", e);
1057 }
1058 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001059 }
1060
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001061 public void makeInitialized(int userId) {
1062 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001063 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001064 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001065 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001066 userData = mUsers.get(userId);
1067 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001068 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001069 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001070 }
Amith Yamasani12747872015-12-07 14:19:49 -08001071 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1072 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001073 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001074 }
1075 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001076 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001077 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001078 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001079 }
1080
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001081 /**
1082 * If default guest restrictions haven't been initialized yet, add the basic
1083 * restrictions.
1084 */
1085 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001086 synchronized (mGuestRestrictions) {
1087 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001088 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001089 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001090 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1091 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1092 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001093 }
1094 }
1095
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001096 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301097 public Bundle getDefaultGuestRestrictions() {
1098 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001099 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301100 return new Bundle(mGuestRestrictions);
1101 }
1102 }
1103
1104 @Override
1105 public void setDefaultGuestRestrictions(Bundle restrictions) {
1106 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001107 synchronized (mGuestRestrictions) {
1108 mGuestRestrictions.clear();
1109 mGuestRestrictions.putAll(restrictions);
1110 }
1111 synchronized (mPackagesLock) {
1112 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301113 }
1114 }
1115
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001116 /**
1117 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1118 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001119 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001120 @Nullable Bundle global) {
1121 Preconditions.checkNotNull(local);
1122 boolean globalChanged = false;
1123 boolean localChanged;
1124 synchronized (mRestrictionsLock) {
1125 if (global != null) {
1126 // Update global.
1127 globalChanged = !UserRestrictionsUtils.areEqual(
1128 mDevicePolicyGlobalUserRestrictions, global);
1129 if (globalChanged) {
1130 mDevicePolicyGlobalUserRestrictions = global;
1131 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001132 // Remember the global restriction owner userId to be able to make a distinction
1133 // in getUserRestrictionSource on who set local policies.
1134 mGlobalRestrictionOwnerUserId = userId;
1135 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001136 if (mGlobalRestrictionOwnerUserId == userId) {
1137 // When profile owner sets restrictions it passes null global bundle and we
1138 // reset global restriction owner userId.
1139 // This means this user used to have DO, but now the DO is gone and the user
1140 // instead has PO.
1141 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1142 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001143 }
1144 {
1145 // Update local.
1146 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1147 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1148 if (localChanged) {
1149 mDevicePolicyLocalUserRestrictions.put(userId, local);
1150 }
1151 }
1152 }
1153 if (DBG) {
1154 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1155 + " global=" + global + (globalChanged ? " (changed)" : "")
1156 + " local=" + local + (localChanged ? " (changed)" : "")
1157 );
1158 }
1159 // Don't call them within the mRestrictionsLock.
1160 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001161 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001162 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001163 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001164 if (globalChanged) {
1165 writeUserListLP();
1166 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001167 }
1168
1169 synchronized (mRestrictionsLock) {
1170 if (globalChanged) {
1171 applyUserRestrictionsForAllUsersLR();
1172 } else if (localChanged) {
1173 applyUserRestrictionsLR(userId);
1174 }
1175 }
1176 }
1177
Makoto Onuki068c54a2015-10-13 14:34:03 -07001178 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001179 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001180 final Bundle baseRestrictions =
1181 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1182 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1183 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001184
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001185 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1186 // Common case first.
1187 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001188 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001189 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1190 UserRestrictionsUtils.merge(effective, global);
1191 UserRestrictionsUtils.merge(effective, local);
1192
Makoto Onuki068c54a2015-10-13 14:34:03 -07001193 return effective;
1194 }
1195
1196 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001197 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001198 if (DBG) {
1199 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1200 }
1201 mCachedEffectiveUserRestrictions.remove(userId);
1202 }
1203
1204 private Bundle getEffectiveUserRestrictions(int userId) {
1205 synchronized (mRestrictionsLock) {
1206 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1207 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001208 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001209 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1210 }
1211 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001212 }
1213 }
1214
Makoto Onuki068c54a2015-10-13 14:34:03 -07001215 /** @return a specific user restriction that's in effect currently. */
1216 @Override
1217 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001218 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1219 return false;
1220 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001221 Bundle restrictions = getEffectiveUserRestrictions(userId);
1222 return restrictions != null && restrictions.getBoolean(restrictionKey);
1223 }
1224
1225 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001226 * @hide
1227 *
1228 * Returns who set a user restriction on a user.
1229 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1230 * @param restrictionKey the string key representing the restriction
1231 * @param userId the id of the user for whom to retrieve the restrictions.
1232 * @return The source of user restriction. Any combination of
1233 * {@link UserManager#RESTRICTION_NOT_SET},
1234 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1235 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1236 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1237 */
1238 @Override
1239 public int getUserRestrictionSource(String restrictionKey, int userId) {
1240 checkManageUsersPermission("getUserRestrictionSource");
1241 int result = UserManager.RESTRICTION_NOT_SET;
1242
1243 // Shortcut for the most common case
1244 if (!hasUserRestriction(restrictionKey, userId)) {
1245 return result;
1246 }
1247
1248 if (hasBaseUserRestriction(restrictionKey, userId)) {
1249 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1250 }
1251
1252 synchronized(mRestrictionsLock) {
1253 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1254 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1255 && localRestrictions.getBoolean(restrictionKey)) {
1256 // Local restrictions may have been set by device owner the userId of which is
1257 // stored in mGlobalRestrictionOwnerUserId.
1258 if (mGlobalRestrictionOwnerUserId == userId) {
1259 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1260 } else {
1261 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1262 }
1263 }
1264 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1265 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1266 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1267 }
1268 }
1269
1270 return result;
1271 }
1272
1273 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001274 * @return UserRestrictions that are in effect currently. This always returns a new
1275 * {@link Bundle}.
1276 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001277 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001278 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001279 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001280 }
1281
1282 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001283 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1284 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001285 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1286 return false;
1287 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001288 synchronized (mRestrictionsLock) {
1289 Bundle bundle = mBaseUserRestrictions.get(userId);
1290 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1291 }
1292 }
1293
1294 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001295 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001296 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001297 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1298 return;
1299 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001300 synchronized (mRestrictionsLock) {
1301 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1302 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001303 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1304 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001305 newRestrictions.putBoolean(key, value);
1306
Fyodor Kupolov82402752015-10-28 14:54:51 -07001307 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001308 }
1309 }
1310
Makoto Onuki068c54a2015-10-13 14:34:03 -07001311 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001312 * Optionally updating user restrictions, calculate the effective user restrictions and also
1313 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001314 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001315 * @param newRestrictions User restrictions to set.
1316 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001317 * @param userId target user ID.
1318 */
1319 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001320 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001321 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001322
1323 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1324 mAppliedUserRestrictions.get(userId));
1325
1326 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001327 if (newRestrictions != null) {
1328 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001329 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1330
1331 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001332 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1333 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001334
1335 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1336 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001337 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001338 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001339 }
1340
Fyodor Kupolov82402752015-10-28 14:54:51 -07001341 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001342
Makoto Onuki759a7632015-10-28 16:43:10 -07001343 mCachedEffectiveUserRestrictions.put(userId, effective);
1344
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001345 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001346 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001347 debug("Applying user restrictions: userId=" + userId
1348 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001349 }
1350
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001351 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001352 mHandler.post(new Runnable() {
1353 @Override
1354 public void run() {
1355 try {
1356 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1357 } catch (RemoteException e) {
1358 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1359 }
1360 }
1361 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001362 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001363
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001364 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001365
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001366 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001367 }
1368
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001369 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001370 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001371 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1372 // actually, but we still need some kind of synchronization otherwise we might end up
1373 // calling listeners out-of-order, thus "LR".
1374
1375 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1376 return;
1377 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001378
1379 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1380 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1381
1382 mHandler.post(new Runnable() {
1383 @Override
1384 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001385 UserRestrictionsUtils.applyUserRestrictions(
1386 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001387
Makoto Onukid45a4a22015-11-02 17:17:38 -08001388 final UserRestrictionsListener[] listeners;
1389 synchronized (mUserRestrictionsListeners) {
1390 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1391 mUserRestrictionsListeners.toArray(listeners);
1392 }
1393 for (int i = 0; i < listeners.length; i++) {
1394 listeners[i].onUserRestrictionsChanged(userId,
1395 newRestrictionsFinal, prevRestrictionsFinal);
1396 }
1397 }
1398 });
1399 }
1400
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001401 // Package private for the inner class.
1402 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001403 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001404 }
1405
1406 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001407 // Package private for the inner class.
1408 void applyUserRestrictionsForAllUsersLR() {
1409 if (DBG) {
1410 debug("applyUserRestrictionsForAllUsersLR");
1411 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001412 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001413 mCachedEffectiveUserRestrictions.clear();
1414
Makoto Onuki068c54a2015-10-13 14:34:03 -07001415 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1416 // it on a handler.
1417 final Runnable r = new Runnable() {
1418 @Override
1419 public void run() {
1420 // Then get the list of running users.
1421 final int[] runningUsers;
1422 try {
1423 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1424 } catch (RemoteException e) {
1425 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1426 return;
1427 }
1428 // Then re-calculate the effective restrictions and apply, only for running users.
1429 // It's okay if a new user has started after the getRunningUserIds() call,
1430 // because we'll do the same thing (re-calculate the restrictions and apply)
1431 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001432 synchronized (mRestrictionsLock) {
1433 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001434 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001435 }
1436 }
1437 }
1438 };
1439 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001440 }
1441
Amith Yamasani258848d2012-08-10 17:06:33 -07001442 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001443 * Check if we've hit the limit of how many users can be created.
1444 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001445 private boolean isUserLimitReached() {
1446 int count;
1447 synchronized (mUsersLock) {
1448 count = getAliveUsersExcludingGuestsCountLU();
1449 }
1450 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001451 }
1452
1453 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001454 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001455 checkManageUsersPermission("check if more managed profiles can be added.");
1456 if (ActivityManager.isLowRamDeviceStatic()) {
1457 return false;
1458 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001459 if (!mContext.getPackageManager().hasSystemFeature(
1460 PackageManager.FEATURE_MANAGED_USERS)) {
1461 return false;
1462 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001463 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001464 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1465 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1466 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001467 return false;
1468 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001469 synchronized(mUsersLock) {
1470 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001471 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001472 return false;
1473 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001474 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1475 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001476 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001477 return usersCountAfterRemoving == 1
1478 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001479 }
1480 }
1481
Fyodor Kupolov82402752015-10-28 14:54:51 -07001482 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001483 int aliveUserCount = 0;
1484 final int totalUserCount = mUsers.size();
1485 // Skip over users being removed
1486 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001487 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001488 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001489 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001490 aliveUserCount++;
1491 }
1492 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001493 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001494 }
1495
1496 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001497 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001498 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1499 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1500 * permissions can make certain calls to the UserManager.
1501 *
1502 * @param message used as message if SecurityException is thrown
1503 * @throws SecurityException if the caller does not have enough privilege.
1504 */
1505 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1506 final int uid = Binder.getCallingUid();
1507 if (uid != Process.SYSTEM_UID && uid != 0
1508 && ActivityManager.checkComponentPermission(
1509 Manifest.permission.MANAGE_USERS,
1510 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1511 && ActivityManager.checkComponentPermission(
1512 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1513 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1514 throw new SecurityException(
1515 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1516 + message);
1517 }
1518 }
1519
1520 /**
1521 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001522 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001523 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001524 *
1525 * @param message used as message if SecurityException is thrown
1526 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001527 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001528 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001529 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001530 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001531 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1532 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001533 }
1534
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001535 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001536 * Enforces that only the system UID or root's UID or apps that have the
1537 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1538 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1539 * can make certain calls to the UserManager.
1540 *
1541 * @param message used as message if SecurityException is thrown
1542 * @throws SecurityException if the caller is not system or root
1543 * @see #hasManageOrCreateUsersPermission()
1544 */
1545 private static final void checkManageOrCreateUsersPermission(String message) {
1546 if (!hasManageOrCreateUsersPermission()) {
1547 throw new SecurityException(
1548 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1549 }
1550 }
1551
1552 /**
1553 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1554 * to create user/profiles other than what is allowed for
1555 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1556 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1557 */
1558 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1559 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1560 if (!hasManageOrCreateUsersPermission()) {
1561 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1562 + "permission to create an user with flags: " + creationFlags);
1563 }
1564 } else if (!hasManageUsersPermission()) {
1565 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1566 + " with flags: " + creationFlags);
1567 }
1568 }
1569
1570 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001571 * @return whether the calling UID is system UID or root's UID or the calling app has the
1572 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1573 */
1574 private static final boolean hasManageUsersPermission() {
1575 final int callingUid = Binder.getCallingUid();
1576 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1577 || callingUid == Process.ROOT_UID
1578 || ActivityManager.checkComponentPermission(
1579 android.Manifest.permission.MANAGE_USERS,
1580 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1581 }
1582
1583 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001584 * @return whether the calling UID is system UID or root's UID or the calling app has the
1585 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1586 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1587 */
1588 private static final boolean hasManageOrCreateUsersPermission() {
1589 final int callingUid = Binder.getCallingUid();
1590 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1591 || callingUid == Process.ROOT_UID
1592 || ActivityManager.checkComponentPermission(
1593 android.Manifest.permission.MANAGE_USERS,
1594 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1595 || ActivityManager.checkComponentPermission(
1596 android.Manifest.permission.CREATE_USERS,
1597 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1598 }
1599
1600 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001601 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1602 * UserManager.
1603 *
1604 * @param message used as message if SecurityException is thrown
1605 * @throws SecurityException if the caller is not system or root
1606 */
1607 private static void checkSystemOrRoot(String message) {
1608 final int uid = Binder.getCallingUid();
1609 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1610 throw new SecurityException("Only system may: " + message);
1611 }
1612 }
1613
Fyodor Kupolov82402752015-10-28 14:54:51 -07001614 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001615 try {
1616 File dir = new File(mUsersDir, Integer.toString(info.id));
1617 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001618 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001619 if (!dir.exists()) {
1620 dir.mkdir();
1621 FileUtils.setPermissions(
1622 dir.getPath(),
1623 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1624 -1, -1);
1625 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001626 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001627 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001628 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001629 info.iconPath = file.getAbsolutePath();
1630 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001631 try {
1632 os.close();
1633 } catch (IOException ioe) {
1634 // What the ... !
1635 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001636 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001637 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001638 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001639 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001640 }
1641
Amith Yamasani0b285492011-04-14 17:35:23 -07001642 /**
1643 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1644 * cache it elsewhere.
1645 * @return the array of user ids.
1646 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001647 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001648 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001649 return mUserIds;
1650 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001651 }
1652
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001653 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001654 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001655 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656 return;
1657 }
1658 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001659 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001660 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001661 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001663 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001664 int type;
1665 while ((type = parser.next()) != XmlPullParser.START_TAG
1666 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001667 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001668 }
1669
1670 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001671 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001672 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001673 return;
1674 }
1675
Amith Yamasani2a003292012-08-14 18:25:45 -07001676 mNextSerialNumber = -1;
1677 if (parser.getName().equals(TAG_USERS)) {
1678 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1679 if (lastSerialNumber != null) {
1680 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1681 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001682 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1683 if (versionNumber != null) {
1684 mUserVersion = Integer.parseInt(versionNumber);
1685 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001686 }
1687
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001688 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1689
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001690 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301691 if (type == XmlPullParser.START_TAG) {
1692 final String name = parser.getName();
1693 if (name.equals(TAG_USER)) {
1694 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001695
Amith Yamasani12747872015-12-07 14:19:49 -08001696 UserData userData = readUserLP(Integer.parseInt(id));
1697
1698 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001699 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001700 mUsers.put(userData.info.id, userData);
1701 if (mNextSerialNumber < 0
1702 || mNextSerialNumber <= userData.info.id) {
1703 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001704 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301705 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001706 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301707 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001708 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1709 && type != XmlPullParser.END_TAG) {
1710 if (type == XmlPullParser.START_TAG) {
1711 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001712 synchronized (mGuestRestrictions) {
1713 UserRestrictionsUtils
1714 .readRestrictions(parser, mGuestRestrictions);
1715 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1717 ) {
1718 UserRestrictionsUtils.readRestrictions(parser,
1719 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001720 }
1721 break;
1722 }
1723 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001724 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1725 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1726 if (ownerUserId != null) {
1727 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1728 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001729 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001730 }
1731 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001732 synchronized (mRestrictionsLock) {
1733 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1734 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001735 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001736 upgradeIfNecessaryLP();
1737 } catch (IOException | XmlPullParserException e) {
1738 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001739 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001740 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001741 }
1742 }
1743
Amith Yamasani6f34b412012-10-22 18:19:27 -07001744 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001745 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001746 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001747 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001748 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001749 int userVersion = mUserVersion;
1750 if (userVersion < 1) {
1751 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001752 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1753 if ("Primary".equals(userData.info.name)) {
1754 userData.info.name =
1755 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1756 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001757 }
1758 userVersion = 1;
1759 }
1760
Amith Yamasanibc9625052012-11-15 14:39:18 -08001761 if (userVersion < 2) {
1762 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001763 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1764 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1765 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1766 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001767 }
1768 userVersion = 2;
1769 }
1770
Amith Yamasani350962c2013-08-06 11:18:53 -07001771
Amith Yamasani5e486f52013-08-07 11:06:44 -07001772 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001773 userVersion = 4;
1774 }
1775
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001776 if (userVersion < 5) {
1777 initDefaultGuestRestrictions();
1778 userVersion = 5;
1779 }
1780
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001781 if (userVersion < 6) {
1782 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001783 synchronized (mUsersLock) {
1784 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001785 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001786 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001787 if (!splitSystemUser && userData.info.isRestricted()
1788 && (userData.info.restrictedProfileParentId
1789 == UserInfo.NO_PROFILE_GROUP_ID)) {
1790 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1791 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001792 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001793 }
1794 }
1795 userVersion = 6;
1796 }
1797
Amith Yamasani6f34b412012-10-22 18:19:27 -07001798 if (userVersion < USER_VERSION) {
1799 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1800 + USER_VERSION);
1801 } else {
1802 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001803
1804 if (originalVersion < mUserVersion) {
1805 writeUserListLP();
1806 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001807 }
1808 }
1809
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001810 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001811 int flags = UserInfo.FLAG_INITIALIZED;
1812 // In split system user mode, the admin and primary flags are assigned to the first human
1813 // user.
1814 if (!UserManager.isSplitSystemUser()) {
1815 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1816 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001817 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001818 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001819 UserData userData = new UserData();
1820 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001821 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001822 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001823 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001824 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001825 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001826
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001827 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001828 try {
1829 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1830 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1831 for (String userRestriction : defaultFirstUserRestrictions) {
1832 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1833 restrictions.putBoolean(userRestriction, true);
1834 }
1835 }
1836 } catch (Resources.NotFoundException e) {
1837 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1838 }
1839
Makoto Onuki068c54a2015-10-13 14:34:03 -07001840 synchronized (mRestrictionsLock) {
1841 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1842 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001843
Fyodor Kupolov82402752015-10-28 14:54:51 -07001844 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001845 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001846
Amith Yamasani12747872015-12-07 14:19:49 -08001847 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001848 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001849 }
1850
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001851 private String getOwnerName() {
1852 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1853 }
1854
Amith Yamasani12747872015-12-07 14:19:49 -08001855 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001856 if (DBG) {
1857 debug("scheduleWriteUser");
1858 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001859 // No need to wrap it within a lock -- worst case, we'll just post the same message
1860 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001861 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1862 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001863 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1864 }
1865 }
1866
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001867 /*
1868 * Writes the user file in this format:
1869 *
1870 * <user flags="20039023" id="0">
1871 * <name>Primary</name>
1872 * </user>
1873 */
Amith Yamasani12747872015-12-07 14:19:49 -08001874 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001875 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001876 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001877 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001878 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001879 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001880 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001881 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001882 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1883
1884 // XmlSerializer serializer = XmlUtils.serializerInstance();
1885 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001886 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001887 serializer.startDocument(null, true);
1888 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1889
Amith Yamasani12747872015-12-07 14:19:49 -08001890 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001891 serializer.startTag(null, TAG_USER);
1892 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001893 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001894 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001895 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1896 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1897 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001898 if (userInfo.lastLoggedInFingerprint != null) {
1899 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1900 userInfo.lastLoggedInFingerprint);
1901 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001902 if (userInfo.iconPath != null) {
1903 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1904 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001905 if (userInfo.partial) {
1906 serializer.attribute(null, ATTR_PARTIAL, "true");
1907 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001908 if (userInfo.guestToRemove) {
1909 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1910 }
Kenny Guy2a764942014-04-02 13:29:20 +01001911 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1912 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1913 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001914 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001915 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1916 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1917 Integer.toString(userInfo.restrictedProfileParentId));
1918 }
Amith Yamasani12747872015-12-07 14:19:49 -08001919 // Write seed data
1920 if (userData.persistSeedData) {
1921 if (userData.seedAccountName != null) {
1922 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1923 }
1924 if (userData.seedAccountType != null) {
1925 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1926 }
1927 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001928 if (userInfo.name != null) {
1929 serializer.startTag(null, TAG_NAME);
1930 serializer.text(userInfo.name);
1931 serializer.endTag(null, TAG_NAME);
1932 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001933 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001934 UserRestrictionsUtils.writeRestrictions(serializer,
1935 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1936 UserRestrictionsUtils.writeRestrictions(serializer,
1937 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1938 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001939 }
Amith Yamasani12747872015-12-07 14:19:49 -08001940
1941 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001942 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001943 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001944 serializer.endTag(null, TAG_ACCOUNT);
1945 }
1946
Amith Yamasani12747872015-12-07 14:19:49 -08001947 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1948 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1949 userData.seedAccountOptions.saveToXml(serializer);
1950 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1951 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001952 serializer.endTag(null, TAG_USER);
1953
1954 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001955 userFile.finishWrite(fos);
1956 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001957 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001958 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001959 }
1960 }
1961
1962 /*
1963 * Writes the user list file in this format:
1964 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001965 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001966 * <user id="0"></user>
1967 * <user id="2"></user>
1968 * </users>
1969 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001970 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001971 if (DBG) {
1972 debug("writeUserList");
1973 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001974 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001975 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001976 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001977 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001978 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1979
1980 // XmlSerializer serializer = XmlUtils.serializerInstance();
1981 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001982 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001983 serializer.startDocument(null, true);
1984 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1985
1986 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001987 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001988 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001989
Adam Lesinskieddeb492014-09-08 17:50:03 -07001990 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001991 synchronized (mGuestRestrictions) {
1992 UserRestrictionsUtils
1993 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1994 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301995 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001996 synchronized (mRestrictionsLock) {
1997 UserRestrictionsUtils.writeRestrictions(serializer,
1998 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1999 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002000 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
2001 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
2002 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002003 int[] userIdsToWrite;
2004 synchronized (mUsersLock) {
2005 userIdsToWrite = new int[mUsers.size()];
2006 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002007 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002008 userIdsToWrite[i] = user.id;
2009 }
2010 }
2011 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002012 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002013 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002014 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002015 }
2016
2017 serializer.endTag(null, TAG_USERS);
2018
2019 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002020 userListFile.finishWrite(fos);
2021 } catch (Exception e) {
2022 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002023 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002024 }
2025 }
2026
Amith Yamasani12747872015-12-07 14:19:49 -08002027 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002028 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002029 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002030 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002031 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002032 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002033 long creationTime = 0L;
2034 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002035 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002036 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002037 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002038 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002039 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002040 boolean persistSeedData = false;
2041 String seedAccountName = null;
2042 String seedAccountType = null;
2043 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002044 Bundle baseRestrictions = new Bundle();
2045 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002046
2047 FileInputStream fis = null;
2048 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002049 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002050 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002051 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002052 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002053 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002054 int type;
2055 while ((type = parser.next()) != XmlPullParser.START_TAG
2056 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002057 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002058 }
2059
2060 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002061 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002062 return null;
2063 }
2064
2065 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002066 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2067 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002068 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002069 return null;
2070 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002071 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2072 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002073 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002074 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2075 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002076 lastLoggedInFingerprint = parser.getAttributeValue(null,
2077 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002078 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2079 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002080 restrictedProfileParentId = readIntAttribute(parser,
2081 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002082 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2083 if ("true".equals(valueString)) {
2084 partial = true;
2085 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002086 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2087 if ("true".equals(valueString)) {
2088 guestToRemove = true;
2089 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002090
Amith Yamasani12747872015-12-07 14:19:49 -08002091 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2092 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2093 if (seedAccountName != null || seedAccountType != null) {
2094 persistSeedData = true;
2095 }
2096
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002097 int outerDepth = parser.getDepth();
2098 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2099 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2100 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2101 continue;
2102 }
2103 String tag = parser.getName();
2104 if (TAG_NAME.equals(tag)) {
2105 type = parser.next();
2106 if (type == XmlPullParser.TEXT) {
2107 name = parser.getText();
2108 }
2109 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002110 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2111 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2112 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002113 } else if (TAG_ACCOUNT.equals(tag)) {
2114 type = parser.next();
2115 if (type == XmlPullParser.TEXT) {
2116 account = parser.getText();
2117 }
Amith Yamasani12747872015-12-07 14:19:49 -08002118 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2119 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2120 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002121 }
2122 }
2123 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002124
Amith Yamasani12747872015-12-07 14:19:49 -08002125 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002126 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002127 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002128 userInfo.creationTime = creationTime;
2129 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002130 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002131 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002132 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002133 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002134 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002135
2136 // Create the UserData object that's internal to this class
2137 UserData userData = new UserData();
2138 userData.info = userInfo;
2139 userData.account = account;
2140 userData.seedAccountName = seedAccountName;
2141 userData.seedAccountType = seedAccountType;
2142 userData.persistSeedData = persistSeedData;
2143 userData.seedAccountOptions = seedAccountOptions;
2144
Makoto Onuki068c54a2015-10-13 14:34:03 -07002145 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002146 mBaseUserRestrictions.put(id, baseRestrictions);
2147 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002148 }
Amith Yamasani12747872015-12-07 14:19:49 -08002149 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002150 } catch (IOException ioe) {
2151 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002152 } finally {
2153 if (fis != null) {
2154 try {
2155 fis.close();
2156 } catch (IOException e) {
2157 }
2158 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002159 }
2160 return null;
2161 }
2162
Amith Yamasani920ace02012-09-20 22:15:37 -07002163 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2164 String valueString = parser.getAttributeValue(null, attr);
2165 if (valueString == null) return defaultValue;
2166 try {
2167 return Integer.parseInt(valueString);
2168 } catch (NumberFormatException nfe) {
2169 return defaultValue;
2170 }
2171 }
2172
2173 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2174 String valueString = parser.getAttributeValue(null, attr);
2175 if (valueString == null) return defaultValue;
2176 try {
2177 return Long.parseLong(valueString);
2178 } catch (NumberFormatException nfe) {
2179 return defaultValue;
2180 }
2181 }
2182
Amith Yamasanib82add22013-07-09 11:24:44 -07002183 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002184 * Removes the app restrictions file for a specific package and user id, if it exists.
2185 */
2186 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2187 synchronized (mPackagesLock) {
2188 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002189 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002190 if (resFile.exists()) {
2191 resFile.delete();
2192 }
2193 }
2194 }
2195
Kenny Guya52dc3e2014-02-11 15:33:14 +00002196 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002197 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002198 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002199 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002200 }
2201
Amith Yamasani258848d2012-08-10 17:06:33 -07002202 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002203 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002204 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002205 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002206 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002207
Jessica Hummelbe81c802014-04-22 15:49:22 +01002208 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002209 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002210 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2211 return null;
2212 }
phweisse9c44062016-02-10 12:57:38 +01002213 return createUserInternalUnchecked(name, flags, parentId);
2214 }
2215
2216 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002217 if (ActivityManager.isLowRamDeviceStatic()) {
2218 return null;
2219 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002220 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002221 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002222 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002223 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002224 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002225 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002226 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002227 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002228 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002229 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002230 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002231 if (parentId != UserHandle.USER_NULL) {
2232 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002233 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002234 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002235 if (parent == null) return null;
2236 }
2237 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2238 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2239 return null;
2240 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002241 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2242 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002243 // been reached, cannot add a user.
2244 return null;
2245 }
2246 // If we're adding a guest and there already exists one, bail.
2247 if (isGuest && findCurrentGuestUser() != null) {
2248 return null;
2249 }
2250 // In legacy mode, restricted profile's parent can only be the owner user
2251 if (isRestricted && !UserManager.isSplitSystemUser()
2252 && (parentId != UserHandle.USER_SYSTEM)) {
2253 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2254 return null;
2255 }
2256 if (isRestricted && UserManager.isSplitSystemUser()) {
2257 if (parent == null) {
2258 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2259 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002260 return null;
2261 }
Amith Yamasani12747872015-12-07 14:19:49 -08002262 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002263 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2264 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002265 return null;
2266 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002267 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002268 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2269 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002270 Log.e(LOG_TAG,
2271 "Ephemeral users are supported on split-system-user systems only.");
2272 return null;
2273 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002274 // In split system user mode, we assign the first human user the primary flag.
2275 // And if there is no device owner, we also assign the admin flag to primary user.
2276 if (UserManager.isSplitSystemUser()
2277 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2278 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002279 synchronized (mUsersLock) {
2280 if (!mIsDeviceManaged) {
2281 flags |= UserInfo.FLAG_ADMIN;
2282 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002283 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002284 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002285
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002286 userId = getNextAvailableId();
2287 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002288 boolean ephemeralGuests = Resources.getSystem()
2289 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002290
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002291 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002292 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2293 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2294 || (parent != null && parent.info.isEphemeral())) {
2295 flags |= UserInfo.FLAG_EPHEMERAL;
2296 }
2297
2298 userInfo = new UserInfo(userId, name, null, flags);
2299 userInfo.serialNumber = mNextSerialNumber++;
2300 long now = System.currentTimeMillis();
2301 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2302 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002303 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002304 userData = new UserData();
2305 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002306 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002307 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002308 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002309 writeUserListLP();
2310 if (parent != null) {
2311 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002312 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2313 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002314 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002315 }
Amith Yamasani12747872015-12-07 14:19:49 -08002316 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002317 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002318 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2319 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002320 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002321 }
Amith Yamasani12747872015-12-07 14:19:49 -08002322 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002323 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002324 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002325 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002326 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002327 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002328 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002329 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002330 mPm.createNewUser(userId);
2331 userInfo.partial = false;
2332 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002333 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002334 }
2335 updateUserIds();
2336 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002337 if (isGuest) {
2338 synchronized (mGuestRestrictions) {
2339 restrictions.putAll(mGuestRestrictions);
2340 }
2341 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002342 synchronized (mRestrictionsLock) {
2343 mBaseUserRestrictions.append(userId, restrictions);
2344 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002345 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002346 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2347 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2348 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2349 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002350 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002351 } finally {
2352 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002353 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002354 return userInfo;
2355 }
2356
Amith Yamasani0b285492011-04-14 17:35:23 -07002357 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002358 * @hide
2359 */
Amith Yamasani12747872015-12-07 14:19:49 -08002360 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002361 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002362 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002363 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2364 if (user == null) {
2365 return null;
2366 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002367 long identity = Binder.clearCallingIdentity();
2368 try {
2369 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2370 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2371 // the putIntForUser() will fail.
2372 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2373 android.provider.Settings.Secure.LOCATION_MODE,
2374 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2375 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2376 } finally {
2377 Binder.restoreCallingIdentity(identity);
2378 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002379 return user;
2380 }
2381
2382 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002383 * Find the current guest user. If the Guest user is partial,
2384 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002385 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002386 private UserInfo findCurrentGuestUser() {
2387 synchronized (mUsersLock) {
2388 final int size = mUsers.size();
2389 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002390 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002391 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2392 return user;
2393 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002394 }
2395 }
2396 return null;
2397 }
2398
2399 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002400 * Mark this guest user for deletion to allow us to create another guest
2401 * and switch to that user before actually removing this guest.
2402 * @param userHandle the userid of the current guest
2403 * @return whether the user could be marked for deletion
2404 */
Amith Yamasani12747872015-12-07 14:19:49 -08002405 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002406 public boolean markGuestForDeletion(int userHandle) {
2407 checkManageUsersPermission("Only the system can remove users");
2408 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2409 UserManager.DISALLOW_REMOVE_USER, false)) {
2410 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2411 return false;
2412 }
2413
2414 long ident = Binder.clearCallingIdentity();
2415 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002416 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002417 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002418 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002419 userData = mUsers.get(userHandle);
2420 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 return false;
2422 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002423 }
Amith Yamasani12747872015-12-07 14:19:49 -08002424 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002425 return false;
2426 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002427 // We set this to a guest user that is to be removed. This is a temporary state
2428 // where we are allowed to add new Guest users, even if this one is still not
2429 // removed. This user will still show up in getUserInfo() calls.
2430 // If we don't get around to removing this Guest user, it will be purged on next
2431 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002432 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002433 // Mark it as disabled, so that it isn't returned any more when
2434 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002435 userData.info.flags |= UserInfo.FLAG_DISABLED;
2436 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002437 }
2438 } finally {
2439 Binder.restoreCallingIdentity(ident);
2440 }
2441 return true;
2442 }
2443
2444 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002445 * Removes a user and all data directories created for that user. This method should be called
2446 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002447 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002448 */
Amith Yamasani12747872015-12-07 14:19:49 -08002449 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002450 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002451 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002452 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2453 UserManager.DISALLOW_REMOVE_USER, false)) {
2454 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2455 return false;
2456 }
2457
Kenny Guyee58b4f2014-05-23 15:19:53 +01002458 long ident = Binder.clearCallingIdentity();
2459 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002460 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002461 int currentUser = ActivityManager.getCurrentUser();
2462 if (currentUser == userHandle) {
2463 Log.w(LOG_TAG, "Current user cannot be removed");
2464 return false;
2465 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002466 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002467 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002468 userData = mUsers.get(userHandle);
2469 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002470 return false;
2471 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002472
Fyodor Kupolov82402752015-10-28 14:54:51 -07002473 // We remember deleted user IDs to prevent them from being
2474 // reused during the current boot; they can still be reused
2475 // after a reboot.
2476 mRemovingUserIds.put(userHandle, true);
2477 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002478
Kenny Guyee58b4f2014-05-23 15:19:53 +01002479 try {
2480 mAppOpsService.removeUser(userHandle);
2481 } catch (RemoteException e) {
2482 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2483 }
2484 // Set this to a partially created user, so that the user will be purged
2485 // on next startup, in case the runtime stops now before stopping and
2486 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002487 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002488 // Mark it as disabled, so that it isn't returned any more when
2489 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002490 userData.info.flags |= UserInfo.FLAG_DISABLED;
2491 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002492 }
2493
Amith Yamasani12747872015-12-07 14:19:49 -08002494 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2495 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002496 // Send broadcast to notify system that the user removed was a
2497 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002498 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002499 }
2500
2501 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2502 int res;
2503 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002504 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2505 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002506 @Override
2507 public void userStopped(int userId) {
2508 finishRemoveUser(userId);
2509 }
2510 @Override
2511 public void userStopAborted(int userId) {
2512 }
2513 });
2514 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002515 return false;
2516 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002517 return res == ActivityManager.USER_OP_SUCCESS;
2518 } finally {
2519 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002520 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002521 }
2522
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002523 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002524 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002525 // Let other services shutdown any activity and clean up their state before completely
2526 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002527 long ident = Binder.clearCallingIdentity();
2528 try {
2529 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2530 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002531 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2532 android.Manifest.permission.MANAGE_USERS,
2533
2534 new BroadcastReceiver() {
2535 @Override
2536 public void onReceive(Context context, Intent intent) {
2537 if (DBG) {
2538 Slog.i(LOG_TAG,
2539 "USER_REMOVED broadcast sent, cleaning up user data "
2540 + userHandle);
2541 }
2542 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002543 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002544 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002545 // Clean up any ActivityManager state
2546 LocalServices.getService(ActivityManagerInternal.class)
2547 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002548 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002549 }
2550 }.start();
2551 }
2552 },
2553
2554 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002555 } finally {
2556 Binder.restoreCallingIdentity(ident);
2557 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002558 }
2559
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002560 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002561 try {
2562 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2563 } catch (IllegalStateException e) {
2564 // This may be simply because the user was partially created.
2565 Slog.i(LOG_TAG,
2566 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2567 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002568
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002569 // Cleanup gatekeeper secure user id
2570 try {
2571 final IGateKeeperService gk = GateKeeper.getService();
2572 if (gk != null) {
2573 gk.clearSecureUserId(userHandle);
2574 }
2575 } catch (Exception ex) {
2576 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2577 }
2578
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002579 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002580 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002581
2582 // Clean up all data before removing metadata
2583 mPm.destroyUserData(userHandle,
2584 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2585
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002586 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002587 synchronized (mUsersLock) {
2588 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002589 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002590 }
2591 synchronized (mUserStates) {
2592 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002593 }
2594 synchronized (mRestrictionsLock) {
2595 mBaseUserRestrictions.remove(userHandle);
2596 mAppliedUserRestrictions.remove(userHandle);
2597 mCachedEffectiveUserRestrictions.remove(userHandle);
2598 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002599 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002600 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002601 synchronized (mPackagesLock) {
2602 writeUserListLP();
2603 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002604 // Remove user file
2605 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2606 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002607 updateUserIds();
Amith Yamasani61f57372012-08-31 12:12:28 -07002608 }
2609
Kenny Guyf8d3a232014-05-15 16:09:52 +01002610 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002611 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002612 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2613 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002614 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002615 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002616 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002617 }
2618
Amith Yamasani2a003292012-08-14 18:25:45 -07002619 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002620 public Bundle getApplicationRestrictions(String packageName) {
2621 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2622 }
2623
2624 @Override
2625 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002626 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002627 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002628 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002629 }
2630 synchronized (mPackagesLock) {
2631 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002632 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002633 }
2634 }
2635
2636 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002637 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002638 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002639 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002640 if (restrictions != null) {
2641 restrictions.setDefusable(true);
2642 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002643 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002644 if (restrictions == null || restrictions.isEmpty()) {
2645 cleanAppRestrictionsForPackage(packageName, userId);
2646 } else {
2647 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002648 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002649 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002650 }
Robin Lee66e5d962014-04-09 16:44:21 +01002651
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002652 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2653 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2654 changeIntent.setPackage(packageName);
2655 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2656 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002657 }
2658
2659 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002660 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002661 try {
2662 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002663 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002664 } catch (NameNotFoundException nnfe) {
2665 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002666 } finally {
2667 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002668 }
2669 }
2670
Fyodor Kupolov82402752015-10-28 14:54:51 -07002671 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002672 AtomicFile restrictionsFile =
2673 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2674 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002675 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002676 }
2677
2678 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002679 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002680 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002681 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002682 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002683 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002684 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002685
2686 FileInputStream fis = null;
2687 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002688 fis = restrictionsFile.openRead();
2689 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002690 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002691 XmlUtils.nextElement(parser);
2692 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002693 Slog.e(LOG_TAG, "Unable to read restrictions file "
2694 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002695 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002696 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002697 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2698 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002699 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002700 } catch (IOException|XmlPullParserException e) {
2701 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002702 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002703 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002704 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002705 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002706 }
2707
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002708 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2709 XmlPullParser parser) throws XmlPullParserException, IOException {
2710 int type = parser.getEventType();
2711 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2712 String key = parser.getAttributeValue(null, ATTR_KEY);
2713 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2714 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2715 if (multiple != null) {
2716 values.clear();
2717 int count = Integer.parseInt(multiple);
2718 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2719 if (type == XmlPullParser.START_TAG
2720 && parser.getName().equals(TAG_VALUE)) {
2721 values.add(parser.nextText().trim());
2722 count--;
2723 }
2724 }
2725 String [] valueStrings = new String[values.size()];
2726 values.toArray(valueStrings);
2727 restrictions.putStringArray(key, valueStrings);
2728 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2729 restrictions.putBundle(key, readBundleEntry(parser, values));
2730 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2731 final int outerDepth = parser.getDepth();
2732 ArrayList<Bundle> bundleList = new ArrayList<>();
2733 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2734 Bundle childBundle = readBundleEntry(parser, values);
2735 bundleList.add(childBundle);
2736 }
2737 restrictions.putParcelableArray(key,
2738 bundleList.toArray(new Bundle[bundleList.size()]));
2739 } else {
2740 String value = parser.nextText().trim();
2741 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2742 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2743 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2744 restrictions.putInt(key, Integer.parseInt(value));
2745 } else {
2746 restrictions.putString(key, value);
2747 }
2748 }
2749 }
2750 }
2751
2752 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2753 throws IOException, XmlPullParserException {
2754 Bundle childBundle = new Bundle();
2755 final int outerDepth = parser.getDepth();
2756 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2757 readEntry(childBundle, values, parser);
2758 }
2759 return childBundle;
2760 }
2761
Fyodor Kupolov82402752015-10-28 14:54:51 -07002762 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002763 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002764 AtomicFile restrictionsFile = new AtomicFile(
2765 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002766 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002767 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002768 }
2769
2770 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002771 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002772 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002773 try {
2774 fos = restrictionsFile.startWrite();
2775 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2776
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002777 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002778 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002779 serializer.startDocument(null, true);
2780 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2781
2782 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002783 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002784 serializer.endTag(null, TAG_RESTRICTIONS);
2785
2786 serializer.endDocument();
2787 restrictionsFile.finishWrite(fos);
2788 } catch (Exception e) {
2789 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002790 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2791 }
2792 }
2793
2794 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2795 throws IOException {
2796 for (String key : restrictions.keySet()) {
2797 Object value = restrictions.get(key);
2798 serializer.startTag(null, TAG_ENTRY);
2799 serializer.attribute(null, ATTR_KEY, key);
2800
2801 if (value instanceof Boolean) {
2802 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2803 serializer.text(value.toString());
2804 } else if (value instanceof Integer) {
2805 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2806 serializer.text(value.toString());
2807 } else if (value == null || value instanceof String) {
2808 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2809 serializer.text(value != null ? (String) value : "");
2810 } else if (value instanceof Bundle) {
2811 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2812 writeBundle((Bundle) value, serializer);
2813 } else if (value instanceof Parcelable[]) {
2814 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2815 Parcelable[] array = (Parcelable[]) value;
2816 for (Parcelable parcelable : array) {
2817 if (!(parcelable instanceof Bundle)) {
2818 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2819 }
2820 serializer.startTag(null, TAG_ENTRY);
2821 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2822 writeBundle((Bundle) parcelable, serializer);
2823 serializer.endTag(null, TAG_ENTRY);
2824 }
2825 } else {
2826 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2827 String[] values = (String[]) value;
2828 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2829 for (String choice : values) {
2830 serializer.startTag(null, TAG_VALUE);
2831 serializer.text(choice != null ? choice : "");
2832 serializer.endTag(null, TAG_VALUE);
2833 }
2834 }
2835 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002836 }
2837 }
2838
2839 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002840 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002841 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002842 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002843 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002844 }
2845 }
2846
2847 @Override
2848 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002849 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002850 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002851 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002852 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002853 }
2854 // Not found
2855 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002856 }
2857 }
2858
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002859 @Override
2860 public long getUserCreationTime(int userHandle) {
2861 int callingUserId = UserHandle.getCallingUserId();
2862 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002863 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002864 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002865 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002866 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002867 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002868 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002869 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002870 }
2871 }
2872 }
2873 if (userInfo == null) {
2874 throw new SecurityException("userHandle can only be the calling user or a managed "
2875 + "profile associated with this user");
2876 }
2877 return userInfo.creationTime;
2878 }
2879
Amith Yamasani0b285492011-04-14 17:35:23 -07002880 /**
2881 * Caches the list of user ids in an array, adjusting the array size when necessary.
2882 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002883 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002884 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002885 synchronized (mUsersLock) {
2886 final int userSize = mUsers.size();
2887 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002888 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002889 num++;
2890 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002891 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002892 final int[] newUsers = new int[num];
2893 int n = 0;
2894 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002895 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002896 newUsers[n++] = mUsers.keyAt(i);
2897 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002898 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002899 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002900 }
2901 }
2902
2903 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002904 * Called right before a user is started. This gives us a chance to prepare
2905 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002906 */
2907 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002908 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002909 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002910 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002911
2912 if (userId != UserHandle.USER_SYSTEM) {
2913 synchronized (mRestrictionsLock) {
2914 applyUserRestrictionsLR(userId);
2915 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002916 }
2917 }
2918
2919 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002920 * Called right before a user is unlocked. This gives us a chance to prepare
2921 * app storage.
2922 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002923 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002924 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002925 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002926 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002927 }
2928
2929 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002930 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002931 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002932 * @param userId the user that was just foregrounded
2933 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002934 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002935 UserData userData = getUserDataNoChecks(userId);
2936 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002937 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2938 return;
2939 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002940
2941 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002942 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002943 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002944 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002945 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2946 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002947 }
2948
2949 /**
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 {
Yi Kongc44a6e02016-08-27 12:16:44 +01003027 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3028 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003029 try {
3030 return Integer.parseInt(serial);
3031 } catch (NumberFormatException e) {
3032 throw new IOException("Bad serial number: " + serial);
3033 }
3034 } catch (ErrnoException e) {
3035 if (e.errno == OsConstants.ENODATA) {
3036 return -1;
3037 } else {
3038 throw e.rethrowAsIOException();
3039 }
3040 }
3041 }
3042
Amith Yamasani920ace02012-09-20 22:15:37 -07003043 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003044 public void setSeedAccountData(int userId, String accountName, String accountType,
3045 PersistableBundle accountOptions, boolean persist) {
3046 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3047 synchronized (mPackagesLock) {
3048 final UserData userData;
3049 synchronized (mUsersLock) {
3050 userData = getUserDataLU(userId);
3051 if (userData == null) {
3052 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3053 return;
3054 }
3055 userData.seedAccountName = accountName;
3056 userData.seedAccountType = accountType;
3057 userData.seedAccountOptions = accountOptions;
3058 userData.persistSeedData = persist;
3059 }
3060 if (persist) {
3061 writeUserLP(userData);
3062 }
3063 }
3064 }
3065
3066 @Override
3067 public String getSeedAccountName() throws RemoteException {
3068 checkManageUsersPermission("Cannot get seed account information");
3069 synchronized (mUsersLock) {
3070 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3071 return userData.seedAccountName;
3072 }
3073 }
3074
3075 @Override
3076 public String getSeedAccountType() throws RemoteException {
3077 checkManageUsersPermission("Cannot get seed account information");
3078 synchronized (mUsersLock) {
3079 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3080 return userData.seedAccountType;
3081 }
3082 }
3083
3084 @Override
3085 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3086 checkManageUsersPermission("Cannot get seed account information");
3087 synchronized (mUsersLock) {
3088 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3089 return userData.seedAccountOptions;
3090 }
3091 }
3092
3093 @Override
3094 public void clearSeedAccountData() throws RemoteException {
3095 checkManageUsersPermission("Cannot clear seed account information");
3096 synchronized (mPackagesLock) {
3097 UserData userData;
3098 synchronized (mUsersLock) {
3099 userData = getUserDataLU(UserHandle.getCallingUserId());
3100 if (userData == null) return;
3101 userData.clearSeedAccountData();
3102 }
3103 writeUserLP(userData);
3104 }
3105 }
3106
3107 @Override
3108 public boolean someUserHasSeedAccount(String accountName, String accountType)
3109 throws RemoteException {
3110 checkManageUsersPermission("Cannot check seed account information");
3111 synchronized (mUsersLock) {
3112 final int userSize = mUsers.size();
3113 for (int i = 0; i < userSize; i++) {
3114 final UserData data = mUsers.valueAt(i);
3115 if (data.info.isInitialized()) continue;
3116 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3117 continue;
3118 }
3119 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3120 continue;
3121 }
3122 return true;
3123 }
3124 }
3125 return false;
3126 }
3127
3128 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003129 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3130 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3131 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3132 }
3133
3134 int onShellCommand(Shell shell, String cmd) {
3135 if (cmd == null) {
3136 return shell.handleDefaultCommands(cmd);
3137 }
3138
3139 final PrintWriter pw = shell.getOutPrintWriter();
3140 try {
3141 switch(cmd) {
3142 case "list":
3143 return runList(pw);
3144 }
3145 } catch (RemoteException e) {
3146 pw.println("Remote exception: " + e);
3147 }
3148 return -1;
3149 }
3150
3151 private int runList(PrintWriter pw) throws RemoteException {
3152 final IActivityManager am = ActivityManagerNative.getDefault();
3153 final List<UserInfo> users = getUsers(false);
3154 if (users == null) {
3155 pw.println("Error: couldn't get users");
3156 return 1;
3157 } else {
3158 pw.println("Users:");
3159 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003160 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003161 pw.println("\t" + users.get(i).toString() + running);
3162 }
3163 return 0;
3164 }
3165 }
3166
3167 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003168 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3169 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3170 != PackageManager.PERMISSION_GRANTED) {
3171 pw.println("Permission Denial: can't dump UserManager from from pid="
3172 + Binder.getCallingPid()
3173 + ", uid=" + Binder.getCallingUid()
3174 + " without permission "
3175 + android.Manifest.permission.DUMP);
3176 return;
3177 }
3178
3179 long now = System.currentTimeMillis();
3180 StringBuilder sb = new StringBuilder();
3181 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003182 synchronized (mUsersLock) {
3183 pw.println("Users:");
3184 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003185 UserData userData = mUsers.valueAt(i);
3186 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003187 continue;
3188 }
Amith Yamasani12747872015-12-07 14:19:49 -08003189 UserInfo userInfo = userData.info;
3190 final int userId = userInfo.id;
3191 pw.print(" "); pw.print(userInfo);
3192 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003193 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003194 pw.print(" <removing> ");
3195 }
Amith Yamasani12747872015-12-07 14:19:49 -08003196 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003197 pw.print(" <partial>");
3198 }
3199 pw.println();
3200 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003201 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003202 pw.println("<unknown>");
3203 } else {
3204 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003205 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003206 sb.append(" ago");
3207 pw.println(sb);
3208 }
3209 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003210 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003211 pw.println("<unknown>");
3212 } else {
3213 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003214 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003215 sb.append(" ago");
3216 pw.println(sb);
3217 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003218 pw.print(" Last logged in fingerprint: ");
3219 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003220 pw.print(" Has profile owner: ");
3221 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003222 pw.println(" Restrictions:");
3223 synchronized (mRestrictionsLock) {
3224 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003225 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003226 pw.println(" Device policy local restrictions:");
3227 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003228 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003229 pw.println(" Effective restrictions:");
3230 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003231 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003232 }
Amith Yamasani12747872015-12-07 14:19:49 -08003233
3234 if (userData.account != null) {
3235 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003236 pw.println();
3237 }
Amith Yamasani12747872015-12-07 14:19:49 -08003238
3239 if (userData.seedAccountName != null) {
3240 pw.print(" Seed account name: " + userData.seedAccountName);
3241 pw.println();
3242 if (userData.seedAccountType != null) {
3243 pw.print(" account type: " + userData.seedAccountType);
3244 pw.println();
3245 }
3246 if (userData.seedAccountOptions != null) {
3247 pw.print(" account options exist");
3248 pw.println();
3249 }
3250 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003251 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003252 }
Amith Yamasani12747872015-12-07 14:19:49 -08003253 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003254 pw.println(" Device policy global restrictions:");
3255 synchronized (mRestrictionsLock) {
3256 UserRestrictionsUtils
3257 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3258 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003259 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003260 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3261 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003262 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003263 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003264 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003265 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003266 synchronized (mUsersLock) {
3267 pw.println();
3268 pw.println(" Device managed: " + mIsDeviceManaged);
3269 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003270 synchronized (mUserStates) {
3271 pw.println(" Started users state: " + mUserStates);
3272 }
Amith Yamasani12747872015-12-07 14:19:49 -08003273 // Dump some capabilities
3274 pw.println();
3275 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3276 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003277 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3278 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003279 }
3280 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003281
3282 final class MainHandler extends Handler {
3283
3284 @Override
3285 public void handleMessage(Message msg) {
3286 switch (msg.what) {
3287 case WRITE_USER_MSG:
3288 removeMessages(WRITE_USER_MSG, msg.obj);
3289 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003290 int userId = ((UserData) msg.obj).info.id;
3291 UserData userData = getUserDataNoChecks(userId);
3292 if (userData != null) {
3293 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003294 }
3295 }
3296 }
3297 }
3298 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003299
3300 /**
3301 * @param userId
3302 * @return whether the user has been initialized yet
3303 */
3304 boolean isInitialized(int userId) {
3305 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3306 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003307
3308 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003309 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003310 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3311 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003312 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003313 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003314 }
3315
3316 @Override
3317 public Bundle getBaseUserRestrictions(int userId) {
3318 synchronized (mRestrictionsLock) {
3319 return mBaseUserRestrictions.get(userId);
3320 }
3321 }
3322
3323 @Override
3324 public void setBaseUserRestrictionsByDpmsForMigration(
3325 int userId, Bundle baseRestrictions) {
3326 synchronized (mRestrictionsLock) {
3327 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003328 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003329 }
3330
Amith Yamasani12747872015-12-07 14:19:49 -08003331 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003332 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003333 if (userData != null) {
3334 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003335 } else {
3336 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3337 }
3338 }
3339 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003340
3341 @Override
3342 public boolean getUserRestriction(int userId, String key) {
3343 return getUserRestrictions(userId).getBoolean(key);
3344 }
3345
3346 @Override
3347 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3348 synchronized (mUserRestrictionsListeners) {
3349 mUserRestrictionsListeners.add(listener);
3350 }
3351 }
3352
3353 @Override
3354 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3355 synchronized (mUserRestrictionsListeners) {
3356 mUserRestrictionsListeners.remove(listener);
3357 }
3358 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003359
3360 @Override
3361 public void setDeviceManaged(boolean isManaged) {
3362 synchronized (mUsersLock) {
3363 mIsDeviceManaged = isManaged;
3364 }
3365 }
3366
3367 @Override
3368 public void setUserManaged(int userId, boolean isManaged) {
3369 synchronized (mUsersLock) {
3370 mIsUserManaged.put(userId, isManaged);
3371 }
3372 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003373
3374 @Override
3375 public void setUserIcon(int userId, Bitmap bitmap) {
3376 long ident = Binder.clearCallingIdentity();
3377 try {
3378 synchronized (mPackagesLock) {
3379 UserData userData = getUserDataNoChecks(userId);
3380 if (userData == null || userData.info.partial) {
3381 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3382 return;
3383 }
3384 writeBitmapLP(userData.info, bitmap);
3385 writeUserLP(userData);
3386 }
3387 sendUserInfoChangedBroadcast(userId);
3388 } finally {
3389 Binder.restoreCallingIdentity(ident);
3390 }
3391 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003392
3393 @Override
3394 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3395 synchronized (mUsersLock) {
3396 mForceEphemeralUsers = forceEphemeralUsers;
3397 }
3398 }
3399
3400 @Override
3401 public void removeAllUsers() {
3402 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3403 // Remove the non-system users straight away.
3404 removeNonSystemUsers();
3405 } else {
3406 // Switch to the system user first and then remove the other users.
3407 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3408 @Override
3409 public void onReceive(Context context, Intent intent) {
3410 int userId =
3411 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3412 if (userId != UserHandle.USER_SYSTEM) {
3413 return;
3414 }
3415 mContext.unregisterReceiver(this);
3416 removeNonSystemUsers();
3417 }
3418 };
3419 IntentFilter userSwitchedFilter = new IntentFilter();
3420 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3421 mContext.registerReceiver(
3422 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3423
3424 // Switch to the system user.
3425 ActivityManager am =
3426 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3427 am.switchUser(UserHandle.USER_SYSTEM);
3428 }
3429 }
phweisse9c44062016-02-10 12:57:38 +01003430
3431 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003432 public void onEphemeralUserStop(int userId) {
3433 synchronized (mUsersLock) {
3434 UserInfo userInfo = getUserInfoLU(userId);
3435 if (userInfo != null && userInfo.isEphemeral()) {
3436 // Do not allow switching back to the ephemeral user again as the user is going
3437 // to be deleted.
3438 userInfo.flags |= UserInfo.FLAG_DISABLED;
3439 if (userInfo.isGuest()) {
3440 // Indicate that the guest will be deleted after it stops.
3441 userInfo.guestToRemove = true;
3442 }
3443 }
3444 }
3445 }
3446
3447 @Override
phweisse9c44062016-02-10 12:57:38 +01003448 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3449 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3450 // Keep this in sync with UserManager.createUser
3451 if (user != null && !user.isAdmin()) {
3452 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3453 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3454 }
3455 return user;
3456 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003457
3458 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003459 public boolean isUserRunning(int userId) {
3460 synchronized (mUserStates) {
3461 return mUserStates.get(userId, -1) >= 0;
3462 }
3463 }
3464
3465 @Override
3466 public void setUserState(int userId, int userState) {
3467 synchronized (mUserStates) {
3468 mUserStates.put(userId, userState);
3469 }
3470 }
3471
3472 @Override
3473 public void removeUserState(int userId) {
3474 synchronized (mUserStates) {
3475 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003476 }
3477 }
3478
3479 @Override
3480 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003481 synchronized (mUserStates) {
3482 int state = mUserStates.get(userId, -1);
3483 return (state == UserState.STATE_RUNNING_UNLOCKING)
3484 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003485 }
3486 }
Fyodor Kupolov7a1e6822016-12-05 13:23:28 -08003487
3488 @Override
3489 public boolean isUserUnlocked(int userId) {
3490 synchronized (mUserStates) {
3491 int state = mUserStates.get(userId, -1);
3492 return state == UserState.STATE_RUNNING_UNLOCKED;
3493 }
3494 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003495 }
3496
3497 /* Remove all the users except of the system one. */
3498 private void removeNonSystemUsers() {
3499 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3500 synchronized (mUsersLock) {
3501 final int userSize = mUsers.size();
3502 for (int i = 0; i < userSize; i++) {
3503 UserInfo ui = mUsers.valueAt(i).info;
3504 if (ui.id != UserHandle.USER_SYSTEM) {
3505 usersToRemove.add(ui);
3506 }
3507 }
3508 }
3509 for (UserInfo ui: usersToRemove) {
3510 removeUser(ui.id);
3511 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003512 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003513
3514 private class Shell extends ShellCommand {
3515 @Override
3516 public int onCommand(String cmd) {
3517 return onShellCommand(this, cmd);
3518 }
3519
3520 @Override
3521 public void onHelp() {
3522 final PrintWriter pw = getOutPrintWriter();
3523 pw.println("User manager (user) commands:");
3524 pw.println(" help");
3525 pw.println(" Print this help text.");
3526 pw.println("");
3527 pw.println(" list");
3528 pw.println(" Prints all users on the system.");
3529 }
3530 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003531
3532 private static void debug(String message) {
3533 Log.d(LOG_TAG, message +
3534 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3535 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003536}