blob: efd6f46fe95e9c7298789430e364f445ecc2c6d9 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000036import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.content.Context;
38import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010039import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010040import android.content.IntentSender;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000041import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070042import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080043import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070068import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080070import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010071import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070072import android.security.GateKeeper;
73import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070074import android.system.ErrnoException;
75import android.system.Os;
76import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070077import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080092import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070093import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070094import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000095import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070096import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070097import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000098import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070099import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100100
Jeff Sharkey47f71082016-02-01 17:03:54 -0700101import libcore.io.IoUtils;
102import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800103
104import org.xmlpull.v1.XmlPullParser;
105import org.xmlpull.v1.XmlPullParserException;
106import org.xmlpull.v1.XmlSerializer;
107
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108import java.io.BufferedOutputStream;
109import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700110import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.FileOutputStream;
114import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700115import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100116import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.util.ArrayList;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700118import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.util.List;
120
Makoto Onuki068c54a2015-10-13 14:34:03 -0700121/**
122 * Service for {@link UserManager}.
123 *
124 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700125 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800126 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700127 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
128 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
129 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700130 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700131public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700132
Amith Yamasani2a003292012-08-14 18:25:45 -0700133 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800134 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800135 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700136 // Can be used for manual testing of id recycling
137 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700138
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800140 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700142 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700144 private static final String ATTR_CREATION_TIME = "created";
145 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600146 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700147 private static final String ATTR_SERIAL_NO = "serialNumber";
148 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700149 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700150 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700151 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100152 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700153 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800154 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
155 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530156 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700158 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800159 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800160 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100161 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800162 private static final String TAG_ENTRY = "entry";
163 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800164 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800165 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700166 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800167 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700168
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700169 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
170 private static final String ATTR_TYPE_STRING = "s";
171 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700172 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700173 private static final String ATTR_TYPE_BUNDLE = "B";
174 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700175
Amith Yamasani0b285492011-04-14 17:35:23 -0700176 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700177 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700178 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100179 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700180
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800181 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700182 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800183
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700184 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
185 UserInfo.FLAG_MANAGED_PROFILE
186 | UserInfo.FLAG_EPHEMERAL
187 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700188 | UserInfo.FLAG_GUEST
189 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700190
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700191 @VisibleForTesting
192 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700193 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700194 @VisibleForTesting
195 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
196
197 // Max size of the queue of recently removed users
198 @VisibleForTesting
199 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700200
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700201 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700202
Amith Yamasani920ace02012-09-20 22:15:37 -0700203 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
204
Nicolas Prevotb8186812015-08-06 15:00:03 +0100205 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700206 // without first making sure that the rest of the framework is prepared for it.
207 private static final int MAX_MANAGED_PROFILES = 1;
208
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800209 static final int WRITE_USER_MSG = 1;
210 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530211
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700212 private static final String XATTR_SERIAL = "user.serial";
213
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800214 // Tron counters
215 private static final String TRON_GUEST_CREATED = "users_guest_created";
216 private static final String TRON_USER_CREATED = "users_user_created";
217
Dianne Hackborn4428e172012-08-24 17:43:05 -0700218 private final Context mContext;
219 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700220 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700221 // Short-term lock for internal state, when interaction/sync with PM is not required
222 private final Object mUsersLock = new Object();
223 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700224
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800225 private final Handler mHandler;
226
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700227 private final File mUsersDir;
228 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800230 private static final IBinder mUserRestriconToken = new Binder();
231
Makoto Onuki068c54a2015-10-13 14:34:03 -0700232 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800233 * User-related information that is used for persisting to flash. Only UserInfo is
234 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800235 */
Amith Yamasani12747872015-12-07 14:19:49 -0800236 private static class UserData {
237 // Basic user information and properties
238 UserInfo info;
239 // Account name used when there is a strong association between a user and an account
240 String account;
241 // Account information for seeding into a newly created user. This could also be
242 // used for login validation for an existing user, for updating their credentials.
243 // In the latter case, data may not need to be persisted as it is only valid for the
244 // current login session.
245 String seedAccountName;
246 String seedAccountType;
247 PersistableBundle seedAccountOptions;
248 // Whether to perist the seed account information to be available after a boot
249 boolean persistSeedData;
250
251 void clearSeedAccountData() {
252 seedAccountName = null;
253 seedAccountType = null;
254 seedAccountOptions = null;
255 persistSeedData = false;
256 }
257 }
258
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800259 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800260 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800261
262 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700263 * User restrictions set via UserManager. This doesn't include restrictions set by
264 * device owner / profile owners.
265 *
266 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
267 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
268 * maybe shared between {@link #mBaseUserRestrictions} and
269 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
270 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700271 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700272 */
273 @GuardedBy("mRestrictionsLock")
274 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
275
276 /**
277 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
278 * with device / profile owner restrictions. We'll initialize it lazily; use
279 * {@link #getEffectiveUserRestrictions} to access it.
280 *
281 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
282 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
283 * maybe shared between {@link #mBaseUserRestrictions} and
284 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
285 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700286 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700287 */
288 @GuardedBy("mRestrictionsLock")
289 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
290
Makoto Onuki4f160732015-10-27 17:15:38 -0700291 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800292 * User restrictions that have already been applied in
293 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
294 * that have changed since the last
295 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700296 */
297 @GuardedBy("mRestrictionsLock")
298 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
299
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800300 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800301 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
302 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800303 */
304 @GuardedBy("mRestrictionsLock")
305 private Bundle mDevicePolicyGlobalUserRestrictions;
306
307 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100308 * Id of the user that set global restrictions.
309 */
310 @GuardedBy("mRestrictionsLock")
311 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
312
313 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800314 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
315 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800316 */
317 @GuardedBy("mRestrictionsLock")
318 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
319
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800320 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530321 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800322
323 /**
324 * Set of user IDs being actively removed. Removed IDs linger in this set
325 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700326 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800327 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700328 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800329 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700330
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700331 /**
332 * Queue of recently removed userIds. Used for recycling of userIds
333 */
334 @GuardedBy("mUsersLock")
335 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
336
Fyodor Kupolov82402752015-10-28 14:54:51 -0700337 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700338 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800339 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700340 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700341 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700342
Jason Monk62062992014-05-06 09:55:28 -0400343 private IAppOpsService mAppOpsService;
344
Makoto Onuki068c54a2015-10-13 14:34:03 -0700345 private final LocalService mLocalService;
346
Makoto Onukie7927da2015-11-25 10:05:17 -0800347 @GuardedBy("mUsersLock")
348 private boolean mIsDeviceManaged;
349
350 @GuardedBy("mUsersLock")
351 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
352
Makoto Onukid45a4a22015-11-02 17:17:38 -0800353 @GuardedBy("mUserRestrictionsListeners")
354 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
355 new ArrayList<>();
356
Clara Bayarria1771112015-12-18 16:29:18 +0000357 private final LockPatternUtils mLockPatternUtils;
358
Ricky Waib1dd80b2016-06-07 18:00:55 +0100359 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
360 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
361
362 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
363 @Override
364 public void onReceive(Context context, Intent intent) {
365 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
366 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
367 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
368 setQuietModeEnabled(userHandle, false);
369 if (target != null) {
370 try {
371 mContext.startIntentSender(target, null, 0, 0, 0);
372 } catch (IntentSender.SendIntentException e) {
373 /* ignore */
374 }
375 }
376 }
377 }
378 };
379
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100380 /**
381 * Whether all users should be created ephemeral.
382 */
383 @GuardedBy("mUsersLock")
384 private boolean mForceEphemeralUsers;
385
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000386 @GuardedBy("mUserStates")
387 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700388
Amith Yamasani258848d2012-08-10 17:06:33 -0700389 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700390
Dianne Hackborn4428e172012-08-24 17:43:05 -0700391 public static UserManagerService getInstance() {
392 synchronized (UserManagerService.class) {
393 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700394 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700396
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700397 public static class LifeCycle extends SystemService {
398
399 private UserManagerService mUms;
400
401 /**
402 * @param context
403 */
404 public LifeCycle(Context context) {
405 super(context);
406 }
407
408 @Override
409 public void onStart() {
410 mUms = UserManagerService.getInstance();
411 publishBinderService(Context.USER_SERVICE, mUms);
412 }
413
414 @Override
415 public void onBootPhase(int phase) {
416 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
417 mUms.cleanupPartialUsers();
418 }
419 }
420 }
421
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700422 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800423 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700424 UserManagerService(Context context) {
425 this(context, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700426 }
427
Dianne Hackborn4428e172012-08-24 17:43:05 -0700428 /**
429 * Called by package manager to create the service. This is closely
430 * associated with the package manager, and the given lock is the
431 * package manager's own lock.
432 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800433 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
434 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700435 }
436
Dianne Hackborn4428e172012-08-24 17:43:05 -0700437 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800438 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 mContext = context;
440 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800442 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800443 synchronized (mPackagesLock) {
444 mUsersDir = new File(dataDir, USER_INFO_DIR);
445 mUsersDir.mkdirs();
446 // Make zeroth user directory, for services to migrate their files to that location
447 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
448 userZeroDir.mkdirs();
449 FileUtils.setPermissions(mUsersDir.toString(),
450 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
451 -1, -1);
452 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
453 initDefaultGuestRestrictions();
454 readUserListLP();
455 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700456 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700457 mLocalService = new LocalService();
458 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000459 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000460 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700461 }
462
463 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400464 mAppOpsService = IAppOpsService.Stub.asInterface(
465 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800466
467 synchronized (mRestrictionsLock) {
468 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400469 }
Samuel Tand9453b82016-03-14 15:57:02 -0700470
471 UserInfo currentGuestUser = findCurrentGuestUser();
472 if (currentGuestUser != null && !hasUserRestriction(
473 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
474 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
475 // to it, in case this guest was created in a previous version where this
476 // user restriction was not a default guest restriction.
477 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
478 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700479
Ricky Waib1dd80b2016-06-07 18:00:55 +0100480 mContext.registerReceiver(mDisableQuietModeCallback,
481 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
482 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700483 }
484
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700485 void cleanupPartialUsers() {
486 // Prune out any partially created, partially removed and ephemeral users.
487 ArrayList<UserInfo> partials = new ArrayList<>();
488 synchronized (mUsersLock) {
489 final int userSize = mUsers.size();
490 for (int i = 0; i < userSize; i++) {
491 UserInfo ui = mUsers.valueAt(i).info;
492 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
493 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700494 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700495 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700496 }
497 }
498 }
499 final int partialsSize = partials.size();
500 for (int i = 0; i < partialsSize; i++) {
501 UserInfo ui = partials.get(i);
502 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
503 + " (name=" + ui.name + ")");
504 removeUserState(ui.id);
505 }
506 }
507
Amith Yamasani258848d2012-08-10 17:06:33 -0700508 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800509 public String getUserAccount(int userId) {
510 checkManageUserAndAcrossUsersFullPermission("get user account");
511 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800512 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800513 }
514 }
515
516 @Override
517 public void setUserAccount(int userId, String accountName) {
518 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800519 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800520 synchronized (mPackagesLock) {
521 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800522 final UserData userData = mUsers.get(userId);
523 if (userData == null) {
524 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
525 return;
526 }
527 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800528 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800529 userData.account = accountName;
530 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800531 }
532 }
533
534 if (userToUpdate != null) {
535 writeUserLP(userToUpdate);
536 }
537 }
538 }
539
540 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700541 public UserInfo getPrimaryUser() {
542 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700543 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700544 final int userSize = mUsers.size();
545 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800546 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800547 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700548 return ui;
549 }
550 }
551 }
552 return null;
553 }
554
555 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700556 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700557 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700558 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700559 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700560 final int userSize = mUsers.size();
561 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800562 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700563 if (ui.partial) {
564 continue;
565 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800566 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700567 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700568 }
Amith Yamasani13593602012-03-22 16:16:17 -0700569 }
570 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700571 }
Amith Yamasani13593602012-03-22 16:16:17 -0700572 }
573
Amith Yamasani258848d2012-08-10 17:06:33 -0700574 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100575 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700576 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800577 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700578 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700579 } else {
580 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800581 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700582 final long ident = Binder.clearCallingIdentity();
583 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700584 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700585 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100586 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 } finally {
588 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000589 }
590 }
591
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700592 @Override
593 public int[] getProfileIds(int userId, boolean enabledOnly) {
594 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700595 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700596 }
597 final long ident = Binder.clearCallingIdentity();
598 try {
599 synchronized (mUsersLock) {
600 return getProfileIdsLU(userId, enabledOnly).toArray();
601 }
602 } finally {
603 Binder.restoreCallingIdentity(ident);
604 }
605 }
606
Amith Yamasanibe465322014-04-24 13:45:17 -0700607 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700608 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700609 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
610 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
611 for (int i = 0; i < profileIds.size(); i++) {
612 int profileId = profileIds.get(i);
613 UserInfo userInfo = mUsers.get(profileId).info;
614 // If full info is not required - clear PII data to prevent 3P apps from reading it
615 if (!fullInfo) {
616 userInfo = new UserInfo(userInfo);
617 userInfo.name = null;
618 userInfo.iconPath = null;
619 } else {
620 userInfo = userWithName(userInfo);
621 }
622 users.add(userInfo);
623 }
624 return users;
625 }
626
627 /**
628 * Assume permissions already checked and caller's identity cleared
629 */
630 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700631 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700632 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700633 if (user == null) {
634 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700635 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700636 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700637 final int userSize = mUsers.size();
638 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800639 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700640 if (!isProfileOf(user, profile)) {
641 continue;
642 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100643 if (enabledOnly && !profile.isEnabled()) {
644 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700645 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700646 if (mRemovingUserIds.get(profile.id)) {
647 continue;
648 }
Tony Mak80189cd2016-04-05 17:21:42 +0100649 if (profile.partial) {
650 continue;
651 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700652 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700653 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700654 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700655 }
656
Jessica Hummelbe81c802014-04-22 15:49:22 +0100657 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700658 public int getCredentialOwnerProfile(int userHandle) {
659 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000660 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700661 synchronized (mUsersLock) {
662 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700663 if (profileParent != null) {
664 return profileParent.id;
665 }
666 }
667 }
668
669 return userHandle;
670 }
671
672 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700673 public boolean isSameProfileGroup(int userId, int otherUserId) {
674 if (userId == otherUserId) return true;
675 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700676 return isSameProfileGroupNoChecks(userId, otherUserId);
677 }
678
679 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700680 synchronized (mUsersLock) {
681 UserInfo userInfo = getUserInfoLU(userId);
682 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
683 return false;
684 }
685 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
686 if (otherUserInfo == null
687 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
688 return false;
689 }
690 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700691 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700692 }
693
694 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100695 public UserInfo getProfileParent(int userHandle) {
696 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700697 synchronized (mUsersLock) {
698 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700699 }
700 }
701
Fyodor Kupolov82402752015-10-28 14:54:51 -0700702 private UserInfo getProfileParentLU(int userHandle) {
703 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700704 if (profile == null) {
705 return null;
706 }
707 int parentUserId = profile.profileGroupId;
708 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
709 return null;
710 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700711 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100712 }
713 }
714
Fyodor Kupolov82402752015-10-28 14:54:51 -0700715 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100716 return user.id == profile.id ||
717 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
718 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000719 }
720
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000721 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000722 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100723 Intent intent = new Intent();
724 if (inQuietMode) {
725 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
726 } else {
727 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
728 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000729 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
730 intent.putExtra(Intent.EXTRA_USER, profileHandle);
731 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000732 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000733 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000734 }
735
736 @Override
737 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
738 checkManageUsersPermission("silence profile");
739 boolean changed = false;
740 UserInfo profile, parent;
741 synchronized (mPackagesLock) {
742 synchronized (mUsersLock) {
743 profile = getUserInfoLU(userHandle);
744 parent = getProfileParentLU(userHandle);
745
746 }
747 if (profile == null || !profile.isManagedProfile()) {
748 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
749 }
750 if (profile.isQuietModeEnabled() != enableQuietMode) {
751 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800752 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000753 changed = true;
754 }
755 }
756 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000757 long identity = Binder.clearCallingIdentity();
758 try {
759 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100760 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100761 LocalServices.getService(ActivityManagerInternal.class)
762 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000763 } else {
764 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
765 }
766 } catch (RemoteException e) {
767 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
768 } finally {
769 Binder.restoreCallingIdentity(identity);
770 }
771
772 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
773 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000774 }
775 }
776
777 @Override
778 public boolean isQuietModeEnabled(int userHandle) {
779 synchronized (mPackagesLock) {
780 UserInfo info;
781 synchronized (mUsersLock) {
782 info = getUserInfoLU(userHandle);
783 }
784 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000785 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000786 }
787 return info.isQuietModeEnabled();
788 }
789 }
790
Kenny Guya52dc3e2014-02-11 15:33:14 +0000791 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100792 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100793 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600794 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100795 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100796 // if the user is already unlocked, no need to show a profile challenge
797 setQuietModeEnabled(userHandle, false);
798 return true;
799 }
800
801 long identity = Binder.clearCallingIdentity();
802 try {
803 // otherwise, we show a profile challenge to trigger decryption of the user
804 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
805 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100806 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
807 // lock, confirm screenlock page will know and show personal challenge, and unlock
808 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100809 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
810 userHandle);
811 if (unlockIntent == null) {
812 return false;
813 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100814 final Intent callBackIntent = new Intent(
815 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100816 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100817 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100818 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100819 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
820 callBackIntent.setPackage(mContext.getPackageName());
821 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
822 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
823 mContext,
824 0,
825 callBackIntent,
826 PendingIntent.FLAG_CANCEL_CURRENT |
827 PendingIntent.FLAG_ONE_SHOT |
828 PendingIntent.FLAG_IMMUTABLE);
829 // After unlocking the challenge, it will disable quiet mode and run the original
830 // intentSender
831 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100832 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
833 mContext.startActivity(unlockIntent);
834 } finally {
835 Binder.restoreCallingIdentity(identity);
836 }
837 return false;
838 }
839
840 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100841 public void setUserEnabled(int userId) {
842 checkManageUsersPermission("enable user");
843 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700844 UserInfo info;
845 synchronized (mUsersLock) {
846 info = getUserInfoLU(userId);
847 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100848 if (info != null && !info.isEnabled()) {
849 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800850 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100851 }
852 }
853 }
854
855 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700856 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700857 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000858 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700859 return userWithName(getUserInfoLU(userId));
860 }
861 }
862
863 /**
864 * Returns a UserInfo object with the name filled in, for Owner, or the original
865 * if the name is already set.
866 */
867 private UserInfo userWithName(UserInfo orig) {
868 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
869 UserInfo withName = new UserInfo(orig);
870 withName.name = getOwnerName();
871 return withName;
872 } else {
873 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000874 }
875 }
876
877 @Override
878 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000879 int callingUserId = UserHandle.getCallingUserId();
880 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700881 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700882 throw new SecurityException(
883 "You need MANAGE_USERS permission to: check if specified user a " +
884 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000885 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000886 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700887 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700888 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000889 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700890 }
891 }
892
Amith Yamasani71e6c692013-03-24 17:39:28 -0700893 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700894 public boolean isUserUnlockingOrUnlocked(int userId) {
895 int callingUserId = UserHandle.getCallingUserId();
896 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700897 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700898 throw new SecurityException(
899 "You need MANAGE_USERS permission to: check isUserUnlockingOrUnlocked");
900 }
901 }
902 return mLocalService.isUserUnlockingOrUnlocked(userId);
903 }
904
905 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700906 public boolean isDemoUser(int userId) {
907 int callingUserId = UserHandle.getCallingUserId();
908 if (callingUserId != userId && !hasManageUsersPermission()) {
909 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
910 + " is a demo user");
911 }
912 synchronized (mUsersLock) {
913 UserInfo userInfo = getUserInfoLU(userId);
914 return userInfo != null && userInfo.isDemo();
915 }
916 }
917
918 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700919 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700920 synchronized (mUsersLock) {
921 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700922 }
923 }
924
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700925 @Override
926 public boolean canHaveRestrictedProfile(int userId) {
927 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700928 synchronized (mUsersLock) {
929 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700930 if (userInfo == null || !userInfo.canHaveProfile()) {
931 return false;
932 }
933 if (!userInfo.isAdmin()) {
934 return false;
935 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800936 // restricted profile can be created if there is no DO set and the admin user has no PO;
937 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700938 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700939 }
940
Amith Yamasani195263742012-08-21 15:40:12 -0700941 /*
942 * Should be locked on mUsers before calling this.
943 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700944 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800945 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700946 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800947 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700948 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
949 return null;
950 }
Amith Yamasani12747872015-12-07 14:19:49 -0800951 return userData != null ? userData.info : null;
952 }
953
954 private UserData getUserDataLU(int userId) {
955 final UserData userData = mUsers.get(userId);
956 // If it is partial and not in the process of being removed, return as unknown user.
957 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
958 return null;
959 }
960 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700961 }
962
Fyodor Kupolov82402752015-10-28 14:54:51 -0700963 /**
964 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
965 * <p>No permissions checking or any addition checks are made</p>
966 */
967 private UserInfo getUserInfoNoChecks(int userId) {
968 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800969 final UserData userData = mUsers.get(userId);
970 return userData != null ? userData.info : null;
971 }
972 }
973
974 /**
975 * Obtains {@link #mUsersLock} and return UserData from mUsers.
976 * <p>No permissions checking or any addition checks are made</p>
977 */
978 private UserData getUserDataNoChecks(int userId) {
979 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700980 return mUsers.get(userId);
981 }
982 }
983
Amith Yamasani236b2b52015-08-18 14:32:14 -0700984 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700985 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700986 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700987 }
988
Amith Yamasani258848d2012-08-10 17:06:33 -0700989 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700990 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700991 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700992 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700993 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800994 UserData userData = getUserDataNoChecks(userId);
995 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700996 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
997 return;
998 }
Amith Yamasani12747872015-12-07 14:19:49 -0800999 if (name != null && !name.equals(userData.info.name)) {
1000 userData.info.name = name;
1001 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001002 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001003 }
1004 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001005 if (changed) {
1006 sendUserInfoChangedBroadcast(userId);
1007 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001008 }
1009
Amith Yamasani258848d2012-08-10 17:06:33 -07001010 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001011 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001012 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001013 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1014 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1015 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001016 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001017 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001018 }
1019
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001020
1021
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001022 private void sendUserInfoChangedBroadcast(int userId) {
1023 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1024 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1025 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001026 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001027 }
1028
Amith Yamasani258848d2012-08-10 17:06:33 -07001029 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001030 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001031 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001032 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001033 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1034 if (targetUserInfo == null || targetUserInfo.partial) {
1035 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001036 return null;
1037 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001038
1039 final int callingUserId = UserHandle.getCallingUserId();
1040 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1041 final int targetGroupId = targetUserInfo.profileGroupId;
1042 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1043 && callingGroupId == targetGroupId);
1044 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001045 checkManageUsersPermission("get the icon of a user who is not related");
1046 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001047
1048 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001049 return null;
1050 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001051 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001052 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001053
1054 try {
1055 return ParcelFileDescriptor.open(
1056 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1057 } catch (FileNotFoundException e) {
1058 Log.e(LOG_TAG, "Couldn't find icon file", e);
1059 }
1060 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001061 }
1062
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001063 public void makeInitialized(int userId) {
1064 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001065 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001066 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001067 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001068 userData = mUsers.get(userId);
1069 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001070 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001071 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001072 }
Amith Yamasani12747872015-12-07 14:19:49 -08001073 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1074 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001075 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001076 }
1077 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001078 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001079 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001080 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001081 }
1082
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001083 /**
1084 * If default guest restrictions haven't been initialized yet, add the basic
1085 * restrictions.
1086 */
1087 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001088 synchronized (mGuestRestrictions) {
1089 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001090 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001091 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001092 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1093 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1094 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001095 }
1096 }
1097
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001098 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301099 public Bundle getDefaultGuestRestrictions() {
1100 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001101 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301102 return new Bundle(mGuestRestrictions);
1103 }
1104 }
1105
1106 @Override
1107 public void setDefaultGuestRestrictions(Bundle restrictions) {
1108 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001109 synchronized (mGuestRestrictions) {
1110 mGuestRestrictions.clear();
1111 mGuestRestrictions.putAll(restrictions);
1112 }
1113 synchronized (mPackagesLock) {
1114 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301115 }
1116 }
1117
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001118 /**
1119 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1120 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001121 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001122 @Nullable Bundle global) {
1123 Preconditions.checkNotNull(local);
1124 boolean globalChanged = false;
1125 boolean localChanged;
1126 synchronized (mRestrictionsLock) {
1127 if (global != null) {
1128 // Update global.
1129 globalChanged = !UserRestrictionsUtils.areEqual(
1130 mDevicePolicyGlobalUserRestrictions, global);
1131 if (globalChanged) {
1132 mDevicePolicyGlobalUserRestrictions = global;
1133 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001134 // Remember the global restriction owner userId to be able to make a distinction
1135 // in getUserRestrictionSource on who set local policies.
1136 mGlobalRestrictionOwnerUserId = userId;
1137 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001138 if (mGlobalRestrictionOwnerUserId == userId) {
1139 // When profile owner sets restrictions it passes null global bundle and we
1140 // reset global restriction owner userId.
1141 // This means this user used to have DO, but now the DO is gone and the user
1142 // instead has PO.
1143 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1144 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001145 }
1146 {
1147 // Update local.
1148 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1149 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1150 if (localChanged) {
1151 mDevicePolicyLocalUserRestrictions.put(userId, local);
1152 }
1153 }
1154 }
1155 if (DBG) {
1156 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1157 + " global=" + global + (globalChanged ? " (changed)" : "")
1158 + " local=" + local + (localChanged ? " (changed)" : "")
1159 );
1160 }
1161 // Don't call them within the mRestrictionsLock.
1162 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001163 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001164 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001165 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001166 if (globalChanged) {
1167 writeUserListLP();
1168 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001169 }
1170
1171 synchronized (mRestrictionsLock) {
1172 if (globalChanged) {
1173 applyUserRestrictionsForAllUsersLR();
1174 } else if (localChanged) {
1175 applyUserRestrictionsLR(userId);
1176 }
1177 }
1178 }
1179
Makoto Onuki068c54a2015-10-13 14:34:03 -07001180 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001181 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001182 final Bundle baseRestrictions =
1183 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1184 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1185 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001186
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001187 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1188 // Common case first.
1189 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001190 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001191 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1192 UserRestrictionsUtils.merge(effective, global);
1193 UserRestrictionsUtils.merge(effective, local);
1194
Makoto Onuki068c54a2015-10-13 14:34:03 -07001195 return effective;
1196 }
1197
1198 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001199 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001200 if (DBG) {
1201 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1202 }
1203 mCachedEffectiveUserRestrictions.remove(userId);
1204 }
1205
1206 private Bundle getEffectiveUserRestrictions(int userId) {
1207 synchronized (mRestrictionsLock) {
1208 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1209 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001210 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001211 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1212 }
1213 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001214 }
1215 }
1216
Makoto Onuki068c54a2015-10-13 14:34:03 -07001217 /** @return a specific user restriction that's in effect currently. */
1218 @Override
1219 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001220 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1221 return false;
1222 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001223 Bundle restrictions = getEffectiveUserRestrictions(userId);
1224 return restrictions != null && restrictions.getBoolean(restrictionKey);
1225 }
1226
1227 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001228 * @hide
1229 *
1230 * Returns who set a user restriction on a user.
1231 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1232 * @param restrictionKey the string key representing the restriction
1233 * @param userId the id of the user for whom to retrieve the restrictions.
1234 * @return The source of user restriction. Any combination of
1235 * {@link UserManager#RESTRICTION_NOT_SET},
1236 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1237 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1238 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1239 */
1240 @Override
1241 public int getUserRestrictionSource(String restrictionKey, int userId) {
1242 checkManageUsersPermission("getUserRestrictionSource");
1243 int result = UserManager.RESTRICTION_NOT_SET;
1244
1245 // Shortcut for the most common case
1246 if (!hasUserRestriction(restrictionKey, userId)) {
1247 return result;
1248 }
1249
1250 if (hasBaseUserRestriction(restrictionKey, userId)) {
1251 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1252 }
1253
1254 synchronized(mRestrictionsLock) {
1255 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1256 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1257 && localRestrictions.getBoolean(restrictionKey)) {
1258 // Local restrictions may have been set by device owner the userId of which is
1259 // stored in mGlobalRestrictionOwnerUserId.
1260 if (mGlobalRestrictionOwnerUserId == userId) {
1261 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1262 } else {
1263 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1264 }
1265 }
1266 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1267 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1268 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1269 }
1270 }
1271
1272 return result;
1273 }
1274
1275 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001276 * @return UserRestrictions that are in effect currently. This always returns a new
1277 * {@link Bundle}.
1278 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001279 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001280 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001281 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001282 }
1283
1284 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001285 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1286 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001287 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1288 return false;
1289 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001290 synchronized (mRestrictionsLock) {
1291 Bundle bundle = mBaseUserRestrictions.get(userId);
1292 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1293 }
1294 }
1295
1296 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001297 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001298 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001299 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1300 return;
1301 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001302 synchronized (mRestrictionsLock) {
1303 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1304 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001305 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1306 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001307 newRestrictions.putBoolean(key, value);
1308
Fyodor Kupolov82402752015-10-28 14:54:51 -07001309 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001310 }
1311 }
1312
Makoto Onuki068c54a2015-10-13 14:34:03 -07001313 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001314 * Optionally updating user restrictions, calculate the effective user restrictions and also
1315 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001316 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001317 * @param newRestrictions User restrictions to set.
1318 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001319 * @param userId target user ID.
1320 */
1321 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001322 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001323 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001324
1325 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1326 mAppliedUserRestrictions.get(userId));
1327
1328 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001329 if (newRestrictions != null) {
1330 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001331 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1332
1333 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001334 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1335 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001336
1337 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1338 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001339 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001340 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001341 }
1342
Fyodor Kupolov82402752015-10-28 14:54:51 -07001343 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001344
Makoto Onuki759a7632015-10-28 16:43:10 -07001345 mCachedEffectiveUserRestrictions.put(userId, effective);
1346
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001347 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001348 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001349 debug("Applying user restrictions: userId=" + userId
1350 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001351 }
1352
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001353 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001354 mHandler.post(new Runnable() {
1355 @Override
1356 public void run() {
1357 try {
1358 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1359 } catch (RemoteException e) {
1360 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1361 }
1362 }
1363 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001364 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001365
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001366 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001367
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001368 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001369 }
1370
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001371 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001372 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001373 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1374 // actually, but we still need some kind of synchronization otherwise we might end up
1375 // calling listeners out-of-order, thus "LR".
1376
1377 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1378 return;
1379 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001380
1381 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1382 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1383
1384 mHandler.post(new Runnable() {
1385 @Override
1386 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001387 UserRestrictionsUtils.applyUserRestrictions(
1388 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001389
Makoto Onukid45a4a22015-11-02 17:17:38 -08001390 final UserRestrictionsListener[] listeners;
1391 synchronized (mUserRestrictionsListeners) {
1392 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1393 mUserRestrictionsListeners.toArray(listeners);
1394 }
1395 for (int i = 0; i < listeners.length; i++) {
1396 listeners[i].onUserRestrictionsChanged(userId,
1397 newRestrictionsFinal, prevRestrictionsFinal);
1398 }
1399 }
1400 });
1401 }
1402
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001403 // Package private for the inner class.
1404 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001405 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001406 }
1407
1408 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001409 // Package private for the inner class.
1410 void applyUserRestrictionsForAllUsersLR() {
1411 if (DBG) {
1412 debug("applyUserRestrictionsForAllUsersLR");
1413 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001414 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001415 mCachedEffectiveUserRestrictions.clear();
1416
Makoto Onuki068c54a2015-10-13 14:34:03 -07001417 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1418 // it on a handler.
1419 final Runnable r = new Runnable() {
1420 @Override
1421 public void run() {
1422 // Then get the list of running users.
1423 final int[] runningUsers;
1424 try {
1425 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1426 } catch (RemoteException e) {
1427 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1428 return;
1429 }
1430 // Then re-calculate the effective restrictions and apply, only for running users.
1431 // It's okay if a new user has started after the getRunningUserIds() call,
1432 // because we'll do the same thing (re-calculate the restrictions and apply)
1433 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001434 synchronized (mRestrictionsLock) {
1435 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001436 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001437 }
1438 }
1439 }
1440 };
1441 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001442 }
1443
Amith Yamasani258848d2012-08-10 17:06:33 -07001444 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001445 * Check if we've hit the limit of how many users can be created.
1446 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001447 private boolean isUserLimitReached() {
1448 int count;
1449 synchronized (mUsersLock) {
1450 count = getAliveUsersExcludingGuestsCountLU();
1451 }
1452 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001453 }
1454
1455 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001456 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001457 checkManageUsersPermission("check if more managed profiles can be added.");
1458 if (ActivityManager.isLowRamDeviceStatic()) {
1459 return false;
1460 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001461 if (!mContext.getPackageManager().hasSystemFeature(
1462 PackageManager.FEATURE_MANAGED_USERS)) {
1463 return false;
1464 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001465 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001466 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1467 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1468 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001469 return false;
1470 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001471 synchronized(mUsersLock) {
1472 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001473 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001474 return false;
1475 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001476 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1477 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001478 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001479 return usersCountAfterRemoving == 1
1480 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001481 }
1482 }
1483
Fyodor Kupolov82402752015-10-28 14:54:51 -07001484 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001485 int aliveUserCount = 0;
1486 final int totalUserCount = mUsers.size();
1487 // Skip over users being removed
1488 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001489 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001490 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001491 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001492 aliveUserCount++;
1493 }
1494 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001495 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001496 }
1497
1498 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001499 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001500 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1501 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1502 * permissions can make certain calls to the UserManager.
1503 *
1504 * @param message used as message if SecurityException is thrown
1505 * @throws SecurityException if the caller does not have enough privilege.
1506 */
1507 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1508 final int uid = Binder.getCallingUid();
1509 if (uid != Process.SYSTEM_UID && uid != 0
1510 && ActivityManager.checkComponentPermission(
1511 Manifest.permission.MANAGE_USERS,
1512 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1513 && ActivityManager.checkComponentPermission(
1514 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1515 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1516 throw new SecurityException(
1517 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1518 + message);
1519 }
1520 }
1521
1522 /**
1523 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001524 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001525 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001526 *
1527 * @param message used as message if SecurityException is thrown
1528 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001529 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001530 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001531 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001532 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001533 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1534 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001535 }
1536
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001537 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001538 * Enforces that only the system UID or root's UID or apps that have the
1539 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1540 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1541 * can make certain calls to the UserManager.
1542 *
1543 * @param message used as message if SecurityException is thrown
1544 * @throws SecurityException if the caller is not system or root
1545 * @see #hasManageOrCreateUsersPermission()
1546 */
1547 private static final void checkManageOrCreateUsersPermission(String message) {
1548 if (!hasManageOrCreateUsersPermission()) {
1549 throw new SecurityException(
1550 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1551 }
1552 }
1553
1554 /**
1555 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1556 * to create user/profiles other than what is allowed for
1557 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1558 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1559 */
1560 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1561 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1562 if (!hasManageOrCreateUsersPermission()) {
1563 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1564 + "permission to create an user with flags: " + creationFlags);
1565 }
1566 } else if (!hasManageUsersPermission()) {
1567 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1568 + " with flags: " + creationFlags);
1569 }
1570 }
1571
1572 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001573 * @return whether the calling UID is system UID or root's UID or the calling app has the
1574 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1575 */
1576 private static final boolean hasManageUsersPermission() {
1577 final int callingUid = Binder.getCallingUid();
1578 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1579 || callingUid == Process.ROOT_UID
1580 || ActivityManager.checkComponentPermission(
1581 android.Manifest.permission.MANAGE_USERS,
1582 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1583 }
1584
1585 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001586 * @return whether the calling UID is system UID or root's UID or the calling app has the
1587 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1588 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1589 */
1590 private static final boolean hasManageOrCreateUsersPermission() {
1591 final int callingUid = Binder.getCallingUid();
1592 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1593 || callingUid == Process.ROOT_UID
1594 || ActivityManager.checkComponentPermission(
1595 android.Manifest.permission.MANAGE_USERS,
1596 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1597 || ActivityManager.checkComponentPermission(
1598 android.Manifest.permission.CREATE_USERS,
1599 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1600 }
1601
1602 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001603 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1604 * UserManager.
1605 *
1606 * @param message used as message if SecurityException is thrown
1607 * @throws SecurityException if the caller is not system or root
1608 */
1609 private static void checkSystemOrRoot(String message) {
1610 final int uid = Binder.getCallingUid();
1611 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1612 throw new SecurityException("Only system may: " + message);
1613 }
1614 }
1615
Fyodor Kupolov82402752015-10-28 14:54:51 -07001616 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001617 try {
1618 File dir = new File(mUsersDir, Integer.toString(info.id));
1619 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001620 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001621 if (!dir.exists()) {
1622 dir.mkdir();
1623 FileUtils.setPermissions(
1624 dir.getPath(),
1625 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1626 -1, -1);
1627 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001628 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001629 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001630 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001631 info.iconPath = file.getAbsolutePath();
1632 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001633 try {
1634 os.close();
1635 } catch (IOException ioe) {
1636 // What the ... !
1637 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001638 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001639 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001640 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001641 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001642 }
1643
Amith Yamasani0b285492011-04-14 17:35:23 -07001644 /**
1645 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1646 * cache it elsewhere.
1647 * @return the array of user ids.
1648 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001649 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001650 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001651 return mUserIds;
1652 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001653 }
1654
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001655 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001657 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001658 return;
1659 }
1660 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001661 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001663 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001664 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001665 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001666 int type;
1667 while ((type = parser.next()) != XmlPullParser.START_TAG
1668 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001669 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001670 }
1671
1672 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001673 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001674 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001675 return;
1676 }
1677
Amith Yamasani2a003292012-08-14 18:25:45 -07001678 mNextSerialNumber = -1;
1679 if (parser.getName().equals(TAG_USERS)) {
1680 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1681 if (lastSerialNumber != null) {
1682 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1683 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001684 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1685 if (versionNumber != null) {
1686 mUserVersion = Integer.parseInt(versionNumber);
1687 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001688 }
1689
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1691
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001692 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301693 if (type == XmlPullParser.START_TAG) {
1694 final String name = parser.getName();
1695 if (name.equals(TAG_USER)) {
1696 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001697
Amith Yamasani12747872015-12-07 14:19:49 -08001698 UserData userData = readUserLP(Integer.parseInt(id));
1699
1700 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001701 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001702 mUsers.put(userData.info.id, userData);
1703 if (mNextSerialNumber < 0
1704 || mNextSerialNumber <= userData.info.id) {
1705 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001706 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301707 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001708 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301709 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001710 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1711 && type != XmlPullParser.END_TAG) {
1712 if (type == XmlPullParser.START_TAG) {
1713 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001714 synchronized (mGuestRestrictions) {
1715 UserRestrictionsUtils
1716 .readRestrictions(parser, mGuestRestrictions);
1717 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001718 }
1719 break;
1720 }
1721 }
Makoto Onuki82de3002016-09-30 09:58:15 -07001722 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1723 UserRestrictionsUtils.readRestrictions(parser,
1724 newDevicePolicyGlobalUserRestrictions);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001725 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1726 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1727 if (ownerUserId != null) {
1728 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1729 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001730 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001731 }
1732 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001733 synchronized (mRestrictionsLock) {
1734 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1735 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001736 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001737 upgradeIfNecessaryLP();
1738 } catch (IOException | XmlPullParserException e) {
1739 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001740 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001741 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001742 }
1743 }
1744
Amith Yamasani6f34b412012-10-22 18:19:27 -07001745 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001746 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001747 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001748 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001749 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001750 int userVersion = mUserVersion;
1751 if (userVersion < 1) {
1752 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001753 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1754 if ("Primary".equals(userData.info.name)) {
1755 userData.info.name =
1756 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1757 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001758 }
1759 userVersion = 1;
1760 }
1761
Amith Yamasanibc9625052012-11-15 14:39:18 -08001762 if (userVersion < 2) {
1763 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001764 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1765 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1766 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1767 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001768 }
1769 userVersion = 2;
1770 }
1771
Amith Yamasani350962c2013-08-06 11:18:53 -07001772
Amith Yamasani5e486f52013-08-07 11:06:44 -07001773 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001774 userVersion = 4;
1775 }
1776
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001777 if (userVersion < 5) {
1778 initDefaultGuestRestrictions();
1779 userVersion = 5;
1780 }
1781
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001782 if (userVersion < 6) {
1783 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001784 synchronized (mUsersLock) {
1785 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001786 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001787 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001788 if (!splitSystemUser && userData.info.isRestricted()
1789 && (userData.info.restrictedProfileParentId
1790 == UserInfo.NO_PROFILE_GROUP_ID)) {
1791 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1792 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001793 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001794 }
1795 }
1796 userVersion = 6;
1797 }
1798
Amith Yamasani6f34b412012-10-22 18:19:27 -07001799 if (userVersion < USER_VERSION) {
1800 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1801 + USER_VERSION);
1802 } else {
1803 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001804
1805 if (originalVersion < mUserVersion) {
1806 writeUserListLP();
1807 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001808 }
1809 }
1810
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001811 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001812 int flags = UserInfo.FLAG_INITIALIZED;
1813 // In split system user mode, the admin and primary flags are assigned to the first human
1814 // user.
1815 if (!UserManager.isSplitSystemUser()) {
1816 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1817 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001818 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001819 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001820 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001821 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001822 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001823
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001824 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001825 try {
1826 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1827 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1828 for (String userRestriction : defaultFirstUserRestrictions) {
1829 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1830 restrictions.putBoolean(userRestriction, true);
1831 }
1832 }
1833 } catch (Resources.NotFoundException e) {
1834 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1835 }
1836
Makoto Onuki068c54a2015-10-13 14:34:03 -07001837 synchronized (mRestrictionsLock) {
1838 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1839 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001840
Fyodor Kupolov82402752015-10-28 14:54:51 -07001841 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001842 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001843
Amith Yamasani12747872015-12-07 14:19:49 -08001844 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001845 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001846 }
1847
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001848 private String getOwnerName() {
1849 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1850 }
1851
Amith Yamasani12747872015-12-07 14:19:49 -08001852 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001853 if (DBG) {
1854 debug("scheduleWriteUser");
1855 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001856 // No need to wrap it within a lock -- worst case, we'll just post the same message
1857 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001858 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1859 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001860 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1861 }
1862 }
1863
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001864 /*
1865 * Writes the user file in this format:
1866 *
1867 * <user flags="20039023" id="0">
1868 * <name>Primary</name>
1869 * </user>
1870 */
Amith Yamasani12747872015-12-07 14:19:49 -08001871 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001872 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001873 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001874 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001875 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001876 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001877 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001878 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001879 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1880
1881 // XmlSerializer serializer = XmlUtils.serializerInstance();
1882 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001883 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001884 serializer.startDocument(null, true);
1885 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1886
Amith Yamasani12747872015-12-07 14:19:49 -08001887 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001888 serializer.startTag(null, TAG_USER);
1889 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001890 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001891 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001892 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1893 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1894 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001895 if (userInfo.lastLoggedInFingerprint != null) {
1896 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1897 userInfo.lastLoggedInFingerprint);
1898 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001899 if (userInfo.iconPath != null) {
1900 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1901 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001902 if (userInfo.partial) {
1903 serializer.attribute(null, ATTR_PARTIAL, "true");
1904 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001905 if (userInfo.guestToRemove) {
1906 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1907 }
Kenny Guy2a764942014-04-02 13:29:20 +01001908 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1909 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1910 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001911 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001912 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1913 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1914 Integer.toString(userInfo.restrictedProfileParentId));
1915 }
Amith Yamasani12747872015-12-07 14:19:49 -08001916 // Write seed data
1917 if (userData.persistSeedData) {
1918 if (userData.seedAccountName != null) {
1919 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1920 }
1921 if (userData.seedAccountType != null) {
1922 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1923 }
1924 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001925 if (userInfo.name != null) {
1926 serializer.startTag(null, TAG_NAME);
1927 serializer.text(userInfo.name);
1928 serializer.endTag(null, TAG_NAME);
1929 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001930 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001931 UserRestrictionsUtils.writeRestrictions(serializer,
1932 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1933 UserRestrictionsUtils.writeRestrictions(serializer,
1934 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1935 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001936 }
Amith Yamasani12747872015-12-07 14:19:49 -08001937
1938 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001939 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001940 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001941 serializer.endTag(null, TAG_ACCOUNT);
1942 }
1943
Amith Yamasani12747872015-12-07 14:19:49 -08001944 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1945 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1946 userData.seedAccountOptions.saveToXml(serializer);
1947 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1948 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001949 serializer.endTag(null, TAG_USER);
1950
1951 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001952 userFile.finishWrite(fos);
1953 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001954 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001955 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001956 }
1957 }
1958
1959 /*
1960 * Writes the user list file in this format:
1961 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001962 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001963 * <user id="0"></user>
1964 * <user id="2"></user>
1965 * </users>
1966 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001967 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001968 if (DBG) {
1969 debug("writeUserList");
1970 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001971 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001972 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001973 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001974 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001975 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1976
1977 // XmlSerializer serializer = XmlUtils.serializerInstance();
1978 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001979 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001980 serializer.startDocument(null, true);
1981 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1982
1983 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001984 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001985 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001986
Adam Lesinskieddeb492014-09-08 17:50:03 -07001987 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001988 synchronized (mGuestRestrictions) {
1989 UserRestrictionsUtils
1990 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1991 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301992 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001993 synchronized (mRestrictionsLock) {
1994 UserRestrictionsUtils.writeRestrictions(serializer,
1995 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1996 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001997 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1998 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1999 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002000 int[] userIdsToWrite;
2001 synchronized (mUsersLock) {
2002 userIdsToWrite = new int[mUsers.size()];
2003 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002004 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002005 userIdsToWrite[i] = user.id;
2006 }
2007 }
2008 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002009 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002010 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002011 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002012 }
2013
2014 serializer.endTag(null, TAG_USERS);
2015
2016 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002017 userListFile.finishWrite(fos);
2018 } catch (Exception e) {
2019 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002020 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002021 }
2022 }
2023
Amith Yamasani12747872015-12-07 14:19:49 -08002024 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002025 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002026 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002027 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002028 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002029 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002030 long creationTime = 0L;
2031 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002032 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002033 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002034 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002035 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002036 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002037 boolean persistSeedData = false;
2038 String seedAccountName = null;
2039 String seedAccountType = null;
2040 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002041 Bundle baseRestrictions = new Bundle();
2042 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002043
2044 FileInputStream fis = null;
2045 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002046 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002047 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002048 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002049 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002050 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002051 int type;
2052 while ((type = parser.next()) != XmlPullParser.START_TAG
2053 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002054 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002055 }
2056
2057 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002058 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002059 return null;
2060 }
2061
2062 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002063 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2064 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002065 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002066 return null;
2067 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002068 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2069 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002070 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002071 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2072 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002073 lastLoggedInFingerprint = parser.getAttributeValue(null,
2074 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002075 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2076 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002077 restrictedProfileParentId = readIntAttribute(parser,
2078 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002079 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2080 if ("true".equals(valueString)) {
2081 partial = true;
2082 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002083 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2084 if ("true".equals(valueString)) {
2085 guestToRemove = true;
2086 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002087
Amith Yamasani12747872015-12-07 14:19:49 -08002088 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2089 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2090 if (seedAccountName != null || seedAccountType != null) {
2091 persistSeedData = true;
2092 }
2093
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002094 int outerDepth = parser.getDepth();
2095 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2096 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2097 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2098 continue;
2099 }
2100 String tag = parser.getName();
2101 if (TAG_NAME.equals(tag)) {
2102 type = parser.next();
2103 if (type == XmlPullParser.TEXT) {
2104 name = parser.getText();
2105 }
2106 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002107 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2108 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2109 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002110 } else if (TAG_ACCOUNT.equals(tag)) {
2111 type = parser.next();
2112 if (type == XmlPullParser.TEXT) {
2113 account = parser.getText();
2114 }
Amith Yamasani12747872015-12-07 14:19:49 -08002115 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2116 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2117 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002118 }
2119 }
2120 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002121
Amith Yamasani12747872015-12-07 14:19:49 -08002122 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002123 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002124 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002125 userInfo.creationTime = creationTime;
2126 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002127 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002128 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002129 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002130 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002131 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002132
2133 // Create the UserData object that's internal to this class
2134 UserData userData = new UserData();
2135 userData.info = userInfo;
2136 userData.account = account;
2137 userData.seedAccountName = seedAccountName;
2138 userData.seedAccountType = seedAccountType;
2139 userData.persistSeedData = persistSeedData;
2140 userData.seedAccountOptions = seedAccountOptions;
2141
Makoto Onuki068c54a2015-10-13 14:34:03 -07002142 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002143 mBaseUserRestrictions.put(id, baseRestrictions);
2144 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002145 }
Amith Yamasani12747872015-12-07 14:19:49 -08002146 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002147 } catch (IOException ioe) {
2148 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002149 } finally {
2150 if (fis != null) {
2151 try {
2152 fis.close();
2153 } catch (IOException e) {
2154 }
2155 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002156 }
2157 return null;
2158 }
2159
Amith Yamasani920ace02012-09-20 22:15:37 -07002160 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2161 String valueString = parser.getAttributeValue(null, attr);
2162 if (valueString == null) return defaultValue;
2163 try {
2164 return Integer.parseInt(valueString);
2165 } catch (NumberFormatException nfe) {
2166 return defaultValue;
2167 }
2168 }
2169
2170 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2171 String valueString = parser.getAttributeValue(null, attr);
2172 if (valueString == null) return defaultValue;
2173 try {
2174 return Long.parseLong(valueString);
2175 } catch (NumberFormatException nfe) {
2176 return defaultValue;
2177 }
2178 }
2179
Amith Yamasanib82add22013-07-09 11:24:44 -07002180 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002181 * Removes the app restrictions file for a specific package and user id, if it exists.
2182 */
2183 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2184 synchronized (mPackagesLock) {
2185 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002186 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002187 if (resFile.exists()) {
2188 resFile.delete();
2189 }
2190 }
2191 }
2192
Kenny Guya52dc3e2014-02-11 15:33:14 +00002193 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002194 public UserInfo createProfileForUser(String name, int flags, int userId,
2195 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002196 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002197 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002198 }
2199
Amith Yamasani258848d2012-08-10 17:06:33 -07002200 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002201 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2202 String[] disallowedPackages) {
2203 checkManageOrCreateUsersPermission(flags);
2204 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2205 }
2206
2207 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002208 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002209 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002210 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002211 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002212
Jessica Hummelbe81c802014-04-22 15:49:22 +01002213 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002214 return createUserInternal(name, flags, parentId, null);
2215 }
2216
2217 private UserInfo createUserInternal(String name, int flags, int parentId,
2218 String[] disallowedPackages) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002219 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002220 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2221 return null;
2222 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002223 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2224 }
2225
2226 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2227 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002228 DeviceStorageMonitorInternal dsm = LocalServices
2229 .getService(DeviceStorageMonitorInternal.class);
2230 if (dsm.isMemoryLow()) {
2231 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2232 return null;
2233 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002234 if (ActivityManager.isLowRamDeviceStatic()) {
2235 return null;
2236 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002237 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002238 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002239 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002240 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002241 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002242 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002243 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002244 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002245 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002246 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002247 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002248 if (parentId != UserHandle.USER_NULL) {
2249 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002250 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002251 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002252 if (parent == null) return null;
2253 }
2254 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2255 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2256 return null;
2257 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002258 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2259 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002260 // been reached, cannot add a user.
2261 return null;
2262 }
2263 // If we're adding a guest and there already exists one, bail.
2264 if (isGuest && findCurrentGuestUser() != null) {
2265 return null;
2266 }
2267 // In legacy mode, restricted profile's parent can only be the owner user
2268 if (isRestricted && !UserManager.isSplitSystemUser()
2269 && (parentId != UserHandle.USER_SYSTEM)) {
2270 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2271 return null;
2272 }
2273 if (isRestricted && UserManager.isSplitSystemUser()) {
2274 if (parent == null) {
2275 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2276 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002277 return null;
2278 }
Amith Yamasani12747872015-12-07 14:19:49 -08002279 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002280 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2281 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002282 return null;
2283 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002284 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002285 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2286 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002287 Log.e(LOG_TAG,
2288 "Ephemeral users are supported on split-system-user systems only.");
2289 return null;
2290 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002291 // In split system user mode, we assign the first human user the primary flag.
2292 // And if there is no device owner, we also assign the admin flag to primary user.
2293 if (UserManager.isSplitSystemUser()
2294 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2295 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002296 synchronized (mUsersLock) {
2297 if (!mIsDeviceManaged) {
2298 flags |= UserInfo.FLAG_ADMIN;
2299 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002300 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002301 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002302
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002303 userId = getNextAvailableId();
2304 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002305 boolean ephemeralGuests = Resources.getSystem()
2306 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002307
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002308 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002309 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2310 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2311 || (parent != null && parent.info.isEphemeral())) {
2312 flags |= UserInfo.FLAG_EPHEMERAL;
2313 }
2314
2315 userInfo = new UserInfo(userId, name, null, flags);
2316 userInfo.serialNumber = mNextSerialNumber++;
2317 long now = System.currentTimeMillis();
2318 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2319 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002320 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002321 userData = new UserData();
2322 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002323 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002324 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002325 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002326 writeUserListLP();
2327 if (parent != null) {
2328 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002329 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2330 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002331 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002332 }
Amith Yamasani12747872015-12-07 14:19:49 -08002333 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002334 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002335 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2336 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002337 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002338 }
Amith Yamasani12747872015-12-07 14:19:49 -08002339 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002340 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002341 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002342 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002343 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002344 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002345 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002346 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002347 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002348 userInfo.partial = false;
2349 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002350 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002351 }
2352 updateUserIds();
2353 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002354 if (isGuest) {
2355 synchronized (mGuestRestrictions) {
2356 restrictions.putAll(mGuestRestrictions);
2357 }
2358 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002359 synchronized (mRestrictionsLock) {
2360 mBaseUserRestrictions.append(userId, restrictions);
2361 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002362 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002363 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2364 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2365 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2366 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002367 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002368 } finally {
2369 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002370 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002371 return userInfo;
2372 }
2373
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002374 @VisibleForTesting
2375 UserData putUserInfo(UserInfo userInfo) {
2376 final UserData userData = new UserData();
2377 userData.info = userInfo;
2378 synchronized (mUsers) {
2379 mUsers.put(userInfo.id, userData);
2380 }
2381 return userData;
2382 }
2383
2384 @VisibleForTesting
2385 void removeUserInfo(int userId) {
2386 synchronized (mUsers) {
2387 mUsers.remove(userId);
2388 }
2389 }
2390
Amith Yamasani0b285492011-04-14 17:35:23 -07002391 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002392 * @hide
2393 */
Amith Yamasani12747872015-12-07 14:19:49 -08002394 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002395 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002396 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002397 final UserInfo user = createProfileForUser(
2398 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002399 if (user == null) {
2400 return null;
2401 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002402 long identity = Binder.clearCallingIdentity();
2403 try {
2404 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2405 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2406 // the putIntForUser() will fail.
2407 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2408 android.provider.Settings.Secure.LOCATION_MODE,
2409 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2410 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2411 } finally {
2412 Binder.restoreCallingIdentity(identity);
2413 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002414 return user;
2415 }
2416
2417 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002418 * Find the current guest user. If the Guest user is partial,
2419 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002420 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 private UserInfo findCurrentGuestUser() {
2422 synchronized (mUsersLock) {
2423 final int size = mUsers.size();
2424 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002425 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002426 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2427 return user;
2428 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002429 }
2430 }
2431 return null;
2432 }
2433
2434 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002435 * Mark this guest user for deletion to allow us to create another guest
2436 * and switch to that user before actually removing this guest.
2437 * @param userHandle the userid of the current guest
2438 * @return whether the user could be marked for deletion
2439 */
Amith Yamasani12747872015-12-07 14:19:49 -08002440 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002441 public boolean markGuestForDeletion(int userHandle) {
2442 checkManageUsersPermission("Only the system can remove users");
2443 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2444 UserManager.DISALLOW_REMOVE_USER, false)) {
2445 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2446 return false;
2447 }
2448
2449 long ident = Binder.clearCallingIdentity();
2450 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002451 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002452 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002453 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002454 userData = mUsers.get(userHandle);
2455 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002456 return false;
2457 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002458 }
Amith Yamasani12747872015-12-07 14:19:49 -08002459 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002460 return false;
2461 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002462 // We set this to a guest user that is to be removed. This is a temporary state
2463 // where we are allowed to add new Guest users, even if this one is still not
2464 // removed. This user will still show up in getUserInfo() calls.
2465 // If we don't get around to removing this Guest user, it will be purged on next
2466 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002467 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002468 // Mark it as disabled, so that it isn't returned any more when
2469 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002470 userData.info.flags |= UserInfo.FLAG_DISABLED;
2471 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002472 }
2473 } finally {
2474 Binder.restoreCallingIdentity(ident);
2475 }
2476 return true;
2477 }
2478
2479 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002480 * Removes a user and all data directories created for that user. This method should be called
2481 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002482 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002483 */
Amith Yamasani12747872015-12-07 14:19:49 -08002484 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002485 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002486 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002487 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2488 UserManager.DISALLOW_REMOVE_USER, false)) {
2489 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2490 return false;
2491 }
2492
Kenny Guyee58b4f2014-05-23 15:19:53 +01002493 long ident = Binder.clearCallingIdentity();
2494 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002495 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002496 int currentUser = ActivityManager.getCurrentUser();
2497 if (currentUser == userHandle) {
2498 Log.w(LOG_TAG, "Current user cannot be removed");
2499 return false;
2500 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002501 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002502 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002503 userData = mUsers.get(userHandle);
2504 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002505 return false;
2506 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002507
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002508 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002509 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002510
Kenny Guyee58b4f2014-05-23 15:19:53 +01002511 try {
2512 mAppOpsService.removeUser(userHandle);
2513 } catch (RemoteException e) {
2514 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2515 }
2516 // Set this to a partially created user, so that the user will be purged
2517 // on next startup, in case the runtime stops now before stopping and
2518 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002519 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002520 // Mark it as disabled, so that it isn't returned any more when
2521 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002522 userData.info.flags |= UserInfo.FLAG_DISABLED;
2523 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002524 }
2525
Amith Yamasani12747872015-12-07 14:19:49 -08002526 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2527 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002528 // Send broadcast to notify system that the user removed was a
2529 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002530 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002531 }
2532
2533 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2534 int res;
2535 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002536 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2537 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002538 @Override
2539 public void userStopped(int userId) {
2540 finishRemoveUser(userId);
2541 }
2542 @Override
2543 public void userStopAborted(int userId) {
2544 }
2545 });
2546 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002547 return false;
2548 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002549 return res == ActivityManager.USER_OP_SUCCESS;
2550 } finally {
2551 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002552 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002553 }
2554
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002555 @VisibleForTesting
2556 void addRemovingUserIdLocked(int userId) {
2557 // We remember deleted user IDs to prevent them from being
2558 // reused during the current boot; they can still be reused
2559 // after a reboot or recycling of userIds.
2560 mRemovingUserIds.put(userId, true);
2561 mRecentlyRemovedIds.add(userId);
2562 // Keep LRU queue of recently removed IDs for recycling
2563 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2564 mRecentlyRemovedIds.removeFirst();
2565 }
2566 }
2567
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002568 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002569 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002570 // Let other services shutdown any activity and clean up their state before completely
2571 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002572 long ident = Binder.clearCallingIdentity();
2573 try {
2574 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2575 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002576 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2577 android.Manifest.permission.MANAGE_USERS,
2578
2579 new BroadcastReceiver() {
2580 @Override
2581 public void onReceive(Context context, Intent intent) {
2582 if (DBG) {
2583 Slog.i(LOG_TAG,
2584 "USER_REMOVED broadcast sent, cleaning up user data "
2585 + userHandle);
2586 }
2587 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002588 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002589 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002590 // Clean up any ActivityManager state
2591 LocalServices.getService(ActivityManagerInternal.class)
2592 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002593 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002594 }
2595 }.start();
2596 }
2597 },
2598
2599 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002600 } finally {
2601 Binder.restoreCallingIdentity(ident);
2602 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002603 }
2604
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002605 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002606 try {
2607 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2608 } catch (IllegalStateException e) {
2609 // This may be simply because the user was partially created.
2610 Slog.i(LOG_TAG,
2611 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2612 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002613
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002614 // Cleanup gatekeeper secure user id
2615 try {
2616 final IGateKeeperService gk = GateKeeper.getService();
2617 if (gk != null) {
2618 gk.clearSecureUserId(userHandle);
2619 }
2620 } catch (Exception ex) {
2621 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2622 }
2623
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002624 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002625 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002626
2627 // Clean up all data before removing metadata
2628 mPm.destroyUserData(userHandle,
2629 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2630
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002631 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002632 synchronized (mUsersLock) {
2633 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002634 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002635 }
2636 synchronized (mUserStates) {
2637 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002638 }
2639 synchronized (mRestrictionsLock) {
2640 mBaseUserRestrictions.remove(userHandle);
2641 mAppliedUserRestrictions.remove(userHandle);
2642 mCachedEffectiveUserRestrictions.remove(userHandle);
2643 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002644 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002645 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002646 synchronized (mPackagesLock) {
2647 writeUserListLP();
2648 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002649 // Remove user file
2650 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2651 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002652 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002653 if (RELEASE_DELETED_USER_ID) {
2654 synchronized (mUsers) {
2655 mRemovingUserIds.delete(userHandle);
2656 }
2657 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002658 }
2659
Kenny Guyf8d3a232014-05-15 16:09:52 +01002660 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002661 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002662 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2663 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002664 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002665 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002666 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002667 }
2668
Amith Yamasani2a003292012-08-14 18:25:45 -07002669 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002670 public Bundle getApplicationRestrictions(String packageName) {
2671 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2672 }
2673
2674 @Override
2675 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002676 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002677 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002678 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002679 }
2680 synchronized (mPackagesLock) {
2681 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002682 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002683 }
2684 }
2685
2686 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002687 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002688 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002689 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002690 if (restrictions != null) {
2691 restrictions.setDefusable(true);
2692 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002693 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002694 if (restrictions == null || restrictions.isEmpty()) {
2695 cleanAppRestrictionsForPackage(packageName, userId);
2696 } else {
2697 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002698 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002699 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002700 }
Robin Lee66e5d962014-04-09 16:44:21 +01002701
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002702 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2703 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2704 changeIntent.setPackage(packageName);
2705 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2706 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002707 }
2708
2709 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002710 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002711 try {
2712 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002713 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002714 } catch (NameNotFoundException nnfe) {
2715 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002716 } finally {
2717 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002718 }
2719 }
2720
Fyodor Kupolov82402752015-10-28 14:54:51 -07002721 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002722 AtomicFile restrictionsFile =
2723 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2724 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002725 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002726 }
2727
2728 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002729 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002730 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002731 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002732 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002733 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002734 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002735
2736 FileInputStream fis = null;
2737 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002738 fis = restrictionsFile.openRead();
2739 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002740 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002741 XmlUtils.nextElement(parser);
2742 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002743 Slog.e(LOG_TAG, "Unable to read restrictions file "
2744 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002745 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002746 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002747 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2748 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002749 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002750 } catch (IOException|XmlPullParserException e) {
2751 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002752 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002753 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002754 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002755 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002756 }
2757
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002758 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2759 XmlPullParser parser) throws XmlPullParserException, IOException {
2760 int type = parser.getEventType();
2761 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2762 String key = parser.getAttributeValue(null, ATTR_KEY);
2763 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2764 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2765 if (multiple != null) {
2766 values.clear();
2767 int count = Integer.parseInt(multiple);
2768 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2769 if (type == XmlPullParser.START_TAG
2770 && parser.getName().equals(TAG_VALUE)) {
2771 values.add(parser.nextText().trim());
2772 count--;
2773 }
2774 }
2775 String [] valueStrings = new String[values.size()];
2776 values.toArray(valueStrings);
2777 restrictions.putStringArray(key, valueStrings);
2778 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2779 restrictions.putBundle(key, readBundleEntry(parser, values));
2780 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2781 final int outerDepth = parser.getDepth();
2782 ArrayList<Bundle> bundleList = new ArrayList<>();
2783 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2784 Bundle childBundle = readBundleEntry(parser, values);
2785 bundleList.add(childBundle);
2786 }
2787 restrictions.putParcelableArray(key,
2788 bundleList.toArray(new Bundle[bundleList.size()]));
2789 } else {
2790 String value = parser.nextText().trim();
2791 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2792 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2793 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2794 restrictions.putInt(key, Integer.parseInt(value));
2795 } else {
2796 restrictions.putString(key, value);
2797 }
2798 }
2799 }
2800 }
2801
2802 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2803 throws IOException, XmlPullParserException {
2804 Bundle childBundle = new Bundle();
2805 final int outerDepth = parser.getDepth();
2806 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2807 readEntry(childBundle, values, parser);
2808 }
2809 return childBundle;
2810 }
2811
Fyodor Kupolov82402752015-10-28 14:54:51 -07002812 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002813 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002814 AtomicFile restrictionsFile = new AtomicFile(
2815 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002816 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002817 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002818 }
2819
2820 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002821 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002822 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002823 try {
2824 fos = restrictionsFile.startWrite();
2825 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2826
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002827 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002828 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002829 serializer.startDocument(null, true);
2830 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2831
2832 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002833 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002834 serializer.endTag(null, TAG_RESTRICTIONS);
2835
2836 serializer.endDocument();
2837 restrictionsFile.finishWrite(fos);
2838 } catch (Exception e) {
2839 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002840 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2841 }
2842 }
2843
2844 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2845 throws IOException {
2846 for (String key : restrictions.keySet()) {
2847 Object value = restrictions.get(key);
2848 serializer.startTag(null, TAG_ENTRY);
2849 serializer.attribute(null, ATTR_KEY, key);
2850
2851 if (value instanceof Boolean) {
2852 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2853 serializer.text(value.toString());
2854 } else if (value instanceof Integer) {
2855 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2856 serializer.text(value.toString());
2857 } else if (value == null || value instanceof String) {
2858 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2859 serializer.text(value != null ? (String) value : "");
2860 } else if (value instanceof Bundle) {
2861 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2862 writeBundle((Bundle) value, serializer);
2863 } else if (value instanceof Parcelable[]) {
2864 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2865 Parcelable[] array = (Parcelable[]) value;
2866 for (Parcelable parcelable : array) {
2867 if (!(parcelable instanceof Bundle)) {
2868 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2869 }
2870 serializer.startTag(null, TAG_ENTRY);
2871 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2872 writeBundle((Bundle) parcelable, serializer);
2873 serializer.endTag(null, TAG_ENTRY);
2874 }
2875 } else {
2876 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2877 String[] values = (String[]) value;
2878 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2879 for (String choice : values) {
2880 serializer.startTag(null, TAG_VALUE);
2881 serializer.text(choice != null ? choice : "");
2882 serializer.endTag(null, TAG_VALUE);
2883 }
2884 }
2885 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002886 }
2887 }
2888
2889 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002890 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002892 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002893 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002894 }
2895 }
2896
2897 @Override
2898 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002899 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002900 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002901 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002902 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002903 }
2904 // Not found
2905 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002906 }
2907 }
2908
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002909 @Override
2910 public long getUserCreationTime(int userHandle) {
2911 int callingUserId = UserHandle.getCallingUserId();
2912 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002913 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002914 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002915 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002916 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002917 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002918 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002919 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002920 }
2921 }
2922 }
2923 if (userInfo == null) {
2924 throw new SecurityException("userHandle can only be the calling user or a managed "
2925 + "profile associated with this user");
2926 }
2927 return userInfo.creationTime;
2928 }
2929
Amith Yamasani0b285492011-04-14 17:35:23 -07002930 /**
2931 * Caches the list of user ids in an array, adjusting the array size when necessary.
2932 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002933 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002934 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002935 synchronized (mUsersLock) {
2936 final int userSize = mUsers.size();
2937 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002938 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002939 num++;
2940 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002941 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002942 final int[] newUsers = new int[num];
2943 int n = 0;
2944 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002945 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002946 newUsers[n++] = mUsers.keyAt(i);
2947 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002948 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002949 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002950 }
2951 }
2952
2953 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002954 * Called right before a user is started. This gives us a chance to prepare
2955 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002956 */
2957 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002958 UserInfo userInfo = getUserInfo(userId);
2959 if (userInfo == null) {
2960 return;
2961 }
2962 final int userSerial = userInfo.serialNumber;
2963 // Migrate only if build fingerprints mismatch
2964 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002965 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002966 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002967
2968 if (userId != UserHandle.USER_SYSTEM) {
2969 synchronized (mRestrictionsLock) {
2970 applyUserRestrictionsLR(userId);
2971 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002972 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002973
2974 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002975 }
2976
2977 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002978 * Called right before a user is unlocked. This gives us a chance to prepare
2979 * app storage.
2980 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002981 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002982 UserInfo userInfo = getUserInfo(userId);
2983 if (userInfo == null) {
2984 return;
2985 }
2986 final int userSerial = userInfo.serialNumber;
2987 // Migrate only if build fingerprints mismatch
2988 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002989 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002990 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002991 }
2992
2993 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002994 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002995 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002996 * @param userId the user that was just foregrounded
2997 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002998 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002999 UserData userData = getUserDataNoChecks(userId);
3000 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003001 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3002 return;
3003 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003004
3005 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003006 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003007 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003008 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003009 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3010 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003011 }
3012
Amith Yamasanieb437d42016-04-29 09:31:25 -07003013 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07003014 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07003015 String demoLauncher =
3016 mContext.getResources().getString(
3017 com.android.internal.R.string.config_demoModeLauncherComponent);
3018 if (!TextUtils.isEmpty(demoLauncher)) {
3019 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07003020 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00003021 try {
3022 final IPackageManager iPm = AppGlobals.getPackageManager();
3023 iPm.setComponentEnabledSetting(componentToEnable,
3024 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3025 /* userId= */ userId);
3026 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3027 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3028 /* userId= */ userId, null);
3029 } catch (RemoteException re) {
3030 // Internal, shouldn't happen
3031 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003032 }
3033 }
3034 }
3035
Amith Yamasani920ace02012-09-20 22:15:37 -07003036 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003037 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003038 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003039 @VisibleForTesting
3040 int getNextAvailableId() {
3041 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003042 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003043 nextId = scanNextAvailableIdLocked();
3044 if (nextId >= 0) {
3045 return nextId;
3046 }
3047 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3048 // except most recently removed
3049 if (mRemovingUserIds.size() > 0) {
3050 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3051 mRemovingUserIds.clear();
3052 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3053 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003054 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003055 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003056 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003057 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003058 if (nextId < 0) {
3059 throw new IllegalStateException("No user id available!");
3060 }
3061 return nextId;
3062 }
3063
3064 private int scanNextAvailableIdLocked() {
3065 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3066 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3067 return i;
3068 }
3069 }
3070 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003071 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003072
Amith Yamasanifc95e702013-09-26 13:20:17 -07003073 private String packageToRestrictionsFileName(String packageName) {
3074 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3075 }
3076
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003077 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003078 * Enforce that serial number stored in user directory inode matches the
3079 * given expected value. Gracefully sets the serial number if currently
3080 * undefined.
3081 *
3082 * @throws IOException when problem extracting serial number, or serial
3083 * number is mismatched.
3084 */
3085 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003086 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3087 // When we're emulating FBE, the directory may have been chmod
3088 // 000'ed, meaning we can't read the serial number to enforce it;
3089 // instead of destroying the user, just log a warning.
3090 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3091 return;
3092 }
3093
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003094 final int foundSerial = getSerialNumber(file);
3095 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3096
3097 if (foundSerial == -1) {
3098 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3099 try {
3100 setSerialNumber(file, serialNumber);
3101 } catch (IOException e) {
3102 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3103 }
3104
3105 } else if (foundSerial != serialNumber) {
3106 throw new IOException("Found serial number " + foundSerial
3107 + " doesn't match expected " + serialNumber);
3108 }
3109 }
3110
3111 /**
3112 * Set serial number stored in user directory inode.
3113 *
3114 * @throws IOException if serial number was already set
3115 */
3116 private static void setSerialNumber(File file, int serialNumber)
3117 throws IOException {
3118 try {
3119 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3120 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3121 } catch (ErrnoException e) {
3122 throw e.rethrowAsIOException();
3123 }
3124 }
3125
3126 /**
3127 * Return serial number stored in user directory inode.
3128 *
3129 * @return parsed serial number, or -1 if not set
3130 */
3131 private static int getSerialNumber(File file) throws IOException {
3132 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003133 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3134 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003135 try {
3136 return Integer.parseInt(serial);
3137 } catch (NumberFormatException e) {
3138 throw new IOException("Bad serial number: " + serial);
3139 }
3140 } catch (ErrnoException e) {
3141 if (e.errno == OsConstants.ENODATA) {
3142 return -1;
3143 } else {
3144 throw e.rethrowAsIOException();
3145 }
3146 }
3147 }
3148
Amith Yamasani920ace02012-09-20 22:15:37 -07003149 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003150 public void setSeedAccountData(int userId, String accountName, String accountType,
3151 PersistableBundle accountOptions, boolean persist) {
3152 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3153 synchronized (mPackagesLock) {
3154 final UserData userData;
3155 synchronized (mUsersLock) {
3156 userData = getUserDataLU(userId);
3157 if (userData == null) {
3158 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3159 return;
3160 }
3161 userData.seedAccountName = accountName;
3162 userData.seedAccountType = accountType;
3163 userData.seedAccountOptions = accountOptions;
3164 userData.persistSeedData = persist;
3165 }
3166 if (persist) {
3167 writeUserLP(userData);
3168 }
3169 }
3170 }
3171
3172 @Override
3173 public String getSeedAccountName() throws RemoteException {
3174 checkManageUsersPermission("Cannot get seed account information");
3175 synchronized (mUsersLock) {
3176 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3177 return userData.seedAccountName;
3178 }
3179 }
3180
3181 @Override
3182 public String getSeedAccountType() throws RemoteException {
3183 checkManageUsersPermission("Cannot get seed account information");
3184 synchronized (mUsersLock) {
3185 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3186 return userData.seedAccountType;
3187 }
3188 }
3189
3190 @Override
3191 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3192 checkManageUsersPermission("Cannot get seed account information");
3193 synchronized (mUsersLock) {
3194 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3195 return userData.seedAccountOptions;
3196 }
3197 }
3198
3199 @Override
3200 public void clearSeedAccountData() throws RemoteException {
3201 checkManageUsersPermission("Cannot clear seed account information");
3202 synchronized (mPackagesLock) {
3203 UserData userData;
3204 synchronized (mUsersLock) {
3205 userData = getUserDataLU(UserHandle.getCallingUserId());
3206 if (userData == null) return;
3207 userData.clearSeedAccountData();
3208 }
3209 writeUserLP(userData);
3210 }
3211 }
3212
3213 @Override
3214 public boolean someUserHasSeedAccount(String accountName, String accountType)
3215 throws RemoteException {
3216 checkManageUsersPermission("Cannot check seed account information");
3217 synchronized (mUsersLock) {
3218 final int userSize = mUsers.size();
3219 for (int i = 0; i < userSize; i++) {
3220 final UserData data = mUsers.valueAt(i);
3221 if (data.info.isInitialized()) continue;
3222 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3223 continue;
3224 }
3225 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3226 continue;
3227 }
3228 return true;
3229 }
3230 }
3231 return false;
3232 }
3233
3234 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003235 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003236 FileDescriptor err, String[] args, ShellCallback callback,
3237 ResultReceiver resultReceiver) {
3238 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003239 }
3240
3241 int onShellCommand(Shell shell, String cmd) {
3242 if (cmd == null) {
3243 return shell.handleDefaultCommands(cmd);
3244 }
3245
3246 final PrintWriter pw = shell.getOutPrintWriter();
3247 try {
3248 switch(cmd) {
3249 case "list":
3250 return runList(pw);
3251 }
3252 } catch (RemoteException e) {
3253 pw.println("Remote exception: " + e);
3254 }
3255 return -1;
3256 }
3257
3258 private int runList(PrintWriter pw) throws RemoteException {
3259 final IActivityManager am = ActivityManagerNative.getDefault();
3260 final List<UserInfo> users = getUsers(false);
3261 if (users == null) {
3262 pw.println("Error: couldn't get users");
3263 return 1;
3264 } else {
3265 pw.println("Users:");
3266 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003267 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003268 pw.println("\t" + users.get(i).toString() + running);
3269 }
3270 return 0;
3271 }
3272 }
3273
3274 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003275 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3276 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3277 != PackageManager.PERMISSION_GRANTED) {
3278 pw.println("Permission Denial: can't dump UserManager from from pid="
3279 + Binder.getCallingPid()
3280 + ", uid=" + Binder.getCallingUid()
3281 + " without permission "
3282 + android.Manifest.permission.DUMP);
3283 return;
3284 }
3285
3286 long now = System.currentTimeMillis();
3287 StringBuilder sb = new StringBuilder();
3288 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003289 synchronized (mUsersLock) {
3290 pw.println("Users:");
3291 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003292 UserData userData = mUsers.valueAt(i);
3293 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003294 continue;
3295 }
Amith Yamasani12747872015-12-07 14:19:49 -08003296 UserInfo userInfo = userData.info;
3297 final int userId = userInfo.id;
3298 pw.print(" "); pw.print(userInfo);
3299 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003300 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003301 pw.print(" <removing> ");
3302 }
Amith Yamasani12747872015-12-07 14:19:49 -08003303 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003304 pw.print(" <partial>");
3305 }
3306 pw.println();
3307 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003308 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003309 pw.println("<unknown>");
3310 } else {
3311 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003312 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003313 sb.append(" ago");
3314 pw.println(sb);
3315 }
3316 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003317 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003318 pw.println("<unknown>");
3319 } else {
3320 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003321 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003322 sb.append(" ago");
3323 pw.println(sb);
3324 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003325 pw.print(" Last logged in fingerprint: ");
3326 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003327 pw.print(" Has profile owner: ");
3328 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003329 pw.println(" Restrictions:");
3330 synchronized (mRestrictionsLock) {
3331 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003332 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003333 pw.println(" Device policy local restrictions:");
3334 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003335 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003336 pw.println(" Effective restrictions:");
3337 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003338 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003339 }
Amith Yamasani12747872015-12-07 14:19:49 -08003340
3341 if (userData.account != null) {
3342 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003343 pw.println();
3344 }
Amith Yamasani12747872015-12-07 14:19:49 -08003345
3346 if (userData.seedAccountName != null) {
3347 pw.print(" Seed account name: " + userData.seedAccountName);
3348 pw.println();
3349 if (userData.seedAccountType != null) {
3350 pw.print(" account type: " + userData.seedAccountType);
3351 pw.println();
3352 }
3353 if (userData.seedAccountOptions != null) {
3354 pw.print(" account options exist");
3355 pw.println();
3356 }
3357 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003358 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003359 }
Amith Yamasani12747872015-12-07 14:19:49 -08003360 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003361 pw.println(" Device policy global restrictions:");
3362 synchronized (mRestrictionsLock) {
3363 UserRestrictionsUtils
3364 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3365 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003366 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003367 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3368 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003369 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003370 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003371 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003372 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003373 synchronized (mUsersLock) {
3374 pw.println();
3375 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003376 if (mRemovingUserIds.size() > 0) {
3377 pw.println();
3378 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3379 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003380 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003381 synchronized (mUserStates) {
3382 pw.println(" Started users state: " + mUserStates);
3383 }
Amith Yamasani12747872015-12-07 14:19:49 -08003384 // Dump some capabilities
3385 pw.println();
3386 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3387 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003388 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3389 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003390 }
3391 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003392
3393 final class MainHandler extends Handler {
3394
3395 @Override
3396 public void handleMessage(Message msg) {
3397 switch (msg.what) {
3398 case WRITE_USER_MSG:
3399 removeMessages(WRITE_USER_MSG, msg.obj);
3400 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003401 int userId = ((UserData) msg.obj).info.id;
3402 UserData userData = getUserDataNoChecks(userId);
3403 if (userData != null) {
3404 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003405 }
3406 }
3407 }
3408 }
3409 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003410
3411 /**
3412 * @param userId
3413 * @return whether the user has been initialized yet
3414 */
3415 boolean isInitialized(int userId) {
3416 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3417 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003418
3419 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003420 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003421 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3422 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003423 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003424 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003425 }
3426
3427 @Override
3428 public Bundle getBaseUserRestrictions(int userId) {
3429 synchronized (mRestrictionsLock) {
3430 return mBaseUserRestrictions.get(userId);
3431 }
3432 }
3433
3434 @Override
3435 public void setBaseUserRestrictionsByDpmsForMigration(
3436 int userId, Bundle baseRestrictions) {
3437 synchronized (mRestrictionsLock) {
3438 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003439 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003440 }
3441
Amith Yamasani12747872015-12-07 14:19:49 -08003442 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003443 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003444 if (userData != null) {
3445 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003446 } else {
3447 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3448 }
3449 }
3450 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003451
3452 @Override
3453 public boolean getUserRestriction(int userId, String key) {
3454 return getUserRestrictions(userId).getBoolean(key);
3455 }
3456
3457 @Override
3458 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3459 synchronized (mUserRestrictionsListeners) {
3460 mUserRestrictionsListeners.add(listener);
3461 }
3462 }
3463
3464 @Override
3465 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3466 synchronized (mUserRestrictionsListeners) {
3467 mUserRestrictionsListeners.remove(listener);
3468 }
3469 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003470
3471 @Override
3472 public void setDeviceManaged(boolean isManaged) {
3473 synchronized (mUsersLock) {
3474 mIsDeviceManaged = isManaged;
3475 }
3476 }
3477
3478 @Override
3479 public void setUserManaged(int userId, boolean isManaged) {
3480 synchronized (mUsersLock) {
3481 mIsUserManaged.put(userId, isManaged);
3482 }
3483 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003484
3485 @Override
3486 public void setUserIcon(int userId, Bitmap bitmap) {
3487 long ident = Binder.clearCallingIdentity();
3488 try {
3489 synchronized (mPackagesLock) {
3490 UserData userData = getUserDataNoChecks(userId);
3491 if (userData == null || userData.info.partial) {
3492 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3493 return;
3494 }
3495 writeBitmapLP(userData.info, bitmap);
3496 writeUserLP(userData);
3497 }
3498 sendUserInfoChangedBroadcast(userId);
3499 } finally {
3500 Binder.restoreCallingIdentity(ident);
3501 }
3502 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003503
3504 @Override
3505 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3506 synchronized (mUsersLock) {
3507 mForceEphemeralUsers = forceEphemeralUsers;
3508 }
3509 }
3510
3511 @Override
3512 public void removeAllUsers() {
3513 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3514 // Remove the non-system users straight away.
3515 removeNonSystemUsers();
3516 } else {
3517 // Switch to the system user first and then remove the other users.
3518 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3519 @Override
3520 public void onReceive(Context context, Intent intent) {
3521 int userId =
3522 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3523 if (userId != UserHandle.USER_SYSTEM) {
3524 return;
3525 }
3526 mContext.unregisterReceiver(this);
3527 removeNonSystemUsers();
3528 }
3529 };
3530 IntentFilter userSwitchedFilter = new IntentFilter();
3531 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3532 mContext.registerReceiver(
3533 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3534
3535 // Switch to the system user.
3536 ActivityManager am =
3537 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3538 am.switchUser(UserHandle.USER_SYSTEM);
3539 }
3540 }
phweisse9c44062016-02-10 12:57:38 +01003541
3542 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003543 public void onEphemeralUserStop(int userId) {
3544 synchronized (mUsersLock) {
3545 UserInfo userInfo = getUserInfoLU(userId);
3546 if (userInfo != null && userInfo.isEphemeral()) {
3547 // Do not allow switching back to the ephemeral user again as the user is going
3548 // to be deleted.
3549 userInfo.flags |= UserInfo.FLAG_DISABLED;
3550 if (userInfo.isGuest()) {
3551 // Indicate that the guest will be deleted after it stops.
3552 userInfo.guestToRemove = true;
3553 }
3554 }
3555 }
3556 }
3557
3558 @Override
phweisse9c44062016-02-10 12:57:38 +01003559 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003560 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003561 // Keep this in sync with UserManager.createUser
3562 if (user != null && !user.isAdmin()) {
3563 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3564 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3565 }
3566 return user;
3567 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003568
3569 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003570 public boolean isUserRunning(int userId) {
3571 synchronized (mUserStates) {
3572 return mUserStates.get(userId, -1) >= 0;
3573 }
3574 }
3575
3576 @Override
3577 public void setUserState(int userId, int userState) {
3578 synchronized (mUserStates) {
3579 mUserStates.put(userId, userState);
3580 }
3581 }
3582
3583 @Override
3584 public void removeUserState(int userId) {
3585 synchronized (mUserStates) {
3586 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003587 }
3588 }
3589
3590 @Override
3591 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003592 synchronized (mUserStates) {
3593 int state = mUserStates.get(userId, -1);
3594 return (state == UserState.STATE_RUNNING_UNLOCKING)
3595 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003596 }
3597 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003598 }
3599
3600 /* Remove all the users except of the system one. */
3601 private void removeNonSystemUsers() {
3602 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3603 synchronized (mUsersLock) {
3604 final int userSize = mUsers.size();
3605 for (int i = 0; i < userSize; i++) {
3606 UserInfo ui = mUsers.valueAt(i).info;
3607 if (ui.id != UserHandle.USER_SYSTEM) {
3608 usersToRemove.add(ui);
3609 }
3610 }
3611 }
3612 for (UserInfo ui: usersToRemove) {
3613 removeUser(ui.id);
3614 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003615 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003616
3617 private class Shell extends ShellCommand {
3618 @Override
3619 public int onCommand(String cmd) {
3620 return onShellCommand(this, cmd);
3621 }
3622
3623 @Override
3624 public void onHelp() {
3625 final PrintWriter pw = getOutPrintWriter();
3626 pw.println("User manager (user) commands:");
3627 pw.println(" help");
3628 pw.println(" Print this help text.");
3629 pw.println("");
3630 pw.println(" list");
3631 pw.println(" Prints all users on the system.");
3632 }
3633 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003634
3635 private static void debug(String message) {
3636 Log.d(LOG_TAG, message +
3637 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3638 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003639}