blob: 6498b0ec0f767a5df0745e8bb1429e55acbfac8b [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000036import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.content.Context;
38import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010039import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010040import android.content.IntentSender;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000041import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070042import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080043import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070068import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080070import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010071import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070072import android.security.GateKeeper;
73import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070074import android.system.ErrnoException;
75import android.system.Os;
76import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070077import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080092import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070093import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070094import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000095import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070096import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070097import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000098import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070099import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +0100100
Jeff Sharkey47f71082016-02-01 17:03:54 -0700101import libcore.io.IoUtils;
102import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800103
104import org.xmlpull.v1.XmlPullParser;
105import org.xmlpull.v1.XmlPullParserException;
106import org.xmlpull.v1.XmlSerializer;
107
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108import java.io.BufferedOutputStream;
109import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700110import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113import java.io.FileOutputStream;
114import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700115import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100116import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117import java.util.ArrayList;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700118import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.util.List;
120
Makoto Onuki068c54a2015-10-13 14:34:03 -0700121/**
122 * Service for {@link UserManager}.
123 *
124 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700125 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800126 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700127 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
128 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
129 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700130 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700131public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700132
Amith Yamasani2a003292012-08-14 18:25:45 -0700133 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800134 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800135 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700136 // Can be used for manual testing of id recycling
137 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700138
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800140 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700142 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700144 private static final String ATTR_CREATION_TIME = "created";
145 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600146 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700147 private static final String ATTR_SERIAL_NO = "serialNumber";
148 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700149 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700150 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700151 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100152 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700153 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800154 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
155 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530156 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700158 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800159 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800160 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100161 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800162 private static final String TAG_ENTRY = "entry";
163 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800164 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800165 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700166 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800167 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700168
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700169 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
170 private static final String ATTR_TYPE_STRING = "s";
171 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700172 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700173 private static final String ATTR_TYPE_BUNDLE = "B";
174 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700175
Amith Yamasani0b285492011-04-14 17:35:23 -0700176 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700177 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700178 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100179 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700180
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800181 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700182 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800183
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700184 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
185 UserInfo.FLAG_MANAGED_PROFILE
186 | UserInfo.FLAG_EPHEMERAL
187 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700188 | UserInfo.FLAG_GUEST
189 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700190
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700191 @VisibleForTesting
192 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700193 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700194 @VisibleForTesting
195 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
196
197 // Max size of the queue of recently removed users
198 @VisibleForTesting
199 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700200
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700201 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700202
Amith Yamasani920ace02012-09-20 22:15:37 -0700203 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
204
Nicolas Prevotb8186812015-08-06 15:00:03 +0100205 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700206 // without first making sure that the rest of the framework is prepared for it.
207 private static final int MAX_MANAGED_PROFILES = 1;
208
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800209 static final int WRITE_USER_MSG = 1;
210 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530211
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700212 private static final String XATTR_SERIAL = "user.serial";
213
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800214 // Tron counters
215 private static final String TRON_GUEST_CREATED = "users_guest_created";
216 private static final String TRON_USER_CREATED = "users_user_created";
217
Dianne Hackborn4428e172012-08-24 17:43:05 -0700218 private final Context mContext;
219 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700220 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700221 // Short-term lock for internal state, when interaction/sync with PM is not required
222 private final Object mUsersLock = new Object();
223 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700224
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800225 private final Handler mHandler;
226
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700227 private final File mUsersDir;
228 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800230 private static final IBinder mUserRestriconToken = new Binder();
231
Makoto Onuki068c54a2015-10-13 14:34:03 -0700232 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800233 * User-related information that is used for persisting to flash. Only UserInfo is
234 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800235 */
Amith Yamasani12747872015-12-07 14:19:49 -0800236 private static class UserData {
237 // Basic user information and properties
238 UserInfo info;
239 // Account name used when there is a strong association between a user and an account
240 String account;
241 // Account information for seeding into a newly created user. This could also be
242 // used for login validation for an existing user, for updating their credentials.
243 // In the latter case, data may not need to be persisted as it is only valid for the
244 // current login session.
245 String seedAccountName;
246 String seedAccountType;
247 PersistableBundle seedAccountOptions;
248 // Whether to perist the seed account information to be available after a boot
249 boolean persistSeedData;
250
251 void clearSeedAccountData() {
252 seedAccountName = null;
253 seedAccountType = null;
254 seedAccountOptions = null;
255 persistSeedData = false;
256 }
257 }
258
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800259 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800260 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800261
262 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700263 * User restrictions set via UserManager. This doesn't include restrictions set by
264 * device owner / profile owners.
265 *
266 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
267 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
268 * maybe shared between {@link #mBaseUserRestrictions} and
269 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
270 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700271 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700272 */
273 @GuardedBy("mRestrictionsLock")
274 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
275
276 /**
277 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
278 * with device / profile owner restrictions. We'll initialize it lazily; use
279 * {@link #getEffectiveUserRestrictions} to access it.
280 *
281 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
282 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
283 * maybe shared between {@link #mBaseUserRestrictions} and
284 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
285 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700286 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700287 */
288 @GuardedBy("mRestrictionsLock")
289 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
290
Makoto Onuki4f160732015-10-27 17:15:38 -0700291 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800292 * User restrictions that have already been applied in
293 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
294 * that have changed since the last
295 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700296 */
297 @GuardedBy("mRestrictionsLock")
298 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
299
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800300 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800301 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
302 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800303 */
304 @GuardedBy("mRestrictionsLock")
305 private Bundle mDevicePolicyGlobalUserRestrictions;
306
307 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100308 * Id of the user that set global restrictions.
309 */
310 @GuardedBy("mRestrictionsLock")
311 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
312
313 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800314 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
315 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800316 */
317 @GuardedBy("mRestrictionsLock")
318 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
319
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800320 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530321 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800322
323 /**
324 * Set of user IDs being actively removed. Removed IDs linger in this set
325 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700326 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800327 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700328 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800329 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700330
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700331 /**
332 * Queue of recently removed userIds. Used for recycling of userIds
333 */
334 @GuardedBy("mUsersLock")
335 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
336
Fyodor Kupolov82402752015-10-28 14:54:51 -0700337 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700338 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800339 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700340 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700341 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700342
Jason Monk62062992014-05-06 09:55:28 -0400343 private IAppOpsService mAppOpsService;
344
Makoto Onuki068c54a2015-10-13 14:34:03 -0700345 private final LocalService mLocalService;
346
Makoto Onukie7927da2015-11-25 10:05:17 -0800347 @GuardedBy("mUsersLock")
348 private boolean mIsDeviceManaged;
349
350 @GuardedBy("mUsersLock")
351 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
352
Makoto Onukid45a4a22015-11-02 17:17:38 -0800353 @GuardedBy("mUserRestrictionsListeners")
354 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
355 new ArrayList<>();
356
Clara Bayarria1771112015-12-18 16:29:18 +0000357 private final LockPatternUtils mLockPatternUtils;
358
Ricky Waib1dd80b2016-06-07 18:00:55 +0100359 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
360 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
361
362 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
363 @Override
364 public void onReceive(Context context, Intent intent) {
365 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
366 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
367 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
368 setQuietModeEnabled(userHandle, false);
369 if (target != null) {
370 try {
371 mContext.startIntentSender(target, null, 0, 0, 0);
372 } catch (IntentSender.SendIntentException e) {
373 /* ignore */
374 }
375 }
376 }
377 }
378 };
379
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100380 /**
381 * Whether all users should be created ephemeral.
382 */
383 @GuardedBy("mUsersLock")
384 private boolean mForceEphemeralUsers;
385
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000386 @GuardedBy("mUserStates")
387 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700388
Amith Yamasani258848d2012-08-10 17:06:33 -0700389 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700390
Dianne Hackborn4428e172012-08-24 17:43:05 -0700391 public static UserManagerService getInstance() {
392 synchronized (UserManagerService.class) {
393 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700394 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700396
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700397 public static class LifeCycle extends SystemService {
398
399 private UserManagerService mUms;
400
401 /**
402 * @param context
403 */
404 public LifeCycle(Context context) {
405 super(context);
406 }
407
408 @Override
409 public void onStart() {
410 mUms = UserManagerService.getInstance();
411 publishBinderService(Context.USER_SERVICE, mUms);
412 }
413
414 @Override
415 public void onBootPhase(int phase) {
416 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
417 mUms.cleanupPartialUsers();
418 }
419 }
420 }
421
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700422 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800423 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700424 UserManagerService(Context context) {
425 this(context, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700426 }
427
Dianne Hackborn4428e172012-08-24 17:43:05 -0700428 /**
429 * Called by package manager to create the service. This is closely
430 * associated with the package manager, and the given lock is the
431 * package manager's own lock.
432 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800433 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
434 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700435 }
436
Dianne Hackborn4428e172012-08-24 17:43:05 -0700437 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800438 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 mContext = context;
440 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700441 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800442 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800443 synchronized (mPackagesLock) {
444 mUsersDir = new File(dataDir, USER_INFO_DIR);
445 mUsersDir.mkdirs();
446 // Make zeroth user directory, for services to migrate their files to that location
447 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
448 userZeroDir.mkdirs();
449 FileUtils.setPermissions(mUsersDir.toString(),
450 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
451 -1, -1);
452 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
453 initDefaultGuestRestrictions();
454 readUserListLP();
455 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700456 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700457 mLocalService = new LocalService();
458 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000459 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000460 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700461 }
462
463 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400464 mAppOpsService = IAppOpsService.Stub.asInterface(
465 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800466
467 synchronized (mRestrictionsLock) {
468 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400469 }
Samuel Tand9453b82016-03-14 15:57:02 -0700470
471 UserInfo currentGuestUser = findCurrentGuestUser();
472 if (currentGuestUser != null && !hasUserRestriction(
473 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
474 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
475 // to it, in case this guest was created in a previous version where this
476 // user restriction was not a default guest restriction.
477 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
478 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700479
Ricky Waib1dd80b2016-06-07 18:00:55 +0100480 mContext.registerReceiver(mDisableQuietModeCallback,
481 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
482 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700483 }
484
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700485 void cleanupPartialUsers() {
486 // Prune out any partially created, partially removed and ephemeral users.
487 ArrayList<UserInfo> partials = new ArrayList<>();
488 synchronized (mUsersLock) {
489 final int userSize = mUsers.size();
490 for (int i = 0; i < userSize; i++) {
491 UserInfo ui = mUsers.valueAt(i).info;
492 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
493 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700494 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700495 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700496 }
497 }
498 }
499 final int partialsSize = partials.size();
500 for (int i = 0; i < partialsSize; i++) {
501 UserInfo ui = partials.get(i);
502 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
503 + " (name=" + ui.name + ")");
504 removeUserState(ui.id);
505 }
506 }
507
Amith Yamasani258848d2012-08-10 17:06:33 -0700508 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800509 public String getUserAccount(int userId) {
510 checkManageUserAndAcrossUsersFullPermission("get user account");
511 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800512 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800513 }
514 }
515
516 @Override
517 public void setUserAccount(int userId, String accountName) {
518 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800519 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800520 synchronized (mPackagesLock) {
521 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800522 final UserData userData = mUsers.get(userId);
523 if (userData == null) {
524 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
525 return;
526 }
527 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800528 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800529 userData.account = accountName;
530 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800531 }
532 }
533
534 if (userToUpdate != null) {
535 writeUserLP(userToUpdate);
536 }
537 }
538 }
539
540 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700541 public UserInfo getPrimaryUser() {
542 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700543 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700544 final int userSize = mUsers.size();
545 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800546 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800547 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700548 return ui;
549 }
550 }
551 }
552 return null;
553 }
554
555 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700556 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700557 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700558 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700559 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700560 final int userSize = mUsers.size();
561 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800562 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700563 if (ui.partial) {
564 continue;
565 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800566 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700567 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700568 }
Amith Yamasani13593602012-03-22 16:16:17 -0700569 }
570 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700571 }
Amith Yamasani13593602012-03-22 16:16:17 -0700572 }
573
Amith Yamasani258848d2012-08-10 17:06:33 -0700574 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100575 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700576 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800577 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700578 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700579 } else {
580 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800581 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700582 final long ident = Binder.clearCallingIdentity();
583 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700584 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700585 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100586 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 } finally {
588 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000589 }
590 }
591
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700592 @Override
593 public int[] getProfileIds(int userId, boolean enabledOnly) {
594 if (userId != UserHandle.getCallingUserId()) {
595 checkManageUsersPermission("getting profiles related to user " + userId);
596 }
597 final long ident = Binder.clearCallingIdentity();
598 try {
599 synchronized (mUsersLock) {
600 return getProfileIdsLU(userId, enabledOnly).toArray();
601 }
602 } finally {
603 Binder.restoreCallingIdentity(ident);
604 }
605 }
606
Amith Yamasanibe465322014-04-24 13:45:17 -0700607 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700608 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700609 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
610 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
611 for (int i = 0; i < profileIds.size(); i++) {
612 int profileId = profileIds.get(i);
613 UserInfo userInfo = mUsers.get(profileId).info;
614 // If full info is not required - clear PII data to prevent 3P apps from reading it
615 if (!fullInfo) {
616 userInfo = new UserInfo(userInfo);
617 userInfo.name = null;
618 userInfo.iconPath = null;
619 } else {
620 userInfo = userWithName(userInfo);
621 }
622 users.add(userInfo);
623 }
624 return users;
625 }
626
627 /**
628 * Assume permissions already checked and caller's identity cleared
629 */
630 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700631 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700632 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700633 if (user == null) {
634 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700635 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700636 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700637 final int userSize = mUsers.size();
638 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800639 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700640 if (!isProfileOf(user, profile)) {
641 continue;
642 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100643 if (enabledOnly && !profile.isEnabled()) {
644 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700645 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700646 if (mRemovingUserIds.get(profile.id)) {
647 continue;
648 }
Tony Mak80189cd2016-04-05 17:21:42 +0100649 if (profile.partial) {
650 continue;
651 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700652 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700653 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700654 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700655 }
656
Jessica Hummelbe81c802014-04-22 15:49:22 +0100657 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700658 public int getCredentialOwnerProfile(int userHandle) {
659 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000660 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700661 synchronized (mUsersLock) {
662 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700663 if (profileParent != null) {
664 return profileParent.id;
665 }
666 }
667 }
668
669 return userHandle;
670 }
671
672 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700673 public boolean isSameProfileGroup(int userId, int otherUserId) {
674 if (userId == otherUserId) return true;
675 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700676 synchronized (mUsersLock) {
677 UserInfo userInfo = getUserInfoLU(userId);
678 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
679 return false;
680 }
681 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
682 if (otherUserInfo == null
683 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
684 return false;
685 }
686 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700687 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700688 }
689
690 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100691 public UserInfo getProfileParent(int userHandle) {
692 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700693 synchronized (mUsersLock) {
694 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700695 }
696 }
697
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 private UserInfo getProfileParentLU(int userHandle) {
699 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700700 if (profile == null) {
701 return null;
702 }
703 int parentUserId = profile.profileGroupId;
704 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
705 return null;
706 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700707 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100708 }
709 }
710
Fyodor Kupolov82402752015-10-28 14:54:51 -0700711 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100712 return user.id == profile.id ||
713 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
714 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000715 }
716
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000717 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000718 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100719 Intent intent = new Intent();
720 if (inQuietMode) {
721 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
722 } else {
723 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
724 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000725 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
726 intent.putExtra(Intent.EXTRA_USER, profileHandle);
727 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000728 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000729 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000730 }
731
732 @Override
733 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
734 checkManageUsersPermission("silence profile");
735 boolean changed = false;
736 UserInfo profile, parent;
737 synchronized (mPackagesLock) {
738 synchronized (mUsersLock) {
739 profile = getUserInfoLU(userHandle);
740 parent = getProfileParentLU(userHandle);
741
742 }
743 if (profile == null || !profile.isManagedProfile()) {
744 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
745 }
746 if (profile.isQuietModeEnabled() != enableQuietMode) {
747 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800748 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000749 changed = true;
750 }
751 }
752 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000753 long identity = Binder.clearCallingIdentity();
754 try {
755 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100756 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100757 LocalServices.getService(ActivityManagerInternal.class)
758 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000759 } else {
760 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
761 }
762 } catch (RemoteException e) {
763 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
764 } finally {
765 Binder.restoreCallingIdentity(identity);
766 }
767
768 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
769 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000770 }
771 }
772
773 @Override
774 public boolean isQuietModeEnabled(int userHandle) {
775 synchronized (mPackagesLock) {
776 UserInfo info;
777 synchronized (mUsersLock) {
778 info = getUserInfoLU(userHandle);
779 }
780 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000781 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000782 }
783 return info.isQuietModeEnabled();
784 }
785 }
786
Kenny Guya52dc3e2014-02-11 15:33:14 +0000787 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100788 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100789 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600790 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100791 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100792 // if the user is already unlocked, no need to show a profile challenge
793 setQuietModeEnabled(userHandle, false);
794 return true;
795 }
796
797 long identity = Binder.clearCallingIdentity();
798 try {
799 // otherwise, we show a profile challenge to trigger decryption of the user
800 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
801 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100802 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
803 // lock, confirm screenlock page will know and show personal challenge, and unlock
804 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100805 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
806 userHandle);
807 if (unlockIntent == null) {
808 return false;
809 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100810 final Intent callBackIntent = new Intent(
811 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100812 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100813 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100814 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100815 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
816 callBackIntent.setPackage(mContext.getPackageName());
817 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
818 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
819 mContext,
820 0,
821 callBackIntent,
822 PendingIntent.FLAG_CANCEL_CURRENT |
823 PendingIntent.FLAG_ONE_SHOT |
824 PendingIntent.FLAG_IMMUTABLE);
825 // After unlocking the challenge, it will disable quiet mode and run the original
826 // intentSender
827 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100828 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
829 mContext.startActivity(unlockIntent);
830 } finally {
831 Binder.restoreCallingIdentity(identity);
832 }
833 return false;
834 }
835
836 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100837 public void setUserEnabled(int userId) {
838 checkManageUsersPermission("enable user");
839 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700840 UserInfo info;
841 synchronized (mUsersLock) {
842 info = getUserInfoLU(userId);
843 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100844 if (info != null && !info.isEnabled()) {
845 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800846 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100847 }
848 }
849 }
850
851 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700852 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700853 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000854 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700855 return userWithName(getUserInfoLU(userId));
856 }
857 }
858
859 /**
860 * Returns a UserInfo object with the name filled in, for Owner, or the original
861 * if the name is already set.
862 */
863 private UserInfo userWithName(UserInfo orig) {
864 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
865 UserInfo withName = new UserInfo(orig);
866 withName.name = getOwnerName();
867 return withName;
868 } else {
869 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000870 }
871 }
872
873 @Override
874 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000875 int callingUserId = UserHandle.getCallingUserId();
876 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700877 if (!isSameProfileGroup(callingUserId, userId)) {
878 throw new SecurityException(
879 "You need MANAGE_USERS permission to: check if specified user a " +
880 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000881 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000882 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700883 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700884 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000885 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700886 }
887 }
888
Amith Yamasani71e6c692013-03-24 17:39:28 -0700889 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700890 public boolean isUserUnlockingOrUnlocked(int userId) {
891 int callingUserId = UserHandle.getCallingUserId();
892 if (callingUserId != userId && !hasManageUsersPermission()) {
893 if (!isSameProfileGroup(callingUserId, userId)) {
894 throw new SecurityException(
895 "You need MANAGE_USERS permission to: check isUserUnlockingOrUnlocked");
896 }
897 }
898 return mLocalService.isUserUnlockingOrUnlocked(userId);
899 }
900
901 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700902 public boolean isDemoUser(int userId) {
903 int callingUserId = UserHandle.getCallingUserId();
904 if (callingUserId != userId && !hasManageUsersPermission()) {
905 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
906 + " is a demo user");
907 }
908 synchronized (mUsersLock) {
909 UserInfo userInfo = getUserInfoLU(userId);
910 return userInfo != null && userInfo.isDemo();
911 }
912 }
913
914 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700915 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700916 synchronized (mUsersLock) {
917 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700918 }
919 }
920
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700921 @Override
922 public boolean canHaveRestrictedProfile(int userId) {
923 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700924 synchronized (mUsersLock) {
925 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700926 if (userInfo == null || !userInfo.canHaveProfile()) {
927 return false;
928 }
929 if (!userInfo.isAdmin()) {
930 return false;
931 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800932 // restricted profile can be created if there is no DO set and the admin user has no PO;
933 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700934 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700935 }
936
Amith Yamasani195263742012-08-21 15:40:12 -0700937 /*
938 * Should be locked on mUsers before calling this.
939 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700940 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800941 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700942 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800943 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700944 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
945 return null;
946 }
Amith Yamasani12747872015-12-07 14:19:49 -0800947 return userData != null ? userData.info : null;
948 }
949
950 private UserData getUserDataLU(int userId) {
951 final UserData userData = mUsers.get(userId);
952 // If it is partial and not in the process of being removed, return as unknown user.
953 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
954 return null;
955 }
956 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700957 }
958
Fyodor Kupolov82402752015-10-28 14:54:51 -0700959 /**
960 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
961 * <p>No permissions checking or any addition checks are made</p>
962 */
963 private UserInfo getUserInfoNoChecks(int userId) {
964 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800965 final UserData userData = mUsers.get(userId);
966 return userData != null ? userData.info : null;
967 }
968 }
969
970 /**
971 * Obtains {@link #mUsersLock} and return UserData from mUsers.
972 * <p>No permissions checking or any addition checks are made</p>
973 */
974 private UserData getUserDataNoChecks(int userId) {
975 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700976 return mUsers.get(userId);
977 }
978 }
979
Amith Yamasani236b2b52015-08-18 14:32:14 -0700980 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700981 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700982 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700983 }
984
Amith Yamasani258848d2012-08-10 17:06:33 -0700985 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700986 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700987 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700988 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700989 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800990 UserData userData = getUserDataNoChecks(userId);
991 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700992 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
993 return;
994 }
Amith Yamasani12747872015-12-07 14:19:49 -0800995 if (name != null && !name.equals(userData.info.name)) {
996 userData.info.name = name;
997 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700998 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700999 }
1000 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001001 if (changed) {
1002 sendUserInfoChangedBroadcast(userId);
1003 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001004 }
1005
Amith Yamasani258848d2012-08-10 17:06:33 -07001006 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001007 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001008 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001009 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1010 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1011 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001012 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001013 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001014 }
1015
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001016
1017
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001018 private void sendUserInfoChangedBroadcast(int userId) {
1019 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1020 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1021 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001022 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001023 }
1024
Amith Yamasani258848d2012-08-10 17:06:33 -07001025 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001026 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001027 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001028 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001029 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1030 if (targetUserInfo == null || targetUserInfo.partial) {
1031 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001032 return null;
1033 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001034
1035 final int callingUserId = UserHandle.getCallingUserId();
1036 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1037 final int targetGroupId = targetUserInfo.profileGroupId;
1038 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1039 && callingGroupId == targetGroupId);
1040 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001041 checkManageUsersPermission("get the icon of a user who is not related");
1042 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001043
1044 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001045 return null;
1046 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001047 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001048 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001049
1050 try {
1051 return ParcelFileDescriptor.open(
1052 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1053 } catch (FileNotFoundException e) {
1054 Log.e(LOG_TAG, "Couldn't find icon file", e);
1055 }
1056 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001057 }
1058
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001059 public void makeInitialized(int userId) {
1060 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001061 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001062 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001063 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001064 userData = mUsers.get(userId);
1065 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001066 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001067 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001068 }
Amith Yamasani12747872015-12-07 14:19:49 -08001069 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1070 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001071 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001072 }
1073 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001074 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001075 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001076 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001077 }
1078
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001079 /**
1080 * If default guest restrictions haven't been initialized yet, add the basic
1081 * restrictions.
1082 */
1083 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001084 synchronized (mGuestRestrictions) {
1085 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001086 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001087 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001088 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1089 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1090 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001091 }
1092 }
1093
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001094 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301095 public Bundle getDefaultGuestRestrictions() {
1096 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001097 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301098 return new Bundle(mGuestRestrictions);
1099 }
1100 }
1101
1102 @Override
1103 public void setDefaultGuestRestrictions(Bundle restrictions) {
1104 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001105 synchronized (mGuestRestrictions) {
1106 mGuestRestrictions.clear();
1107 mGuestRestrictions.putAll(restrictions);
1108 }
1109 synchronized (mPackagesLock) {
1110 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301111 }
1112 }
1113
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001114 /**
1115 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1116 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001117 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001118 @Nullable Bundle global) {
1119 Preconditions.checkNotNull(local);
1120 boolean globalChanged = false;
1121 boolean localChanged;
1122 synchronized (mRestrictionsLock) {
1123 if (global != null) {
1124 // Update global.
1125 globalChanged = !UserRestrictionsUtils.areEqual(
1126 mDevicePolicyGlobalUserRestrictions, global);
1127 if (globalChanged) {
1128 mDevicePolicyGlobalUserRestrictions = global;
1129 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001130 // Remember the global restriction owner userId to be able to make a distinction
1131 // in getUserRestrictionSource on who set local policies.
1132 mGlobalRestrictionOwnerUserId = userId;
1133 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001134 if (mGlobalRestrictionOwnerUserId == userId) {
1135 // When profile owner sets restrictions it passes null global bundle and we
1136 // reset global restriction owner userId.
1137 // This means this user used to have DO, but now the DO is gone and the user
1138 // instead has PO.
1139 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1140 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001141 }
1142 {
1143 // Update local.
1144 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1145 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1146 if (localChanged) {
1147 mDevicePolicyLocalUserRestrictions.put(userId, local);
1148 }
1149 }
1150 }
1151 if (DBG) {
1152 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1153 + " global=" + global + (globalChanged ? " (changed)" : "")
1154 + " local=" + local + (localChanged ? " (changed)" : "")
1155 );
1156 }
1157 // Don't call them within the mRestrictionsLock.
1158 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001159 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001160 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001161 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001162 if (globalChanged) {
1163 writeUserListLP();
1164 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001165 }
1166
1167 synchronized (mRestrictionsLock) {
1168 if (globalChanged) {
1169 applyUserRestrictionsForAllUsersLR();
1170 } else if (localChanged) {
1171 applyUserRestrictionsLR(userId);
1172 }
1173 }
1174 }
1175
Makoto Onuki068c54a2015-10-13 14:34:03 -07001176 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001177 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001178 final Bundle baseRestrictions =
1179 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1180 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1181 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001182
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001183 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1184 // Common case first.
1185 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001186 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001187 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1188 UserRestrictionsUtils.merge(effective, global);
1189 UserRestrictionsUtils.merge(effective, local);
1190
Makoto Onuki068c54a2015-10-13 14:34:03 -07001191 return effective;
1192 }
1193
1194 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001195 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001196 if (DBG) {
1197 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1198 }
1199 mCachedEffectiveUserRestrictions.remove(userId);
1200 }
1201
1202 private Bundle getEffectiveUserRestrictions(int userId) {
1203 synchronized (mRestrictionsLock) {
1204 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1205 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001206 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001207 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1208 }
1209 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001210 }
1211 }
1212
Makoto Onuki068c54a2015-10-13 14:34:03 -07001213 /** @return a specific user restriction that's in effect currently. */
1214 @Override
1215 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001216 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1217 return false;
1218 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001219 Bundle restrictions = getEffectiveUserRestrictions(userId);
1220 return restrictions != null && restrictions.getBoolean(restrictionKey);
1221 }
1222
1223 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001224 * @hide
1225 *
1226 * Returns who set a user restriction on a user.
1227 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1228 * @param restrictionKey the string key representing the restriction
1229 * @param userId the id of the user for whom to retrieve the restrictions.
1230 * @return The source of user restriction. Any combination of
1231 * {@link UserManager#RESTRICTION_NOT_SET},
1232 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1233 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1234 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1235 */
1236 @Override
1237 public int getUserRestrictionSource(String restrictionKey, int userId) {
1238 checkManageUsersPermission("getUserRestrictionSource");
1239 int result = UserManager.RESTRICTION_NOT_SET;
1240
1241 // Shortcut for the most common case
1242 if (!hasUserRestriction(restrictionKey, userId)) {
1243 return result;
1244 }
1245
1246 if (hasBaseUserRestriction(restrictionKey, userId)) {
1247 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1248 }
1249
1250 synchronized(mRestrictionsLock) {
1251 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1252 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1253 && localRestrictions.getBoolean(restrictionKey)) {
1254 // Local restrictions may have been set by device owner the userId of which is
1255 // stored in mGlobalRestrictionOwnerUserId.
1256 if (mGlobalRestrictionOwnerUserId == userId) {
1257 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1258 } else {
1259 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1260 }
1261 }
1262 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1263 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1264 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1265 }
1266 }
1267
1268 return result;
1269 }
1270
1271 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001272 * @return UserRestrictions that are in effect currently. This always returns a new
1273 * {@link Bundle}.
1274 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001275 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001276 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001277 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001278 }
1279
1280 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001281 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1282 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001283 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1284 return false;
1285 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001286 synchronized (mRestrictionsLock) {
1287 Bundle bundle = mBaseUserRestrictions.get(userId);
1288 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1289 }
1290 }
1291
1292 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001293 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001294 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001295 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1296 return;
1297 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001298 synchronized (mRestrictionsLock) {
1299 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1300 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001301 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1302 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001303 newRestrictions.putBoolean(key, value);
1304
Fyodor Kupolov82402752015-10-28 14:54:51 -07001305 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001306 }
1307 }
1308
Makoto Onuki068c54a2015-10-13 14:34:03 -07001309 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001310 * Optionally updating user restrictions, calculate the effective user restrictions and also
1311 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001312 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001313 * @param newRestrictions User restrictions to set.
1314 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001315 * @param userId target user ID.
1316 */
1317 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001318 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001319 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001320
1321 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1322 mAppliedUserRestrictions.get(userId));
1323
1324 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001325 if (newRestrictions != null) {
1326 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001327 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1328
1329 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001330 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1331 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001332
1333 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1334 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001335 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001336 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001337 }
1338
Fyodor Kupolov82402752015-10-28 14:54:51 -07001339 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001340
Makoto Onuki759a7632015-10-28 16:43:10 -07001341 mCachedEffectiveUserRestrictions.put(userId, effective);
1342
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001343 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001344 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001345 debug("Applying user restrictions: userId=" + userId
1346 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001347 }
1348
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001349 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001350 mHandler.post(new Runnable() {
1351 @Override
1352 public void run() {
1353 try {
1354 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1355 } catch (RemoteException e) {
1356 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1357 }
1358 }
1359 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001360 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001361
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001362 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001363
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001364 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001365 }
1366
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001367 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001368 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001369 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1370 // actually, but we still need some kind of synchronization otherwise we might end up
1371 // calling listeners out-of-order, thus "LR".
1372
1373 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1374 return;
1375 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001376
1377 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1378 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1379
1380 mHandler.post(new Runnable() {
1381 @Override
1382 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001383 UserRestrictionsUtils.applyUserRestrictions(
1384 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001385
Makoto Onukid45a4a22015-11-02 17:17:38 -08001386 final UserRestrictionsListener[] listeners;
1387 synchronized (mUserRestrictionsListeners) {
1388 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1389 mUserRestrictionsListeners.toArray(listeners);
1390 }
1391 for (int i = 0; i < listeners.length; i++) {
1392 listeners[i].onUserRestrictionsChanged(userId,
1393 newRestrictionsFinal, prevRestrictionsFinal);
1394 }
1395 }
1396 });
1397 }
1398
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001399 // Package private for the inner class.
1400 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001401 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001402 }
1403
1404 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001405 // Package private for the inner class.
1406 void applyUserRestrictionsForAllUsersLR() {
1407 if (DBG) {
1408 debug("applyUserRestrictionsForAllUsersLR");
1409 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001410 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001411 mCachedEffectiveUserRestrictions.clear();
1412
Makoto Onuki068c54a2015-10-13 14:34:03 -07001413 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1414 // it on a handler.
1415 final Runnable r = new Runnable() {
1416 @Override
1417 public void run() {
1418 // Then get the list of running users.
1419 final int[] runningUsers;
1420 try {
1421 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1422 } catch (RemoteException e) {
1423 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1424 return;
1425 }
1426 // Then re-calculate the effective restrictions and apply, only for running users.
1427 // It's okay if a new user has started after the getRunningUserIds() call,
1428 // because we'll do the same thing (re-calculate the restrictions and apply)
1429 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001430 synchronized (mRestrictionsLock) {
1431 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001432 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001433 }
1434 }
1435 }
1436 };
1437 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001438 }
1439
Amith Yamasani258848d2012-08-10 17:06:33 -07001440 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001441 * Check if we've hit the limit of how many users can be created.
1442 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001443 private boolean isUserLimitReached() {
1444 int count;
1445 synchronized (mUsersLock) {
1446 count = getAliveUsersExcludingGuestsCountLU();
1447 }
1448 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001449 }
1450
1451 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001452 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001453 checkManageUsersPermission("check if more managed profiles can be added.");
1454 if (ActivityManager.isLowRamDeviceStatic()) {
1455 return false;
1456 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001457 if (!mContext.getPackageManager().hasSystemFeature(
1458 PackageManager.FEATURE_MANAGED_USERS)) {
1459 return false;
1460 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001461 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001462 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1463 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1464 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001465 return false;
1466 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001467 synchronized(mUsersLock) {
1468 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001469 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001470 return false;
1471 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001472 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1473 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001474 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001475 return usersCountAfterRemoving == 1
1476 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001477 }
1478 }
1479
Fyodor Kupolov82402752015-10-28 14:54:51 -07001480 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001481 int aliveUserCount = 0;
1482 final int totalUserCount = mUsers.size();
1483 // Skip over users being removed
1484 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001485 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001486 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001487 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001488 aliveUserCount++;
1489 }
1490 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001491 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001492 }
1493
1494 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001495 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001496 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1497 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1498 * permissions can make certain calls to the UserManager.
1499 *
1500 * @param message used as message if SecurityException is thrown
1501 * @throws SecurityException if the caller does not have enough privilege.
1502 */
1503 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1504 final int uid = Binder.getCallingUid();
1505 if (uid != Process.SYSTEM_UID && uid != 0
1506 && ActivityManager.checkComponentPermission(
1507 Manifest.permission.MANAGE_USERS,
1508 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1509 && ActivityManager.checkComponentPermission(
1510 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1511 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1512 throw new SecurityException(
1513 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1514 + message);
1515 }
1516 }
1517
1518 /**
1519 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001520 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001521 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001522 *
1523 * @param message used as message if SecurityException is thrown
1524 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001525 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001526 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001527 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001528 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001529 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1530 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001531 }
1532
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001533 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001534 * Enforces that only the system UID or root's UID or apps that have the
1535 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1536 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1537 * can make certain calls to the UserManager.
1538 *
1539 * @param message used as message if SecurityException is thrown
1540 * @throws SecurityException if the caller is not system or root
1541 * @see #hasManageOrCreateUsersPermission()
1542 */
1543 private static final void checkManageOrCreateUsersPermission(String message) {
1544 if (!hasManageOrCreateUsersPermission()) {
1545 throw new SecurityException(
1546 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1547 }
1548 }
1549
1550 /**
1551 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1552 * to create user/profiles other than what is allowed for
1553 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1554 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1555 */
1556 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1557 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1558 if (!hasManageOrCreateUsersPermission()) {
1559 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1560 + "permission to create an user with flags: " + creationFlags);
1561 }
1562 } else if (!hasManageUsersPermission()) {
1563 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1564 + " with flags: " + creationFlags);
1565 }
1566 }
1567
1568 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001569 * @return whether the calling UID is system UID or root's UID or the calling app has the
1570 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1571 */
1572 private static final boolean hasManageUsersPermission() {
1573 final int callingUid = Binder.getCallingUid();
1574 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1575 || callingUid == Process.ROOT_UID
1576 || ActivityManager.checkComponentPermission(
1577 android.Manifest.permission.MANAGE_USERS,
1578 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1579 }
1580
1581 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001582 * @return whether the calling UID is system UID or root's UID or the calling app has the
1583 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1584 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1585 */
1586 private static final boolean hasManageOrCreateUsersPermission() {
1587 final int callingUid = Binder.getCallingUid();
1588 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1589 || callingUid == Process.ROOT_UID
1590 || ActivityManager.checkComponentPermission(
1591 android.Manifest.permission.MANAGE_USERS,
1592 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1593 || ActivityManager.checkComponentPermission(
1594 android.Manifest.permission.CREATE_USERS,
1595 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1596 }
1597
1598 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001599 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1600 * UserManager.
1601 *
1602 * @param message used as message if SecurityException is thrown
1603 * @throws SecurityException if the caller is not system or root
1604 */
1605 private static void checkSystemOrRoot(String message) {
1606 final int uid = Binder.getCallingUid();
1607 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1608 throw new SecurityException("Only system may: " + message);
1609 }
1610 }
1611
Fyodor Kupolov82402752015-10-28 14:54:51 -07001612 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001613 try {
1614 File dir = new File(mUsersDir, Integer.toString(info.id));
1615 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001616 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001617 if (!dir.exists()) {
1618 dir.mkdir();
1619 FileUtils.setPermissions(
1620 dir.getPath(),
1621 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1622 -1, -1);
1623 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001624 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001625 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001626 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001627 info.iconPath = file.getAbsolutePath();
1628 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001629 try {
1630 os.close();
1631 } catch (IOException ioe) {
1632 // What the ... !
1633 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001634 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001635 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001636 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001637 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001638 }
1639
Amith Yamasani0b285492011-04-14 17:35:23 -07001640 /**
1641 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1642 * cache it elsewhere.
1643 * @return the array of user ids.
1644 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001645 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001646 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001647 return mUserIds;
1648 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001649 }
1650
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001651 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001652 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001653 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001654 return;
1655 }
1656 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001657 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001658 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001659 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001660 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001661 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662 int type;
1663 while ((type = parser.next()) != XmlPullParser.START_TAG
1664 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001665 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001666 }
1667
1668 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001669 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001670 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001671 return;
1672 }
1673
Amith Yamasani2a003292012-08-14 18:25:45 -07001674 mNextSerialNumber = -1;
1675 if (parser.getName().equals(TAG_USERS)) {
1676 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1677 if (lastSerialNumber != null) {
1678 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1679 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001680 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1681 if (versionNumber != null) {
1682 mUserVersion = Integer.parseInt(versionNumber);
1683 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001684 }
1685
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1687
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001688 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301689 if (type == XmlPullParser.START_TAG) {
1690 final String name = parser.getName();
1691 if (name.equals(TAG_USER)) {
1692 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001693
Amith Yamasani12747872015-12-07 14:19:49 -08001694 UserData userData = readUserLP(Integer.parseInt(id));
1695
1696 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001697 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001698 mUsers.put(userData.info.id, userData);
1699 if (mNextSerialNumber < 0
1700 || mNextSerialNumber <= userData.info.id) {
1701 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001702 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301703 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001704 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301705 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001706 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1707 && type != XmlPullParser.END_TAG) {
1708 if (type == XmlPullParser.START_TAG) {
1709 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001710 synchronized (mGuestRestrictions) {
1711 UserRestrictionsUtils
1712 .readRestrictions(parser, mGuestRestrictions);
1713 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001714 }
1715 break;
1716 }
1717 }
Makoto Onuki82de3002016-09-30 09:58:15 -07001718 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1719 UserRestrictionsUtils.readRestrictions(parser,
1720 newDevicePolicyGlobalUserRestrictions);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001721 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1722 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1723 if (ownerUserId != null) {
1724 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1725 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001726 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001727 }
1728 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001729 synchronized (mRestrictionsLock) {
1730 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1731 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001732 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001733 upgradeIfNecessaryLP();
1734 } catch (IOException | XmlPullParserException e) {
1735 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001736 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001737 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001738 }
1739 }
1740
Amith Yamasani6f34b412012-10-22 18:19:27 -07001741 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001742 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001743 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001744 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001745 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001746 int userVersion = mUserVersion;
1747 if (userVersion < 1) {
1748 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001749 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1750 if ("Primary".equals(userData.info.name)) {
1751 userData.info.name =
1752 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1753 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001754 }
1755 userVersion = 1;
1756 }
1757
Amith Yamasanibc9625052012-11-15 14:39:18 -08001758 if (userVersion < 2) {
1759 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001760 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1761 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1762 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1763 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001764 }
1765 userVersion = 2;
1766 }
1767
Amith Yamasani350962c2013-08-06 11:18:53 -07001768
Amith Yamasani5e486f52013-08-07 11:06:44 -07001769 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001770 userVersion = 4;
1771 }
1772
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001773 if (userVersion < 5) {
1774 initDefaultGuestRestrictions();
1775 userVersion = 5;
1776 }
1777
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001778 if (userVersion < 6) {
1779 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001780 synchronized (mUsersLock) {
1781 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001782 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001783 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001784 if (!splitSystemUser && userData.info.isRestricted()
1785 && (userData.info.restrictedProfileParentId
1786 == UserInfo.NO_PROFILE_GROUP_ID)) {
1787 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1788 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001789 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001790 }
1791 }
1792 userVersion = 6;
1793 }
1794
Amith Yamasani6f34b412012-10-22 18:19:27 -07001795 if (userVersion < USER_VERSION) {
1796 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1797 + USER_VERSION);
1798 } else {
1799 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001800
1801 if (originalVersion < mUserVersion) {
1802 writeUserListLP();
1803 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001804 }
1805 }
1806
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001807 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001808 int flags = UserInfo.FLAG_INITIALIZED;
1809 // In split system user mode, the admin and primary flags are assigned to the first human
1810 // user.
1811 if (!UserManager.isSplitSystemUser()) {
1812 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1813 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001814 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001815 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001816 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001817 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001818 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001819
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001820 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001821 try {
1822 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1823 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1824 for (String userRestriction : defaultFirstUserRestrictions) {
1825 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1826 restrictions.putBoolean(userRestriction, true);
1827 }
1828 }
1829 } catch (Resources.NotFoundException e) {
1830 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1831 }
1832
Makoto Onuki068c54a2015-10-13 14:34:03 -07001833 synchronized (mRestrictionsLock) {
1834 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1835 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001836
Fyodor Kupolov82402752015-10-28 14:54:51 -07001837 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001838 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001839
Amith Yamasani12747872015-12-07 14:19:49 -08001840 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001841 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001842 }
1843
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001844 private String getOwnerName() {
1845 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1846 }
1847
Amith Yamasani12747872015-12-07 14:19:49 -08001848 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001849 if (DBG) {
1850 debug("scheduleWriteUser");
1851 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001852 // No need to wrap it within a lock -- worst case, we'll just post the same message
1853 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001854 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1855 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001856 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1857 }
1858 }
1859
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001860 /*
1861 * Writes the user file in this format:
1862 *
1863 * <user flags="20039023" id="0">
1864 * <name>Primary</name>
1865 * </user>
1866 */
Amith Yamasani12747872015-12-07 14:19:49 -08001867 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001868 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001869 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001870 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001871 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001872 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001873 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001874 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001875 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1876
1877 // XmlSerializer serializer = XmlUtils.serializerInstance();
1878 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001879 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001880 serializer.startDocument(null, true);
1881 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1882
Amith Yamasani12747872015-12-07 14:19:49 -08001883 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001884 serializer.startTag(null, TAG_USER);
1885 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001886 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001887 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001888 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1889 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1890 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001891 if (userInfo.lastLoggedInFingerprint != null) {
1892 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1893 userInfo.lastLoggedInFingerprint);
1894 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001895 if (userInfo.iconPath != null) {
1896 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1897 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001898 if (userInfo.partial) {
1899 serializer.attribute(null, ATTR_PARTIAL, "true");
1900 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001901 if (userInfo.guestToRemove) {
1902 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1903 }
Kenny Guy2a764942014-04-02 13:29:20 +01001904 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1905 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1906 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001907 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001908 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1909 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1910 Integer.toString(userInfo.restrictedProfileParentId));
1911 }
Amith Yamasani12747872015-12-07 14:19:49 -08001912 // Write seed data
1913 if (userData.persistSeedData) {
1914 if (userData.seedAccountName != null) {
1915 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1916 }
1917 if (userData.seedAccountType != null) {
1918 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1919 }
1920 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001921 if (userInfo.name != null) {
1922 serializer.startTag(null, TAG_NAME);
1923 serializer.text(userInfo.name);
1924 serializer.endTag(null, TAG_NAME);
1925 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001926 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001927 UserRestrictionsUtils.writeRestrictions(serializer,
1928 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1929 UserRestrictionsUtils.writeRestrictions(serializer,
1930 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1931 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001932 }
Amith Yamasani12747872015-12-07 14:19:49 -08001933
1934 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001935 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001936 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001937 serializer.endTag(null, TAG_ACCOUNT);
1938 }
1939
Amith Yamasani12747872015-12-07 14:19:49 -08001940 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1941 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1942 userData.seedAccountOptions.saveToXml(serializer);
1943 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1944 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001945 serializer.endTag(null, TAG_USER);
1946
1947 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001948 userFile.finishWrite(fos);
1949 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001950 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001951 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001952 }
1953 }
1954
1955 /*
1956 * Writes the user list file in this format:
1957 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001958 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001959 * <user id="0"></user>
1960 * <user id="2"></user>
1961 * </users>
1962 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001963 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001964 if (DBG) {
1965 debug("writeUserList");
1966 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001967 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001968 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001969 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001970 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001971 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1972
1973 // XmlSerializer serializer = XmlUtils.serializerInstance();
1974 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001975 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001976 serializer.startDocument(null, true);
1977 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1978
1979 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001980 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001981 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001982
Adam Lesinskieddeb492014-09-08 17:50:03 -07001983 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001984 synchronized (mGuestRestrictions) {
1985 UserRestrictionsUtils
1986 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1987 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301988 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001989 synchronized (mRestrictionsLock) {
1990 UserRestrictionsUtils.writeRestrictions(serializer,
1991 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1992 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001993 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1994 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1995 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001996 int[] userIdsToWrite;
1997 synchronized (mUsersLock) {
1998 userIdsToWrite = new int[mUsers.size()];
1999 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002000 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002001 userIdsToWrite[i] = user.id;
2002 }
2003 }
2004 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002005 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002006 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002007 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002008 }
2009
2010 serializer.endTag(null, TAG_USERS);
2011
2012 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002013 userListFile.finishWrite(fos);
2014 } catch (Exception e) {
2015 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002016 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002017 }
2018 }
2019
Amith Yamasani12747872015-12-07 14:19:49 -08002020 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002021 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002022 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002023 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002024 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002025 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002026 long creationTime = 0L;
2027 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002028 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002029 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002030 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002031 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002032 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002033 boolean persistSeedData = false;
2034 String seedAccountName = null;
2035 String seedAccountType = null;
2036 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002037 Bundle baseRestrictions = new Bundle();
2038 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002039
2040 FileInputStream fis = null;
2041 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002042 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002043 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002044 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002045 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002046 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002047 int type;
2048 while ((type = parser.next()) != XmlPullParser.START_TAG
2049 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002050 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002051 }
2052
2053 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002054 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002055 return null;
2056 }
2057
2058 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002059 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2060 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002061 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002062 return null;
2063 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002064 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2065 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002066 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002067 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2068 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002069 lastLoggedInFingerprint = parser.getAttributeValue(null,
2070 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002071 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2072 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002073 restrictedProfileParentId = readIntAttribute(parser,
2074 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002075 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2076 if ("true".equals(valueString)) {
2077 partial = true;
2078 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002079 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2080 if ("true".equals(valueString)) {
2081 guestToRemove = true;
2082 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002083
Amith Yamasani12747872015-12-07 14:19:49 -08002084 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2085 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2086 if (seedAccountName != null || seedAccountType != null) {
2087 persistSeedData = true;
2088 }
2089
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002090 int outerDepth = parser.getDepth();
2091 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2092 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2093 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2094 continue;
2095 }
2096 String tag = parser.getName();
2097 if (TAG_NAME.equals(tag)) {
2098 type = parser.next();
2099 if (type == XmlPullParser.TEXT) {
2100 name = parser.getText();
2101 }
2102 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002103 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2104 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2105 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002106 } else if (TAG_ACCOUNT.equals(tag)) {
2107 type = parser.next();
2108 if (type == XmlPullParser.TEXT) {
2109 account = parser.getText();
2110 }
Amith Yamasani12747872015-12-07 14:19:49 -08002111 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2112 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2113 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002114 }
2115 }
2116 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002117
Amith Yamasani12747872015-12-07 14:19:49 -08002118 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002119 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002120 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002121 userInfo.creationTime = creationTime;
2122 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002123 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002124 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002125 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002126 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002127 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002128
2129 // Create the UserData object that's internal to this class
2130 UserData userData = new UserData();
2131 userData.info = userInfo;
2132 userData.account = account;
2133 userData.seedAccountName = seedAccountName;
2134 userData.seedAccountType = seedAccountType;
2135 userData.persistSeedData = persistSeedData;
2136 userData.seedAccountOptions = seedAccountOptions;
2137
Makoto Onuki068c54a2015-10-13 14:34:03 -07002138 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002139 mBaseUserRestrictions.put(id, baseRestrictions);
2140 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002141 }
Amith Yamasani12747872015-12-07 14:19:49 -08002142 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002143 } catch (IOException ioe) {
2144 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002145 } finally {
2146 if (fis != null) {
2147 try {
2148 fis.close();
2149 } catch (IOException e) {
2150 }
2151 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002152 }
2153 return null;
2154 }
2155
Amith Yamasani920ace02012-09-20 22:15:37 -07002156 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2157 String valueString = parser.getAttributeValue(null, attr);
2158 if (valueString == null) return defaultValue;
2159 try {
2160 return Integer.parseInt(valueString);
2161 } catch (NumberFormatException nfe) {
2162 return defaultValue;
2163 }
2164 }
2165
2166 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2167 String valueString = parser.getAttributeValue(null, attr);
2168 if (valueString == null) return defaultValue;
2169 try {
2170 return Long.parseLong(valueString);
2171 } catch (NumberFormatException nfe) {
2172 return defaultValue;
2173 }
2174 }
2175
Amith Yamasanib82add22013-07-09 11:24:44 -07002176 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002177 * Removes the app restrictions file for a specific package and user id, if it exists.
2178 */
2179 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2180 synchronized (mPackagesLock) {
2181 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002182 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002183 if (resFile.exists()) {
2184 resFile.delete();
2185 }
2186 }
2187 }
2188
Kenny Guya52dc3e2014-02-11 15:33:14 +00002189 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002190 public UserInfo createProfileForUser(String name, int flags, int userId,
2191 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002192 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002193 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002194 }
2195
Amith Yamasani258848d2012-08-10 17:06:33 -07002196 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002197 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2198 String[] disallowedPackages) {
2199 checkManageOrCreateUsersPermission(flags);
2200 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2201 }
2202
2203 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002204 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002205 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002206 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002207 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002208
Jessica Hummelbe81c802014-04-22 15:49:22 +01002209 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002210 return createUserInternal(name, flags, parentId, null);
2211 }
2212
2213 private UserInfo createUserInternal(String name, int flags, int parentId,
2214 String[] disallowedPackages) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002215 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002216 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2217 return null;
2218 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002219 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2220 }
2221
2222 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2223 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002224 DeviceStorageMonitorInternal dsm = LocalServices
2225 .getService(DeviceStorageMonitorInternal.class);
2226 if (dsm.isMemoryLow()) {
2227 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2228 return null;
2229 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002230 if (ActivityManager.isLowRamDeviceStatic()) {
2231 return null;
2232 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002233 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002234 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002235 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002236 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002237 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002238 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002239 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002240 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002241 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002242 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002243 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002244 if (parentId != UserHandle.USER_NULL) {
2245 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002246 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002247 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002248 if (parent == null) return null;
2249 }
2250 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2251 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2252 return null;
2253 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002254 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2255 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002256 // been reached, cannot add a user.
2257 return null;
2258 }
2259 // If we're adding a guest and there already exists one, bail.
2260 if (isGuest && findCurrentGuestUser() != null) {
2261 return null;
2262 }
2263 // In legacy mode, restricted profile's parent can only be the owner user
2264 if (isRestricted && !UserManager.isSplitSystemUser()
2265 && (parentId != UserHandle.USER_SYSTEM)) {
2266 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2267 return null;
2268 }
2269 if (isRestricted && UserManager.isSplitSystemUser()) {
2270 if (parent == null) {
2271 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2272 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002273 return null;
2274 }
Amith Yamasani12747872015-12-07 14:19:49 -08002275 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002276 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2277 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002278 return null;
2279 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002280 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002281 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2282 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002283 Log.e(LOG_TAG,
2284 "Ephemeral users are supported on split-system-user systems only.");
2285 return null;
2286 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002287 // In split system user mode, we assign the first human user the primary flag.
2288 // And if there is no device owner, we also assign the admin flag to primary user.
2289 if (UserManager.isSplitSystemUser()
2290 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2291 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002292 synchronized (mUsersLock) {
2293 if (!mIsDeviceManaged) {
2294 flags |= UserInfo.FLAG_ADMIN;
2295 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002296 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002297 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002298
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002299 userId = getNextAvailableId();
2300 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002301 boolean ephemeralGuests = Resources.getSystem()
2302 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002303
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002304 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002305 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2306 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2307 || (parent != null && parent.info.isEphemeral())) {
2308 flags |= UserInfo.FLAG_EPHEMERAL;
2309 }
2310
2311 userInfo = new UserInfo(userId, name, null, flags);
2312 userInfo.serialNumber = mNextSerialNumber++;
2313 long now = System.currentTimeMillis();
2314 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2315 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002316 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002317 userData = new UserData();
2318 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002319 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002320 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002321 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002322 writeUserListLP();
2323 if (parent != null) {
2324 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002325 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2326 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002327 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002328 }
Amith Yamasani12747872015-12-07 14:19:49 -08002329 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002330 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002331 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2332 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002333 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002334 }
Amith Yamasani12747872015-12-07 14:19:49 -08002335 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002336 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002337 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002338 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002339 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002340 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002341 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002342 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002343 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002344 userInfo.partial = false;
2345 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002346 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002347 }
2348 updateUserIds();
2349 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002350 if (isGuest) {
2351 synchronized (mGuestRestrictions) {
2352 restrictions.putAll(mGuestRestrictions);
2353 }
2354 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002355 synchronized (mRestrictionsLock) {
2356 mBaseUserRestrictions.append(userId, restrictions);
2357 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002358 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002359 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2360 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2361 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2362 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002363 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002364 } finally {
2365 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002366 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002367 return userInfo;
2368 }
2369
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002370 @VisibleForTesting
2371 UserData putUserInfo(UserInfo userInfo) {
2372 final UserData userData = new UserData();
2373 userData.info = userInfo;
2374 synchronized (mUsers) {
2375 mUsers.put(userInfo.id, userData);
2376 }
2377 return userData;
2378 }
2379
2380 @VisibleForTesting
2381 void removeUserInfo(int userId) {
2382 synchronized (mUsers) {
2383 mUsers.remove(userId);
2384 }
2385 }
2386
Amith Yamasani0b285492011-04-14 17:35:23 -07002387 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002388 * @hide
2389 */
Amith Yamasani12747872015-12-07 14:19:49 -08002390 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002391 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002392 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002393 final UserInfo user = createProfileForUser(
2394 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002395 if (user == null) {
2396 return null;
2397 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002398 long identity = Binder.clearCallingIdentity();
2399 try {
2400 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2401 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2402 // the putIntForUser() will fail.
2403 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2404 android.provider.Settings.Secure.LOCATION_MODE,
2405 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2406 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2407 } finally {
2408 Binder.restoreCallingIdentity(identity);
2409 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002410 return user;
2411 }
2412
2413 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002414 * Find the current guest user. If the Guest user is partial,
2415 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002416 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002417 private UserInfo findCurrentGuestUser() {
2418 synchronized (mUsersLock) {
2419 final int size = mUsers.size();
2420 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002421 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002422 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2423 return user;
2424 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002425 }
2426 }
2427 return null;
2428 }
2429
2430 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002431 * Mark this guest user for deletion to allow us to create another guest
2432 * and switch to that user before actually removing this guest.
2433 * @param userHandle the userid of the current guest
2434 * @return whether the user could be marked for deletion
2435 */
Amith Yamasani12747872015-12-07 14:19:49 -08002436 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002437 public boolean markGuestForDeletion(int userHandle) {
2438 checkManageUsersPermission("Only the system can remove users");
2439 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2440 UserManager.DISALLOW_REMOVE_USER, false)) {
2441 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2442 return false;
2443 }
2444
2445 long ident = Binder.clearCallingIdentity();
2446 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002447 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002448 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002449 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002450 userData = mUsers.get(userHandle);
2451 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002452 return false;
2453 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002454 }
Amith Yamasani12747872015-12-07 14:19:49 -08002455 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002456 return false;
2457 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002458 // We set this to a guest user that is to be removed. This is a temporary state
2459 // where we are allowed to add new Guest users, even if this one is still not
2460 // removed. This user will still show up in getUserInfo() calls.
2461 // If we don't get around to removing this Guest user, it will be purged on next
2462 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002463 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002464 // Mark it as disabled, so that it isn't returned any more when
2465 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002466 userData.info.flags |= UserInfo.FLAG_DISABLED;
2467 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002468 }
2469 } finally {
2470 Binder.restoreCallingIdentity(ident);
2471 }
2472 return true;
2473 }
2474
2475 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002476 * Removes a user and all data directories created for that user. This method should be called
2477 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002478 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002479 */
Amith Yamasani12747872015-12-07 14:19:49 -08002480 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002481 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002482 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002483 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2484 UserManager.DISALLOW_REMOVE_USER, false)) {
2485 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2486 return false;
2487 }
2488
Kenny Guyee58b4f2014-05-23 15:19:53 +01002489 long ident = Binder.clearCallingIdentity();
2490 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002491 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002492 int currentUser = ActivityManager.getCurrentUser();
2493 if (currentUser == userHandle) {
2494 Log.w(LOG_TAG, "Current user cannot be removed");
2495 return false;
2496 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002497 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002498 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002499 userData = mUsers.get(userHandle);
2500 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002501 return false;
2502 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002503
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002504 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002505 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002506
Kenny Guyee58b4f2014-05-23 15:19:53 +01002507 try {
2508 mAppOpsService.removeUser(userHandle);
2509 } catch (RemoteException e) {
2510 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2511 }
2512 // Set this to a partially created user, so that the user will be purged
2513 // on next startup, in case the runtime stops now before stopping and
2514 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002515 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002516 // Mark it as disabled, so that it isn't returned any more when
2517 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002518 userData.info.flags |= UserInfo.FLAG_DISABLED;
2519 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002520 }
2521
Amith Yamasani12747872015-12-07 14:19:49 -08002522 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2523 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002524 // Send broadcast to notify system that the user removed was a
2525 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002526 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002527 }
2528
2529 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2530 int res;
2531 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002532 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2533 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002534 @Override
2535 public void userStopped(int userId) {
2536 finishRemoveUser(userId);
2537 }
2538 @Override
2539 public void userStopAborted(int userId) {
2540 }
2541 });
2542 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002543 return false;
2544 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002545 return res == ActivityManager.USER_OP_SUCCESS;
2546 } finally {
2547 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002548 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002549 }
2550
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002551 @VisibleForTesting
2552 void addRemovingUserIdLocked(int userId) {
2553 // We remember deleted user IDs to prevent them from being
2554 // reused during the current boot; they can still be reused
2555 // after a reboot or recycling of userIds.
2556 mRemovingUserIds.put(userId, true);
2557 mRecentlyRemovedIds.add(userId);
2558 // Keep LRU queue of recently removed IDs for recycling
2559 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2560 mRecentlyRemovedIds.removeFirst();
2561 }
2562 }
2563
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002564 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002565 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002566 // Let other services shutdown any activity and clean up their state before completely
2567 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002568 long ident = Binder.clearCallingIdentity();
2569 try {
2570 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2571 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002572 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2573 android.Manifest.permission.MANAGE_USERS,
2574
2575 new BroadcastReceiver() {
2576 @Override
2577 public void onReceive(Context context, Intent intent) {
2578 if (DBG) {
2579 Slog.i(LOG_TAG,
2580 "USER_REMOVED broadcast sent, cleaning up user data "
2581 + userHandle);
2582 }
2583 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002584 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002585 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002586 // Clean up any ActivityManager state
2587 LocalServices.getService(ActivityManagerInternal.class)
2588 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002589 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002590 }
2591 }.start();
2592 }
2593 },
2594
2595 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002596 } finally {
2597 Binder.restoreCallingIdentity(ident);
2598 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002599 }
2600
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002601 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002602 try {
2603 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2604 } catch (IllegalStateException e) {
2605 // This may be simply because the user was partially created.
2606 Slog.i(LOG_TAG,
2607 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2608 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002609
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002610 // Cleanup gatekeeper secure user id
2611 try {
2612 final IGateKeeperService gk = GateKeeper.getService();
2613 if (gk != null) {
2614 gk.clearSecureUserId(userHandle);
2615 }
2616 } catch (Exception ex) {
2617 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2618 }
2619
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002620 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002621 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002622
2623 // Clean up all data before removing metadata
2624 mPm.destroyUserData(userHandle,
2625 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2626
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002627 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002628 synchronized (mUsersLock) {
2629 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002630 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002631 }
2632 synchronized (mUserStates) {
2633 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002634 }
2635 synchronized (mRestrictionsLock) {
2636 mBaseUserRestrictions.remove(userHandle);
2637 mAppliedUserRestrictions.remove(userHandle);
2638 mCachedEffectiveUserRestrictions.remove(userHandle);
2639 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002640 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002641 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002642 synchronized (mPackagesLock) {
2643 writeUserListLP();
2644 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002645 // Remove user file
2646 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2647 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002648 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002649 if (RELEASE_DELETED_USER_ID) {
2650 synchronized (mUsers) {
2651 mRemovingUserIds.delete(userHandle);
2652 }
2653 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002654 }
2655
Kenny Guyf8d3a232014-05-15 16:09:52 +01002656 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002657 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002658 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2659 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002660 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002661 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002662 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002663 }
2664
Amith Yamasani2a003292012-08-14 18:25:45 -07002665 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002666 public Bundle getApplicationRestrictions(String packageName) {
2667 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2668 }
2669
2670 @Override
2671 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002672 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002673 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002674 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002675 }
2676 synchronized (mPackagesLock) {
2677 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002678 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002679 }
2680 }
2681
2682 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002683 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002684 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002685 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002686 if (restrictions != null) {
2687 restrictions.setDefusable(true);
2688 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002689 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002690 if (restrictions == null || restrictions.isEmpty()) {
2691 cleanAppRestrictionsForPackage(packageName, userId);
2692 } else {
2693 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002694 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002695 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002696 }
Robin Lee66e5d962014-04-09 16:44:21 +01002697
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002698 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2699 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2700 changeIntent.setPackage(packageName);
2701 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2702 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002703 }
2704
2705 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002706 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002707 try {
2708 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002709 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002710 } catch (NameNotFoundException nnfe) {
2711 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002712 } finally {
2713 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002714 }
2715 }
2716
Fyodor Kupolov82402752015-10-28 14:54:51 -07002717 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002718 AtomicFile restrictionsFile =
2719 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2720 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002721 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002722 }
2723
2724 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002725 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002726 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002727 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002728 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002729 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002730 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002731
2732 FileInputStream fis = null;
2733 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002734 fis = restrictionsFile.openRead();
2735 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002736 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002737 XmlUtils.nextElement(parser);
2738 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002739 Slog.e(LOG_TAG, "Unable to read restrictions file "
2740 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002741 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002742 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002743 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2744 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002745 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002746 } catch (IOException|XmlPullParserException e) {
2747 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002748 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002749 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002750 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002751 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002752 }
2753
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002754 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2755 XmlPullParser parser) throws XmlPullParserException, IOException {
2756 int type = parser.getEventType();
2757 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2758 String key = parser.getAttributeValue(null, ATTR_KEY);
2759 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2760 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2761 if (multiple != null) {
2762 values.clear();
2763 int count = Integer.parseInt(multiple);
2764 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2765 if (type == XmlPullParser.START_TAG
2766 && parser.getName().equals(TAG_VALUE)) {
2767 values.add(parser.nextText().trim());
2768 count--;
2769 }
2770 }
2771 String [] valueStrings = new String[values.size()];
2772 values.toArray(valueStrings);
2773 restrictions.putStringArray(key, valueStrings);
2774 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2775 restrictions.putBundle(key, readBundleEntry(parser, values));
2776 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2777 final int outerDepth = parser.getDepth();
2778 ArrayList<Bundle> bundleList = new ArrayList<>();
2779 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2780 Bundle childBundle = readBundleEntry(parser, values);
2781 bundleList.add(childBundle);
2782 }
2783 restrictions.putParcelableArray(key,
2784 bundleList.toArray(new Bundle[bundleList.size()]));
2785 } else {
2786 String value = parser.nextText().trim();
2787 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2788 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2789 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2790 restrictions.putInt(key, Integer.parseInt(value));
2791 } else {
2792 restrictions.putString(key, value);
2793 }
2794 }
2795 }
2796 }
2797
2798 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2799 throws IOException, XmlPullParserException {
2800 Bundle childBundle = new Bundle();
2801 final int outerDepth = parser.getDepth();
2802 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2803 readEntry(childBundle, values, parser);
2804 }
2805 return childBundle;
2806 }
2807
Fyodor Kupolov82402752015-10-28 14:54:51 -07002808 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002809 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002810 AtomicFile restrictionsFile = new AtomicFile(
2811 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002812 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002813 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002814 }
2815
2816 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002817 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002818 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002819 try {
2820 fos = restrictionsFile.startWrite();
2821 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2822
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002823 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002824 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002825 serializer.startDocument(null, true);
2826 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2827
2828 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002829 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002830 serializer.endTag(null, TAG_RESTRICTIONS);
2831
2832 serializer.endDocument();
2833 restrictionsFile.finishWrite(fos);
2834 } catch (Exception e) {
2835 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002836 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2837 }
2838 }
2839
2840 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2841 throws IOException {
2842 for (String key : restrictions.keySet()) {
2843 Object value = restrictions.get(key);
2844 serializer.startTag(null, TAG_ENTRY);
2845 serializer.attribute(null, ATTR_KEY, key);
2846
2847 if (value instanceof Boolean) {
2848 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2849 serializer.text(value.toString());
2850 } else if (value instanceof Integer) {
2851 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2852 serializer.text(value.toString());
2853 } else if (value == null || value instanceof String) {
2854 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2855 serializer.text(value != null ? (String) value : "");
2856 } else if (value instanceof Bundle) {
2857 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2858 writeBundle((Bundle) value, serializer);
2859 } else if (value instanceof Parcelable[]) {
2860 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2861 Parcelable[] array = (Parcelable[]) value;
2862 for (Parcelable parcelable : array) {
2863 if (!(parcelable instanceof Bundle)) {
2864 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2865 }
2866 serializer.startTag(null, TAG_ENTRY);
2867 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2868 writeBundle((Bundle) parcelable, serializer);
2869 serializer.endTag(null, TAG_ENTRY);
2870 }
2871 } else {
2872 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2873 String[] values = (String[]) value;
2874 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2875 for (String choice : values) {
2876 serializer.startTag(null, TAG_VALUE);
2877 serializer.text(choice != null ? choice : "");
2878 serializer.endTag(null, TAG_VALUE);
2879 }
2880 }
2881 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002882 }
2883 }
2884
2885 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002886 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002887 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002888 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002889 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002890 }
2891 }
2892
2893 @Override
2894 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002895 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002896 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002897 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002898 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002899 }
2900 // Not found
2901 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002902 }
2903 }
2904
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002905 @Override
2906 public long getUserCreationTime(int userHandle) {
2907 int callingUserId = UserHandle.getCallingUserId();
2908 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002909 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002910 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002911 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002912 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002913 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002914 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002915 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002916 }
2917 }
2918 }
2919 if (userInfo == null) {
2920 throw new SecurityException("userHandle can only be the calling user or a managed "
2921 + "profile associated with this user");
2922 }
2923 return userInfo.creationTime;
2924 }
2925
Amith Yamasani0b285492011-04-14 17:35:23 -07002926 /**
2927 * Caches the list of user ids in an array, adjusting the array size when necessary.
2928 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002929 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002930 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002931 synchronized (mUsersLock) {
2932 final int userSize = mUsers.size();
2933 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002934 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002935 num++;
2936 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002937 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002938 final int[] newUsers = new int[num];
2939 int n = 0;
2940 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002941 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002942 newUsers[n++] = mUsers.keyAt(i);
2943 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002944 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002945 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002946 }
2947 }
2948
2949 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002950 * Called right before a user is started. This gives us a chance to prepare
2951 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002952 */
2953 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002954 UserInfo userInfo = getUserInfo(userId);
2955 if (userInfo == null) {
2956 return;
2957 }
2958 final int userSerial = userInfo.serialNumber;
2959 // Migrate only if build fingerprints mismatch
2960 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002961 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002962 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002963
2964 if (userId != UserHandle.USER_SYSTEM) {
2965 synchronized (mRestrictionsLock) {
2966 applyUserRestrictionsLR(userId);
2967 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002968 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002969
2970 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002971 }
2972
2973 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002974 * Called right before a user is unlocked. This gives us a chance to prepare
2975 * app storage.
2976 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002977 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002978 UserInfo userInfo = getUserInfo(userId);
2979 if (userInfo == null) {
2980 return;
2981 }
2982 final int userSerial = userInfo.serialNumber;
2983 // Migrate only if build fingerprints mismatch
2984 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002985 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002986 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002987 }
2988
2989 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002990 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002991 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002992 * @param userId the user that was just foregrounded
2993 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002994 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002995 UserData userData = getUserDataNoChecks(userId);
2996 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002997 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2998 return;
2999 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003000
3001 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003002 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003003 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003004 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003005 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3006 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003007 }
3008
Amith Yamasanieb437d42016-04-29 09:31:25 -07003009 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07003010 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07003011 String demoLauncher =
3012 mContext.getResources().getString(
3013 com.android.internal.R.string.config_demoModeLauncherComponent);
3014 if (!TextUtils.isEmpty(demoLauncher)) {
3015 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07003016 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00003017 try {
3018 final IPackageManager iPm = AppGlobals.getPackageManager();
3019 iPm.setComponentEnabledSetting(componentToEnable,
3020 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3021 /* userId= */ userId);
3022 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3023 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3024 /* userId= */ userId, null);
3025 } catch (RemoteException re) {
3026 // Internal, shouldn't happen
3027 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003028 }
3029 }
3030 }
3031
Amith Yamasani920ace02012-09-20 22:15:37 -07003032 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003033 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003034 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003035 @VisibleForTesting
3036 int getNextAvailableId() {
3037 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003038 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003039 nextId = scanNextAvailableIdLocked();
3040 if (nextId >= 0) {
3041 return nextId;
3042 }
3043 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3044 // except most recently removed
3045 if (mRemovingUserIds.size() > 0) {
3046 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3047 mRemovingUserIds.clear();
3048 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3049 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003050 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003051 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003052 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003053 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003054 if (nextId < 0) {
3055 throw new IllegalStateException("No user id available!");
3056 }
3057 return nextId;
3058 }
3059
3060 private int scanNextAvailableIdLocked() {
3061 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3062 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3063 return i;
3064 }
3065 }
3066 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003067 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003068
Amith Yamasanifc95e702013-09-26 13:20:17 -07003069 private String packageToRestrictionsFileName(String packageName) {
3070 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3071 }
3072
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003073 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003074 * Enforce that serial number stored in user directory inode matches the
3075 * given expected value. Gracefully sets the serial number if currently
3076 * undefined.
3077 *
3078 * @throws IOException when problem extracting serial number, or serial
3079 * number is mismatched.
3080 */
3081 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003082 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3083 // When we're emulating FBE, the directory may have been chmod
3084 // 000'ed, meaning we can't read the serial number to enforce it;
3085 // instead of destroying the user, just log a warning.
3086 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3087 return;
3088 }
3089
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003090 final int foundSerial = getSerialNumber(file);
3091 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3092
3093 if (foundSerial == -1) {
3094 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3095 try {
3096 setSerialNumber(file, serialNumber);
3097 } catch (IOException e) {
3098 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3099 }
3100
3101 } else if (foundSerial != serialNumber) {
3102 throw new IOException("Found serial number " + foundSerial
3103 + " doesn't match expected " + serialNumber);
3104 }
3105 }
3106
3107 /**
3108 * Set serial number stored in user directory inode.
3109 *
3110 * @throws IOException if serial number was already set
3111 */
3112 private static void setSerialNumber(File file, int serialNumber)
3113 throws IOException {
3114 try {
3115 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3116 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3117 } catch (ErrnoException e) {
3118 throw e.rethrowAsIOException();
3119 }
3120 }
3121
3122 /**
3123 * Return serial number stored in user directory inode.
3124 *
3125 * @return parsed serial number, or -1 if not set
3126 */
3127 private static int getSerialNumber(File file) throws IOException {
3128 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003129 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3130 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003131 try {
3132 return Integer.parseInt(serial);
3133 } catch (NumberFormatException e) {
3134 throw new IOException("Bad serial number: " + serial);
3135 }
3136 } catch (ErrnoException e) {
3137 if (e.errno == OsConstants.ENODATA) {
3138 return -1;
3139 } else {
3140 throw e.rethrowAsIOException();
3141 }
3142 }
3143 }
3144
Amith Yamasani920ace02012-09-20 22:15:37 -07003145 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003146 public void setSeedAccountData(int userId, String accountName, String accountType,
3147 PersistableBundle accountOptions, boolean persist) {
3148 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3149 synchronized (mPackagesLock) {
3150 final UserData userData;
3151 synchronized (mUsersLock) {
3152 userData = getUserDataLU(userId);
3153 if (userData == null) {
3154 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3155 return;
3156 }
3157 userData.seedAccountName = accountName;
3158 userData.seedAccountType = accountType;
3159 userData.seedAccountOptions = accountOptions;
3160 userData.persistSeedData = persist;
3161 }
3162 if (persist) {
3163 writeUserLP(userData);
3164 }
3165 }
3166 }
3167
3168 @Override
3169 public String getSeedAccountName() throws RemoteException {
3170 checkManageUsersPermission("Cannot get seed account information");
3171 synchronized (mUsersLock) {
3172 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3173 return userData.seedAccountName;
3174 }
3175 }
3176
3177 @Override
3178 public String getSeedAccountType() throws RemoteException {
3179 checkManageUsersPermission("Cannot get seed account information");
3180 synchronized (mUsersLock) {
3181 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3182 return userData.seedAccountType;
3183 }
3184 }
3185
3186 @Override
3187 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3188 checkManageUsersPermission("Cannot get seed account information");
3189 synchronized (mUsersLock) {
3190 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3191 return userData.seedAccountOptions;
3192 }
3193 }
3194
3195 @Override
3196 public void clearSeedAccountData() throws RemoteException {
3197 checkManageUsersPermission("Cannot clear seed account information");
3198 synchronized (mPackagesLock) {
3199 UserData userData;
3200 synchronized (mUsersLock) {
3201 userData = getUserDataLU(UserHandle.getCallingUserId());
3202 if (userData == null) return;
3203 userData.clearSeedAccountData();
3204 }
3205 writeUserLP(userData);
3206 }
3207 }
3208
3209 @Override
3210 public boolean someUserHasSeedAccount(String accountName, String accountType)
3211 throws RemoteException {
3212 checkManageUsersPermission("Cannot check seed account information");
3213 synchronized (mUsersLock) {
3214 final int userSize = mUsers.size();
3215 for (int i = 0; i < userSize; i++) {
3216 final UserData data = mUsers.valueAt(i);
3217 if (data.info.isInitialized()) continue;
3218 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3219 continue;
3220 }
3221 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3222 continue;
3223 }
3224 return true;
3225 }
3226 }
3227 return false;
3228 }
3229
3230 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003231 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003232 FileDescriptor err, String[] args, ShellCallback callback,
3233 ResultReceiver resultReceiver) {
3234 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003235 }
3236
3237 int onShellCommand(Shell shell, String cmd) {
3238 if (cmd == null) {
3239 return shell.handleDefaultCommands(cmd);
3240 }
3241
3242 final PrintWriter pw = shell.getOutPrintWriter();
3243 try {
3244 switch(cmd) {
3245 case "list":
3246 return runList(pw);
3247 }
3248 } catch (RemoteException e) {
3249 pw.println("Remote exception: " + e);
3250 }
3251 return -1;
3252 }
3253
3254 private int runList(PrintWriter pw) throws RemoteException {
3255 final IActivityManager am = ActivityManagerNative.getDefault();
3256 final List<UserInfo> users = getUsers(false);
3257 if (users == null) {
3258 pw.println("Error: couldn't get users");
3259 return 1;
3260 } else {
3261 pw.println("Users:");
3262 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003263 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003264 pw.println("\t" + users.get(i).toString() + running);
3265 }
3266 return 0;
3267 }
3268 }
3269
3270 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003271 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3272 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3273 != PackageManager.PERMISSION_GRANTED) {
3274 pw.println("Permission Denial: can't dump UserManager from from pid="
3275 + Binder.getCallingPid()
3276 + ", uid=" + Binder.getCallingUid()
3277 + " without permission "
3278 + android.Manifest.permission.DUMP);
3279 return;
3280 }
3281
3282 long now = System.currentTimeMillis();
3283 StringBuilder sb = new StringBuilder();
3284 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003285 synchronized (mUsersLock) {
3286 pw.println("Users:");
3287 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003288 UserData userData = mUsers.valueAt(i);
3289 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003290 continue;
3291 }
Amith Yamasani12747872015-12-07 14:19:49 -08003292 UserInfo userInfo = userData.info;
3293 final int userId = userInfo.id;
3294 pw.print(" "); pw.print(userInfo);
3295 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003296 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003297 pw.print(" <removing> ");
3298 }
Amith Yamasani12747872015-12-07 14:19:49 -08003299 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003300 pw.print(" <partial>");
3301 }
3302 pw.println();
3303 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003304 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003305 pw.println("<unknown>");
3306 } else {
3307 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003308 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003309 sb.append(" ago");
3310 pw.println(sb);
3311 }
3312 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003313 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003314 pw.println("<unknown>");
3315 } else {
3316 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003317 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003318 sb.append(" ago");
3319 pw.println(sb);
3320 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003321 pw.print(" Last logged in fingerprint: ");
3322 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003323 pw.print(" Has profile owner: ");
3324 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003325 pw.println(" Restrictions:");
3326 synchronized (mRestrictionsLock) {
3327 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003328 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003329 pw.println(" Device policy local restrictions:");
3330 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003331 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003332 pw.println(" Effective restrictions:");
3333 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003334 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003335 }
Amith Yamasani12747872015-12-07 14:19:49 -08003336
3337 if (userData.account != null) {
3338 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003339 pw.println();
3340 }
Amith Yamasani12747872015-12-07 14:19:49 -08003341
3342 if (userData.seedAccountName != null) {
3343 pw.print(" Seed account name: " + userData.seedAccountName);
3344 pw.println();
3345 if (userData.seedAccountType != null) {
3346 pw.print(" account type: " + userData.seedAccountType);
3347 pw.println();
3348 }
3349 if (userData.seedAccountOptions != null) {
3350 pw.print(" account options exist");
3351 pw.println();
3352 }
3353 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003354 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003355 }
Amith Yamasani12747872015-12-07 14:19:49 -08003356 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003357 pw.println(" Device policy global restrictions:");
3358 synchronized (mRestrictionsLock) {
3359 UserRestrictionsUtils
3360 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3361 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003362 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003363 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3364 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003365 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003366 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003367 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003368 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003369 synchronized (mUsersLock) {
3370 pw.println();
3371 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003372 if (mRemovingUserIds.size() > 0) {
3373 pw.println();
3374 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3375 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003376 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003377 synchronized (mUserStates) {
3378 pw.println(" Started users state: " + mUserStates);
3379 }
Amith Yamasani12747872015-12-07 14:19:49 -08003380 // Dump some capabilities
3381 pw.println();
3382 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3383 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003384 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3385 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003386 }
3387 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003388
3389 final class MainHandler extends Handler {
3390
3391 @Override
3392 public void handleMessage(Message msg) {
3393 switch (msg.what) {
3394 case WRITE_USER_MSG:
3395 removeMessages(WRITE_USER_MSG, msg.obj);
3396 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003397 int userId = ((UserData) msg.obj).info.id;
3398 UserData userData = getUserDataNoChecks(userId);
3399 if (userData != null) {
3400 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003401 }
3402 }
3403 }
3404 }
3405 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003406
3407 /**
3408 * @param userId
3409 * @return whether the user has been initialized yet
3410 */
3411 boolean isInitialized(int userId) {
3412 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3413 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003414
3415 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003416 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003417 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3418 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003419 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003420 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003421 }
3422
3423 @Override
3424 public Bundle getBaseUserRestrictions(int userId) {
3425 synchronized (mRestrictionsLock) {
3426 return mBaseUserRestrictions.get(userId);
3427 }
3428 }
3429
3430 @Override
3431 public void setBaseUserRestrictionsByDpmsForMigration(
3432 int userId, Bundle baseRestrictions) {
3433 synchronized (mRestrictionsLock) {
3434 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003435 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003436 }
3437
Amith Yamasani12747872015-12-07 14:19:49 -08003438 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003439 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003440 if (userData != null) {
3441 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003442 } else {
3443 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3444 }
3445 }
3446 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003447
3448 @Override
3449 public boolean getUserRestriction(int userId, String key) {
3450 return getUserRestrictions(userId).getBoolean(key);
3451 }
3452
3453 @Override
3454 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3455 synchronized (mUserRestrictionsListeners) {
3456 mUserRestrictionsListeners.add(listener);
3457 }
3458 }
3459
3460 @Override
3461 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3462 synchronized (mUserRestrictionsListeners) {
3463 mUserRestrictionsListeners.remove(listener);
3464 }
3465 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003466
3467 @Override
3468 public void setDeviceManaged(boolean isManaged) {
3469 synchronized (mUsersLock) {
3470 mIsDeviceManaged = isManaged;
3471 }
3472 }
3473
3474 @Override
3475 public void setUserManaged(int userId, boolean isManaged) {
3476 synchronized (mUsersLock) {
3477 mIsUserManaged.put(userId, isManaged);
3478 }
3479 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003480
3481 @Override
3482 public void setUserIcon(int userId, Bitmap bitmap) {
3483 long ident = Binder.clearCallingIdentity();
3484 try {
3485 synchronized (mPackagesLock) {
3486 UserData userData = getUserDataNoChecks(userId);
3487 if (userData == null || userData.info.partial) {
3488 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3489 return;
3490 }
3491 writeBitmapLP(userData.info, bitmap);
3492 writeUserLP(userData);
3493 }
3494 sendUserInfoChangedBroadcast(userId);
3495 } finally {
3496 Binder.restoreCallingIdentity(ident);
3497 }
3498 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003499
3500 @Override
3501 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3502 synchronized (mUsersLock) {
3503 mForceEphemeralUsers = forceEphemeralUsers;
3504 }
3505 }
3506
3507 @Override
3508 public void removeAllUsers() {
3509 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3510 // Remove the non-system users straight away.
3511 removeNonSystemUsers();
3512 } else {
3513 // Switch to the system user first and then remove the other users.
3514 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3515 @Override
3516 public void onReceive(Context context, Intent intent) {
3517 int userId =
3518 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3519 if (userId != UserHandle.USER_SYSTEM) {
3520 return;
3521 }
3522 mContext.unregisterReceiver(this);
3523 removeNonSystemUsers();
3524 }
3525 };
3526 IntentFilter userSwitchedFilter = new IntentFilter();
3527 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3528 mContext.registerReceiver(
3529 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3530
3531 // Switch to the system user.
3532 ActivityManager am =
3533 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3534 am.switchUser(UserHandle.USER_SYSTEM);
3535 }
3536 }
phweisse9c44062016-02-10 12:57:38 +01003537
3538 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003539 public void onEphemeralUserStop(int userId) {
3540 synchronized (mUsersLock) {
3541 UserInfo userInfo = getUserInfoLU(userId);
3542 if (userInfo != null && userInfo.isEphemeral()) {
3543 // Do not allow switching back to the ephemeral user again as the user is going
3544 // to be deleted.
3545 userInfo.flags |= UserInfo.FLAG_DISABLED;
3546 if (userInfo.isGuest()) {
3547 // Indicate that the guest will be deleted after it stops.
3548 userInfo.guestToRemove = true;
3549 }
3550 }
3551 }
3552 }
3553
3554 @Override
phweisse9c44062016-02-10 12:57:38 +01003555 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003556 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003557 // Keep this in sync with UserManager.createUser
3558 if (user != null && !user.isAdmin()) {
3559 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3560 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3561 }
3562 return user;
3563 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003564
3565 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003566 public boolean isUserRunning(int userId) {
3567 synchronized (mUserStates) {
3568 return mUserStates.get(userId, -1) >= 0;
3569 }
3570 }
3571
3572 @Override
3573 public void setUserState(int userId, int userState) {
3574 synchronized (mUserStates) {
3575 mUserStates.put(userId, userState);
3576 }
3577 }
3578
3579 @Override
3580 public void removeUserState(int userId) {
3581 synchronized (mUserStates) {
3582 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003583 }
3584 }
3585
3586 @Override
3587 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003588 synchronized (mUserStates) {
3589 int state = mUserStates.get(userId, -1);
3590 return (state == UserState.STATE_RUNNING_UNLOCKING)
3591 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003592 }
3593 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003594 }
3595
3596 /* Remove all the users except of the system one. */
3597 private void removeNonSystemUsers() {
3598 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3599 synchronized (mUsersLock) {
3600 final int userSize = mUsers.size();
3601 for (int i = 0; i < userSize; i++) {
3602 UserInfo ui = mUsers.valueAt(i).info;
3603 if (ui.id != UserHandle.USER_SYSTEM) {
3604 usersToRemove.add(ui);
3605 }
3606 }
3607 }
3608 for (UserInfo ui: usersToRemove) {
3609 removeUser(ui.id);
3610 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003611 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003612
3613 private class Shell extends ShellCommand {
3614 @Override
3615 public int onCommand(String cmd) {
3616 return onShellCommand(this, cmd);
3617 }
3618
3619 @Override
3620 public void onHelp() {
3621 final PrintWriter pw = getOutPrintWriter();
3622 pw.println("User manager (user) commands:");
3623 pw.println(" help");
3624 pw.println(" Print this help text.");
3625 pw.println("");
3626 pw.println(" list");
3627 pw.println(" Prints all users on the system.");
3628 }
3629 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003630
3631 private static void debug(String message) {
3632 Log.d(LOG_TAG, message +
3633 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3634 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003635}