blob: 20afed736bab551d1b7b8e4a221f8850a2897f68 [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;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000029import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000035import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000040import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070041import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080042import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010044import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070045import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060047import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080048import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080049import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.os.Environment;
51import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080053import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080055import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010056import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080058import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070060import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010062import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Kenny Guy02c89902016-11-15 19:36:38 +000066import android.os.SystemProperties;
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;
Kenny Guy02c89902016-11-15 19:36:38 +0000114import java.io.InputStream;
115import java.io.OutputStream;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700117import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100118import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119import java.util.ArrayList;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700120import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121import java.util.List;
122
Makoto Onuki068c54a2015-10-13 14:34:03 -0700123/**
124 * Service for {@link UserManager}.
125 *
126 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700127 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800128 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700129 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
130 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
131 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700132 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700133public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700134
Amith Yamasani2a003292012-08-14 18:25:45 -0700135 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800136 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800137 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700138 // Can be used for manual testing of id recycling
139 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700140
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800142 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700144 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700146 private static final String ATTR_CREATION_TIME = "created";
147 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600148 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700149 private static final String ATTR_SERIAL_NO = "serialNumber";
150 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700151 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700152 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700153 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100154 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000155 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700156 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800157 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
158 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530159 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700160 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800162 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800163 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100164 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800165 private static final String TAG_ENTRY = "entry";
166 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800167 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800168 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700169 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800170 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700172 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
173 private static final String ATTR_TYPE_STRING = "s";
174 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700175 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700176 private static final String ATTR_TYPE_BUNDLE = "B";
177 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700178
Amith Yamasani0b285492011-04-14 17:35:23 -0700179 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700180 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700181 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100182 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800184 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700185 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800186
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700187 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
188 UserInfo.FLAG_MANAGED_PROFILE
189 | UserInfo.FLAG_EPHEMERAL
190 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700191 | UserInfo.FLAG_GUEST
192 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700193
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700194 @VisibleForTesting
195 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700196 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700197 @VisibleForTesting
198 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
199
200 // Max size of the queue of recently removed users
201 @VisibleForTesting
202 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700203
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700204 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700205
Amith Yamasani920ace02012-09-20 22:15:37 -0700206 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
207
Nicolas Prevotb8186812015-08-06 15:00:03 +0100208 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700209 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000210 @VisibleForTesting
211 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700212
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800213 static final int WRITE_USER_MSG = 1;
214 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530215
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700216 private static final String XATTR_SERIAL = "user.serial";
217
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800218 // Tron counters
219 private static final String TRON_GUEST_CREATED = "users_guest_created";
220 private static final String TRON_USER_CREATED = "users_user_created";
221
Dianne Hackborn4428e172012-08-24 17:43:05 -0700222 private final Context mContext;
223 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700224 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700225 // Short-term lock for internal state, when interaction/sync with PM is not required
226 private final Object mUsersLock = new Object();
227 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700228
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800229 private final Handler mHandler;
230
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700231 private final File mUsersDir;
232 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700233
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800234 private static final IBinder mUserRestriconToken = new Binder();
235
Makoto Onuki068c54a2015-10-13 14:34:03 -0700236 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800237 * User-related information that is used for persisting to flash. Only UserInfo is
238 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800239 */
Kenny Guy02c89902016-11-15 19:36:38 +0000240 @VisibleForTesting
241 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800242 // Basic user information and properties
243 UserInfo info;
244 // Account name used when there is a strong association between a user and an account
245 String account;
246 // Account information for seeding into a newly created user. This could also be
247 // used for login validation for an existing user, for updating their credentials.
248 // In the latter case, data may not need to be persisted as it is only valid for the
249 // current login session.
250 String seedAccountName;
251 String seedAccountType;
252 PersistableBundle seedAccountOptions;
253 // Whether to perist the seed account information to be available after a boot
254 boolean persistSeedData;
255
256 void clearSeedAccountData() {
257 seedAccountName = null;
258 seedAccountType = null;
259 seedAccountOptions = null;
260 persistSeedData = false;
261 }
262 }
263
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800264 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800265 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800266
267 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700268 * User restrictions set via UserManager. This doesn't include restrictions set by
269 * device owner / profile owners.
270 *
271 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
272 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
273 * maybe shared between {@link #mBaseUserRestrictions} and
274 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
275 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700276 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700277 */
278 @GuardedBy("mRestrictionsLock")
279 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
280
281 /**
282 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
283 * with device / profile owner restrictions. We'll initialize it lazily; use
284 * {@link #getEffectiveUserRestrictions} to access it.
285 *
286 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
287 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
288 * maybe shared between {@link #mBaseUserRestrictions} and
289 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
290 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700291 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700292 */
293 @GuardedBy("mRestrictionsLock")
294 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
295
Makoto Onuki4f160732015-10-27 17:15:38 -0700296 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800297 * User restrictions that have already been applied in
298 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
299 * that have changed since the last
300 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700301 */
302 @GuardedBy("mRestrictionsLock")
303 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
304
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800305 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800306 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
307 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800308 */
309 @GuardedBy("mRestrictionsLock")
310 private Bundle mDevicePolicyGlobalUserRestrictions;
311
312 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100313 * Id of the user that set global restrictions.
314 */
315 @GuardedBy("mRestrictionsLock")
316 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
317
318 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800319 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
320 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800321 */
322 @GuardedBy("mRestrictionsLock")
323 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
324
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800325 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530326 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800327
328 /**
329 * Set of user IDs being actively removed. Removed IDs linger in this set
330 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700331 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800332 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700333 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800334 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700335
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700336 /**
337 * Queue of recently removed userIds. Used for recycling of userIds
338 */
339 @GuardedBy("mUsersLock")
340 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
341
Fyodor Kupolov82402752015-10-28 14:54:51 -0700342 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700343 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800344 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700345 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700346 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700347
Jason Monk62062992014-05-06 09:55:28 -0400348 private IAppOpsService mAppOpsService;
349
Makoto Onuki068c54a2015-10-13 14:34:03 -0700350 private final LocalService mLocalService;
351
Makoto Onukie7927da2015-11-25 10:05:17 -0800352 @GuardedBy("mUsersLock")
353 private boolean mIsDeviceManaged;
354
355 @GuardedBy("mUsersLock")
356 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
357
Makoto Onukid45a4a22015-11-02 17:17:38 -0800358 @GuardedBy("mUserRestrictionsListeners")
359 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
360 new ArrayList<>();
361
Clara Bayarria1771112015-12-18 16:29:18 +0000362 private final LockPatternUtils mLockPatternUtils;
363
Ricky Waib1dd80b2016-06-07 18:00:55 +0100364 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
365 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
366
367 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
368 @Override
369 public void onReceive(Context context, Intent intent) {
370 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
371 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
372 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
373 setQuietModeEnabled(userHandle, false);
374 if (target != null) {
375 try {
376 mContext.startIntentSender(target, null, 0, 0, 0);
377 } catch (IntentSender.SendIntentException e) {
378 /* ignore */
379 }
380 }
381 }
382 }
383 };
384
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100385 /**
386 * Whether all users should be created ephemeral.
387 */
388 @GuardedBy("mUsersLock")
389 private boolean mForceEphemeralUsers;
390
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000391 @GuardedBy("mUserStates")
392 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700393
Amith Yamasani258848d2012-08-10 17:06:33 -0700394 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700395
Dianne Hackborn4428e172012-08-24 17:43:05 -0700396 public static UserManagerService getInstance() {
397 synchronized (UserManagerService.class) {
398 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700399 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700401
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700402 public static class LifeCycle extends SystemService {
403
404 private UserManagerService mUms;
405
406 /**
407 * @param context
408 */
409 public LifeCycle(Context context) {
410 super(context);
411 }
412
413 @Override
414 public void onStart() {
415 mUms = UserManagerService.getInstance();
416 publishBinderService(Context.USER_SERVICE, mUms);
417 }
418
419 @Override
420 public void onBootPhase(int phase) {
421 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
422 mUms.cleanupPartialUsers();
423 }
424 }
425 }
426
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700427 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800428 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700429 UserManagerService(Context context) {
430 this(context, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700431 }
432
Dianne Hackborn4428e172012-08-24 17:43:05 -0700433 /**
434 * Called by package manager to create the service. This is closely
435 * associated with the package manager, and the given lock is the
436 * package manager's own lock.
437 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800438 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
439 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700440 }
441
Dianne Hackborn4428e172012-08-24 17:43:05 -0700442 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800443 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700444 mContext = context;
445 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700446 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800447 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800448 synchronized (mPackagesLock) {
449 mUsersDir = new File(dataDir, USER_INFO_DIR);
450 mUsersDir.mkdirs();
451 // Make zeroth user directory, for services to migrate their files to that location
452 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
453 userZeroDir.mkdirs();
454 FileUtils.setPermissions(mUsersDir.toString(),
455 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
456 -1, -1);
457 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
458 initDefaultGuestRestrictions();
459 readUserListLP();
460 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700461 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700462 mLocalService = new LocalService();
463 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000464 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000465 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700466 }
467
468 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400469 mAppOpsService = IAppOpsService.Stub.asInterface(
470 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800471
472 synchronized (mRestrictionsLock) {
473 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400474 }
Samuel Tand9453b82016-03-14 15:57:02 -0700475
476 UserInfo currentGuestUser = findCurrentGuestUser();
477 if (currentGuestUser != null && !hasUserRestriction(
478 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
479 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
480 // to it, in case this guest was created in a previous version where this
481 // user restriction was not a default guest restriction.
482 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
483 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700484
Ricky Waib1dd80b2016-06-07 18:00:55 +0100485 mContext.registerReceiver(mDisableQuietModeCallback,
486 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
487 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700488 }
489
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700490 void cleanupPartialUsers() {
491 // Prune out any partially created, partially removed and ephemeral users.
492 ArrayList<UserInfo> partials = new ArrayList<>();
493 synchronized (mUsersLock) {
494 final int userSize = mUsers.size();
495 for (int i = 0; i < userSize; i++) {
496 UserInfo ui = mUsers.valueAt(i).info;
497 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
498 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700499 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700500 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700501 }
502 }
503 }
504 final int partialsSize = partials.size();
505 for (int i = 0; i < partialsSize; i++) {
506 UserInfo ui = partials.get(i);
507 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
508 + " (name=" + ui.name + ")");
509 removeUserState(ui.id);
510 }
511 }
512
Amith Yamasani258848d2012-08-10 17:06:33 -0700513 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800514 public String getUserAccount(int userId) {
515 checkManageUserAndAcrossUsersFullPermission("get user account");
516 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800517 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800518 }
519 }
520
521 @Override
522 public void setUserAccount(int userId, String accountName) {
523 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800524 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800525 synchronized (mPackagesLock) {
526 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800527 final UserData userData = mUsers.get(userId);
528 if (userData == null) {
529 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
530 return;
531 }
532 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800533 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800534 userData.account = accountName;
535 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800536 }
537 }
538
539 if (userToUpdate != null) {
540 writeUserLP(userToUpdate);
541 }
542 }
543 }
544
545 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700546 public UserInfo getPrimaryUser() {
547 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700549 final int userSize = mUsers.size();
550 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800551 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800552 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700553 return ui;
554 }
555 }
556 }
557 return null;
558 }
559
560 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700561 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700562 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700564 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700565 final int userSize = mUsers.size();
566 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800567 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700568 if (ui.partial) {
569 continue;
570 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800571 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700572 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700573 }
Amith Yamasani13593602012-03-22 16:16:17 -0700574 }
575 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700576 }
Amith Yamasani13593602012-03-22 16:16:17 -0700577 }
578
Amith Yamasani258848d2012-08-10 17:06:33 -0700579 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100580 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700581 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800582 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700583 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700584 } else {
585 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800586 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 final long ident = Binder.clearCallingIdentity();
588 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700589 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700590 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100591 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700592 } finally {
593 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000594 }
595 }
596
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700597 @Override
598 public int[] getProfileIds(int userId, boolean enabledOnly) {
599 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700600 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700601 }
602 final long ident = Binder.clearCallingIdentity();
603 try {
604 synchronized (mUsersLock) {
605 return getProfileIdsLU(userId, enabledOnly).toArray();
606 }
607 } finally {
608 Binder.restoreCallingIdentity(ident);
609 }
610 }
611
Amith Yamasanibe465322014-04-24 13:45:17 -0700612 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700613 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700614 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
615 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
616 for (int i = 0; i < profileIds.size(); i++) {
617 int profileId = profileIds.get(i);
618 UserInfo userInfo = mUsers.get(profileId).info;
619 // If full info is not required - clear PII data to prevent 3P apps from reading it
620 if (!fullInfo) {
621 userInfo = new UserInfo(userInfo);
622 userInfo.name = null;
623 userInfo.iconPath = null;
624 } else {
625 userInfo = userWithName(userInfo);
626 }
627 users.add(userInfo);
628 }
629 return users;
630 }
631
632 /**
633 * Assume permissions already checked and caller's identity cleared
634 */
635 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700636 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700637 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700638 if (user == null) {
639 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700640 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700641 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700642 final int userSize = mUsers.size();
643 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800644 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700645 if (!isProfileOf(user, profile)) {
646 continue;
647 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100648 if (enabledOnly && !profile.isEnabled()) {
649 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700650 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700651 if (mRemovingUserIds.get(profile.id)) {
652 continue;
653 }
Tony Mak80189cd2016-04-05 17:21:42 +0100654 if (profile.partial) {
655 continue;
656 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700657 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700658 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700659 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700660 }
661
Jessica Hummelbe81c802014-04-22 15:49:22 +0100662 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700663 public int getCredentialOwnerProfile(int userHandle) {
664 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000665 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700666 synchronized (mUsersLock) {
667 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700668 if (profileParent != null) {
669 return profileParent.id;
670 }
671 }
672 }
673
674 return userHandle;
675 }
676
677 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700678 public boolean isSameProfileGroup(int userId, int otherUserId) {
679 if (userId == otherUserId) return true;
680 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700681 return isSameProfileGroupNoChecks(userId, otherUserId);
682 }
683
684 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700685 synchronized (mUsersLock) {
686 UserInfo userInfo = getUserInfoLU(userId);
687 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
688 return false;
689 }
690 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
691 if (otherUserInfo == null
692 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
693 return false;
694 }
695 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700696 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700697 }
698
699 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100700 public UserInfo getProfileParent(int userHandle) {
701 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700702 synchronized (mUsersLock) {
703 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700704 }
705 }
706
Fyodor Kupolov82402752015-10-28 14:54:51 -0700707 private UserInfo getProfileParentLU(int userHandle) {
708 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700709 if (profile == null) {
710 return null;
711 }
712 int parentUserId = profile.profileGroupId;
713 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
714 return null;
715 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700716 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100717 }
718 }
719
Fyodor Kupolov82402752015-10-28 14:54:51 -0700720 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100721 return user.id == profile.id ||
722 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
723 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000724 }
725
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000726 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000727 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100728 Intent intent = new Intent();
729 if (inQuietMode) {
730 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
731 } else {
732 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
733 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000734 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
735 intent.putExtra(Intent.EXTRA_USER, profileHandle);
736 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000737 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000738 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000739 }
740
741 @Override
742 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
743 checkManageUsersPermission("silence profile");
744 boolean changed = false;
745 UserInfo profile, parent;
746 synchronized (mPackagesLock) {
747 synchronized (mUsersLock) {
748 profile = getUserInfoLU(userHandle);
749 parent = getProfileParentLU(userHandle);
750
751 }
752 if (profile == null || !profile.isManagedProfile()) {
753 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
754 }
755 if (profile.isQuietModeEnabled() != enableQuietMode) {
756 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800757 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000758 changed = true;
759 }
760 }
761 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000762 long identity = Binder.clearCallingIdentity();
763 try {
764 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800765 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100766 LocalServices.getService(ActivityManagerInternal.class)
767 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000768 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800769 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000770 }
771 } catch (RemoteException e) {
772 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
773 } finally {
774 Binder.restoreCallingIdentity(identity);
775 }
776
777 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
778 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000779 }
780 }
781
782 @Override
783 public boolean isQuietModeEnabled(int userHandle) {
784 synchronized (mPackagesLock) {
785 UserInfo info;
786 synchronized (mUsersLock) {
787 info = getUserInfoLU(userHandle);
788 }
789 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000790 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000791 }
792 return info.isQuietModeEnabled();
793 }
794 }
795
Kenny Guya52dc3e2014-02-11 15:33:14 +0000796 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100797 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100798 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600799 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100800 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100801 // if the user is already unlocked, no need to show a profile challenge
802 setQuietModeEnabled(userHandle, false);
803 return true;
804 }
805
806 long identity = Binder.clearCallingIdentity();
807 try {
808 // otherwise, we show a profile challenge to trigger decryption of the user
809 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
810 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100811 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
812 // lock, confirm screenlock page will know and show personal challenge, and unlock
813 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100814 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
815 userHandle);
816 if (unlockIntent == null) {
817 return false;
818 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100819 final Intent callBackIntent = new Intent(
820 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100821 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100822 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100823 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100824 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
825 callBackIntent.setPackage(mContext.getPackageName());
826 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
827 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
828 mContext,
829 0,
830 callBackIntent,
831 PendingIntent.FLAG_CANCEL_CURRENT |
832 PendingIntent.FLAG_ONE_SHOT |
833 PendingIntent.FLAG_IMMUTABLE);
834 // After unlocking the challenge, it will disable quiet mode and run the original
835 // intentSender
836 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100837 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
838 mContext.startActivity(unlockIntent);
839 } finally {
840 Binder.restoreCallingIdentity(identity);
841 }
842 return false;
843 }
844
845 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100846 public void setUserEnabled(int userId) {
847 checkManageUsersPermission("enable user");
848 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700849 UserInfo info;
850 synchronized (mUsersLock) {
851 info = getUserInfoLU(userId);
852 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100853 if (info != null && !info.isEnabled()) {
854 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800855 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100856 }
857 }
858 }
859
860 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700861 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700862 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000863 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700864 return userWithName(getUserInfoLU(userId));
865 }
866 }
867
868 /**
869 * Returns a UserInfo object with the name filled in, for Owner, or the original
870 * if the name is already set.
871 */
872 private UserInfo userWithName(UserInfo orig) {
873 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
874 UserInfo withName = new UserInfo(orig);
875 withName.name = getOwnerName();
876 return withName;
877 } else {
878 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000879 }
880 }
881
882 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000883 public int getManagedProfileBadge(@UserIdInt int userId) {
884 int callingUserId = UserHandle.getCallingUserId();
885 if (callingUserId != userId && !hasManageUsersPermission()) {
886 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
887 throw new SecurityException(
888 "You need MANAGE_USERS permission to: check if specified user a " +
889 "managed profile outside your profile group");
890 }
891 }
892 synchronized (mUsersLock) {
893 UserInfo userInfo = getUserInfoLU(userId);
894 return userInfo != null ? userInfo.profileBadge : 0;
895 }
896 }
897
898 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000899 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000900 int callingUserId = UserHandle.getCallingUserId();
901 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700902 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700903 throw new SecurityException(
904 "You need MANAGE_USERS permission to: check if specified user a " +
905 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000906 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000907 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700908 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700909 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000910 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700911 }
912 }
913
Amith Yamasani71e6c692013-03-24 17:39:28 -0700914 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700915 public boolean isUserUnlockingOrUnlocked(int userId) {
916 int callingUserId = UserHandle.getCallingUserId();
917 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700918 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700919 throw new SecurityException(
920 "You need MANAGE_USERS permission to: check isUserUnlockingOrUnlocked");
921 }
922 }
923 return mLocalService.isUserUnlockingOrUnlocked(userId);
924 }
925
926 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700927 public boolean isDemoUser(int userId) {
928 int callingUserId = UserHandle.getCallingUserId();
929 if (callingUserId != userId && !hasManageUsersPermission()) {
930 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
931 + " is a demo user");
932 }
933 synchronized (mUsersLock) {
934 UserInfo userInfo = getUserInfoLU(userId);
935 return userInfo != null && userInfo.isDemo();
936 }
937 }
938
939 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700940 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700941 synchronized (mUsersLock) {
942 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700943 }
944 }
945
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700946 @Override
947 public boolean canHaveRestrictedProfile(int userId) {
948 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700949 synchronized (mUsersLock) {
950 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700951 if (userInfo == null || !userInfo.canHaveProfile()) {
952 return false;
953 }
954 if (!userInfo.isAdmin()) {
955 return false;
956 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800957 // restricted profile can be created if there is no DO set and the admin user has no PO;
958 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700959 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700960 }
961
Amith Yamasani195263742012-08-21 15:40:12 -0700962 /*
963 * Should be locked on mUsers before calling this.
964 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700965 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800966 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700967 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800968 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700969 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
970 return null;
971 }
Amith Yamasani12747872015-12-07 14:19:49 -0800972 return userData != null ? userData.info : null;
973 }
974
975 private UserData getUserDataLU(int userId) {
976 final UserData userData = mUsers.get(userId);
977 // If it is partial and not in the process of being removed, return as unknown user.
978 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
979 return null;
980 }
981 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700982 }
983
Fyodor Kupolov82402752015-10-28 14:54:51 -0700984 /**
985 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
986 * <p>No permissions checking or any addition checks are made</p>
987 */
988 private UserInfo getUserInfoNoChecks(int userId) {
989 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800990 final UserData userData = mUsers.get(userId);
991 return userData != null ? userData.info : null;
992 }
993 }
994
995 /**
996 * Obtains {@link #mUsersLock} and return UserData from mUsers.
997 * <p>No permissions checking or any addition checks are made</p>
998 */
999 private UserData getUserDataNoChecks(int userId) {
1000 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001001 return mUsers.get(userId);
1002 }
1003 }
1004
Amith Yamasani236b2b52015-08-18 14:32:14 -07001005 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001006 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001007 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001008 }
1009
Amith Yamasani258848d2012-08-10 17:06:33 -07001010 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001011 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001012 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001013 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001014 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001015 UserData userData = getUserDataNoChecks(userId);
1016 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001017 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1018 return;
1019 }
Amith Yamasani12747872015-12-07 14:19:49 -08001020 if (name != null && !name.equals(userData.info.name)) {
1021 userData.info.name = name;
1022 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001023 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001024 }
1025 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001026 if (changed) {
1027 sendUserInfoChangedBroadcast(userId);
1028 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001029 }
1030
Amith Yamasani258848d2012-08-10 17:06:33 -07001031 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001032 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001033 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001034 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1035 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1036 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001037 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001038 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001039 }
1040
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001041
1042
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001043 private void sendUserInfoChangedBroadcast(int userId) {
1044 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1045 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1046 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001047 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001048 }
1049
Amith Yamasani258848d2012-08-10 17:06:33 -07001050 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001051 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001052 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001053 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001054 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1055 if (targetUserInfo == null || targetUserInfo.partial) {
1056 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001057 return null;
1058 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001059
1060 final int callingUserId = UserHandle.getCallingUserId();
1061 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1062 final int targetGroupId = targetUserInfo.profileGroupId;
1063 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1064 && callingGroupId == targetGroupId);
1065 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001066 checkManageUsersPermission("get the icon of a user who is not related");
1067 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001068
1069 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001070 return null;
1071 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001072 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001073 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001074
1075 try {
1076 return ParcelFileDescriptor.open(
1077 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1078 } catch (FileNotFoundException e) {
1079 Log.e(LOG_TAG, "Couldn't find icon file", e);
1080 }
1081 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001082 }
1083
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001084 public void makeInitialized(int userId) {
1085 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001086 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001087 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001088 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001089 userData = mUsers.get(userId);
1090 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001091 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001092 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001093 }
Amith Yamasani12747872015-12-07 14:19:49 -08001094 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1095 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001096 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001097 }
1098 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001099 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001100 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001101 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001102 }
1103
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001104 /**
1105 * If default guest restrictions haven't been initialized yet, add the basic
1106 * restrictions.
1107 */
1108 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001109 synchronized (mGuestRestrictions) {
1110 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001111 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001112 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001113 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1114 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1115 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001116 }
1117 }
1118
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001119 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301120 public Bundle getDefaultGuestRestrictions() {
1121 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001122 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301123 return new Bundle(mGuestRestrictions);
1124 }
1125 }
1126
1127 @Override
1128 public void setDefaultGuestRestrictions(Bundle restrictions) {
1129 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001130 synchronized (mGuestRestrictions) {
1131 mGuestRestrictions.clear();
1132 mGuestRestrictions.putAll(restrictions);
1133 }
1134 synchronized (mPackagesLock) {
1135 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301136 }
1137 }
1138
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001139 /**
1140 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1141 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001142 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001143 @Nullable Bundle global) {
1144 Preconditions.checkNotNull(local);
1145 boolean globalChanged = false;
1146 boolean localChanged;
1147 synchronized (mRestrictionsLock) {
1148 if (global != null) {
1149 // Update global.
1150 globalChanged = !UserRestrictionsUtils.areEqual(
1151 mDevicePolicyGlobalUserRestrictions, global);
1152 if (globalChanged) {
1153 mDevicePolicyGlobalUserRestrictions = global;
1154 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001155 // Remember the global restriction owner userId to be able to make a distinction
1156 // in getUserRestrictionSource on who set local policies.
1157 mGlobalRestrictionOwnerUserId = userId;
1158 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001159 if (mGlobalRestrictionOwnerUserId == userId) {
1160 // When profile owner sets restrictions it passes null global bundle and we
1161 // reset global restriction owner userId.
1162 // This means this user used to have DO, but now the DO is gone and the user
1163 // instead has PO.
1164 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1165 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001166 }
1167 {
1168 // Update local.
1169 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1170 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1171 if (localChanged) {
1172 mDevicePolicyLocalUserRestrictions.put(userId, local);
1173 }
1174 }
1175 }
1176 if (DBG) {
1177 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1178 + " global=" + global + (globalChanged ? " (changed)" : "")
1179 + " local=" + local + (localChanged ? " (changed)" : "")
1180 );
1181 }
1182 // Don't call them within the mRestrictionsLock.
1183 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001184 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001185 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001186 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001187 if (globalChanged) {
1188 writeUserListLP();
1189 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001190 }
1191
1192 synchronized (mRestrictionsLock) {
1193 if (globalChanged) {
1194 applyUserRestrictionsForAllUsersLR();
1195 } else if (localChanged) {
1196 applyUserRestrictionsLR(userId);
1197 }
1198 }
1199 }
1200
Makoto Onuki068c54a2015-10-13 14:34:03 -07001201 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001202 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001203 final Bundle baseRestrictions =
1204 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1205 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1206 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001207
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001208 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1209 // Common case first.
1210 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001211 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001212 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1213 UserRestrictionsUtils.merge(effective, global);
1214 UserRestrictionsUtils.merge(effective, local);
1215
Makoto Onuki068c54a2015-10-13 14:34:03 -07001216 return effective;
1217 }
1218
1219 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001220 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001221 if (DBG) {
1222 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1223 }
1224 mCachedEffectiveUserRestrictions.remove(userId);
1225 }
1226
1227 private Bundle getEffectiveUserRestrictions(int userId) {
1228 synchronized (mRestrictionsLock) {
1229 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1230 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001231 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001232 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1233 }
1234 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001235 }
1236 }
1237
Makoto Onuki068c54a2015-10-13 14:34:03 -07001238 /** @return a specific user restriction that's in effect currently. */
1239 @Override
1240 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001241 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1242 return false;
1243 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001244 Bundle restrictions = getEffectiveUserRestrictions(userId);
1245 return restrictions != null && restrictions.getBoolean(restrictionKey);
1246 }
1247
1248 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001249 * @hide
1250 *
1251 * Returns who set a user restriction on a user.
1252 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1253 * @param restrictionKey the string key representing the restriction
1254 * @param userId the id of the user for whom to retrieve the restrictions.
1255 * @return The source of user restriction. Any combination of
1256 * {@link UserManager#RESTRICTION_NOT_SET},
1257 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1258 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1259 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1260 */
1261 @Override
1262 public int getUserRestrictionSource(String restrictionKey, int userId) {
1263 checkManageUsersPermission("getUserRestrictionSource");
1264 int result = UserManager.RESTRICTION_NOT_SET;
1265
1266 // Shortcut for the most common case
1267 if (!hasUserRestriction(restrictionKey, userId)) {
1268 return result;
1269 }
1270
1271 if (hasBaseUserRestriction(restrictionKey, userId)) {
1272 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1273 }
1274
1275 synchronized(mRestrictionsLock) {
1276 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1277 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1278 && localRestrictions.getBoolean(restrictionKey)) {
1279 // Local restrictions may have been set by device owner the userId of which is
1280 // stored in mGlobalRestrictionOwnerUserId.
1281 if (mGlobalRestrictionOwnerUserId == userId) {
1282 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1283 } else {
1284 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1285 }
1286 }
1287 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1288 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1289 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1290 }
1291 }
1292
1293 return result;
1294 }
1295
1296 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001297 * @return UserRestrictions that are in effect currently. This always returns a new
1298 * {@link Bundle}.
1299 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001300 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001301 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001302 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001303 }
1304
1305 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001306 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1307 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001308 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1309 return false;
1310 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001311 synchronized (mRestrictionsLock) {
1312 Bundle bundle = mBaseUserRestrictions.get(userId);
1313 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1314 }
1315 }
1316
1317 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001318 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001319 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001320 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1321 return;
1322 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001323 synchronized (mRestrictionsLock) {
1324 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1325 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001326 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1327 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001328 newRestrictions.putBoolean(key, value);
1329
Fyodor Kupolov82402752015-10-28 14:54:51 -07001330 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001331 }
1332 }
1333
Makoto Onuki068c54a2015-10-13 14:34:03 -07001334 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001335 * Optionally updating user restrictions, calculate the effective user restrictions and also
1336 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001337 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001338 * @param newRestrictions User restrictions to set.
1339 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001340 * @param userId target user ID.
1341 */
1342 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001343 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001344 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001345
1346 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1347 mAppliedUserRestrictions.get(userId));
1348
1349 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001350 if (newRestrictions != null) {
1351 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001352 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1353
1354 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001355 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1356 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001357
1358 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1359 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001360 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001361 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001362 }
1363
Fyodor Kupolov82402752015-10-28 14:54:51 -07001364 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001365
Makoto Onuki759a7632015-10-28 16:43:10 -07001366 mCachedEffectiveUserRestrictions.put(userId, effective);
1367
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001368 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001369 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001370 debug("Applying user restrictions: userId=" + userId
1371 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001372 }
1373
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001374 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001375 mHandler.post(new Runnable() {
1376 @Override
1377 public void run() {
1378 try {
1379 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1380 } catch (RemoteException e) {
1381 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1382 }
1383 }
1384 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001385 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001386
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001387 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001388
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001389 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001390 }
1391
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001392 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001393 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001394 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1395 // actually, but we still need some kind of synchronization otherwise we might end up
1396 // calling listeners out-of-order, thus "LR".
1397
1398 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1399 return;
1400 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001401
1402 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1403 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1404
1405 mHandler.post(new Runnable() {
1406 @Override
1407 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001408 UserRestrictionsUtils.applyUserRestrictions(
1409 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001410
Makoto Onukid45a4a22015-11-02 17:17:38 -08001411 final UserRestrictionsListener[] listeners;
1412 synchronized (mUserRestrictionsListeners) {
1413 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1414 mUserRestrictionsListeners.toArray(listeners);
1415 }
1416 for (int i = 0; i < listeners.length; i++) {
1417 listeners[i].onUserRestrictionsChanged(userId,
1418 newRestrictionsFinal, prevRestrictionsFinal);
1419 }
1420 }
1421 });
1422 }
1423
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001424 // Package private for the inner class.
1425 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001426 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001427 }
1428
1429 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001430 // Package private for the inner class.
1431 void applyUserRestrictionsForAllUsersLR() {
1432 if (DBG) {
1433 debug("applyUserRestrictionsForAllUsersLR");
1434 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001435 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001436 mCachedEffectiveUserRestrictions.clear();
1437
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001438 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001439 // it on a handler.
1440 final Runnable r = new Runnable() {
1441 @Override
1442 public void run() {
1443 // Then get the list of running users.
1444 final int[] runningUsers;
1445 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001446 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001447 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001448 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001449 return;
1450 }
1451 // Then re-calculate the effective restrictions and apply, only for running users.
1452 // It's okay if a new user has started after the getRunningUserIds() call,
1453 // because we'll do the same thing (re-calculate the restrictions and apply)
1454 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001455 synchronized (mRestrictionsLock) {
1456 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001457 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001458 }
1459 }
1460 }
1461 };
1462 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001463 }
1464
Amith Yamasani258848d2012-08-10 17:06:33 -07001465 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001466 * Check if we've hit the limit of how many users can be created.
1467 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001468 private boolean isUserLimitReached() {
1469 int count;
1470 synchronized (mUsersLock) {
1471 count = getAliveUsersExcludingGuestsCountLU();
1472 }
1473 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001474 }
1475
1476 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001477 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001478 checkManageUsersPermission("check if more managed profiles can be added.");
1479 if (ActivityManager.isLowRamDeviceStatic()) {
1480 return false;
1481 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001482 if (!mContext.getPackageManager().hasSystemFeature(
1483 PackageManager.FEATURE_MANAGED_USERS)) {
1484 return false;
1485 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001486 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001487 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1488 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001489 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001490 return false;
1491 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001492 synchronized(mUsersLock) {
1493 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001494 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001495 return false;
1496 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001497 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1498 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001499 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001500 return usersCountAfterRemoving == 1
1501 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001502 }
1503 }
1504
Fyodor Kupolov82402752015-10-28 14:54:51 -07001505 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001506 int aliveUserCount = 0;
1507 final int totalUserCount = mUsers.size();
1508 // Skip over users being removed
1509 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001510 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001511 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001512 aliveUserCount++;
1513 }
1514 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001515 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001516 }
1517
1518 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001519 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001520 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1521 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1522 * permissions can make certain calls to the UserManager.
1523 *
1524 * @param message used as message if SecurityException is thrown
1525 * @throws SecurityException if the caller does not have enough privilege.
1526 */
1527 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1528 final int uid = Binder.getCallingUid();
1529 if (uid != Process.SYSTEM_UID && uid != 0
1530 && ActivityManager.checkComponentPermission(
1531 Manifest.permission.MANAGE_USERS,
1532 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1533 && ActivityManager.checkComponentPermission(
1534 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1535 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1536 throw new SecurityException(
1537 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1538 + message);
1539 }
1540 }
1541
1542 /**
1543 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001544 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001545 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001546 *
1547 * @param message used as message if SecurityException is thrown
1548 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001549 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001550 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001551 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001552 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001553 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1554 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001555 }
1556
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001557 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001558 * Enforces that only the system UID or root's UID or apps that have the
1559 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1560 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1561 * can make certain calls to the UserManager.
1562 *
1563 * @param message used as message if SecurityException is thrown
1564 * @throws SecurityException if the caller is not system or root
1565 * @see #hasManageOrCreateUsersPermission()
1566 */
1567 private static final void checkManageOrCreateUsersPermission(String message) {
1568 if (!hasManageOrCreateUsersPermission()) {
1569 throw new SecurityException(
1570 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1571 }
1572 }
1573
1574 /**
1575 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1576 * to create user/profiles other than what is allowed for
1577 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1578 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1579 */
1580 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1581 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1582 if (!hasManageOrCreateUsersPermission()) {
1583 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1584 + "permission to create an user with flags: " + creationFlags);
1585 }
1586 } else if (!hasManageUsersPermission()) {
1587 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1588 + " with flags: " + creationFlags);
1589 }
1590 }
1591
1592 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001593 * @return whether the calling UID is system UID or root's UID or the calling app has the
1594 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1595 */
1596 private static final boolean hasManageUsersPermission() {
1597 final int callingUid = Binder.getCallingUid();
1598 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1599 || callingUid == Process.ROOT_UID
1600 || ActivityManager.checkComponentPermission(
1601 android.Manifest.permission.MANAGE_USERS,
1602 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1603 }
1604
1605 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001606 * @return whether the calling UID is system UID or root's UID or the calling app has the
1607 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1608 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1609 */
1610 private static final boolean hasManageOrCreateUsersPermission() {
1611 final int callingUid = Binder.getCallingUid();
1612 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1613 || callingUid == Process.ROOT_UID
1614 || ActivityManager.checkComponentPermission(
1615 android.Manifest.permission.MANAGE_USERS,
1616 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1617 || ActivityManager.checkComponentPermission(
1618 android.Manifest.permission.CREATE_USERS,
1619 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1620 }
1621
1622 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001623 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1624 * UserManager.
1625 *
1626 * @param message used as message if SecurityException is thrown
1627 * @throws SecurityException if the caller is not system or root
1628 */
1629 private static void checkSystemOrRoot(String message) {
1630 final int uid = Binder.getCallingUid();
1631 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1632 throw new SecurityException("Only system may: " + message);
1633 }
1634 }
1635
Fyodor Kupolov82402752015-10-28 14:54:51 -07001636 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001637 try {
1638 File dir = new File(mUsersDir, Integer.toString(info.id));
1639 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001640 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001641 if (!dir.exists()) {
1642 dir.mkdir();
1643 FileUtils.setPermissions(
1644 dir.getPath(),
1645 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1646 -1, -1);
1647 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001648 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001649 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001650 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001651 info.iconPath = file.getAbsolutePath();
1652 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001653 try {
1654 os.close();
1655 } catch (IOException ioe) {
1656 // What the ... !
1657 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001658 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001659 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001660 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001661 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001662 }
1663
Amith Yamasani0b285492011-04-14 17:35:23 -07001664 /**
1665 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1666 * cache it elsewhere.
1667 * @return the array of user ids.
1668 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001669 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001670 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001671 return mUserIds;
1672 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001673 }
1674
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001675 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001676 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001677 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001678 return;
1679 }
1680 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001681 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001682 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001683 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001684 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001685 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001686 int type;
1687 while ((type = parser.next()) != XmlPullParser.START_TAG
1688 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001689 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001690 }
1691
1692 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001693 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001694 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001695 return;
1696 }
1697
Amith Yamasani2a003292012-08-14 18:25:45 -07001698 mNextSerialNumber = -1;
1699 if (parser.getName().equals(TAG_USERS)) {
1700 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1701 if (lastSerialNumber != null) {
1702 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1703 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001704 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1705 if (versionNumber != null) {
1706 mUserVersion = Integer.parseInt(versionNumber);
1707 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001708 }
1709
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1711
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001712 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301713 if (type == XmlPullParser.START_TAG) {
1714 final String name = parser.getName();
1715 if (name.equals(TAG_USER)) {
1716 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001717
Amith Yamasani12747872015-12-07 14:19:49 -08001718 UserData userData = readUserLP(Integer.parseInt(id));
1719
1720 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001721 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001722 mUsers.put(userData.info.id, userData);
1723 if (mNextSerialNumber < 0
1724 || mNextSerialNumber <= userData.info.id) {
1725 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001726 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301727 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001728 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301729 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001730 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1731 && type != XmlPullParser.END_TAG) {
1732 if (type == XmlPullParser.START_TAG) {
1733 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001734 synchronized (mGuestRestrictions) {
1735 UserRestrictionsUtils
1736 .readRestrictions(parser, mGuestRestrictions);
1737 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001738 }
1739 break;
1740 }
1741 }
Makoto Onuki82de3002016-09-30 09:58:15 -07001742 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1743 UserRestrictionsUtils.readRestrictions(parser,
1744 newDevicePolicyGlobalUserRestrictions);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001745 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1746 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1747 if (ownerUserId != null) {
1748 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1749 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001750 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001751 }
1752 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001753 synchronized (mRestrictionsLock) {
1754 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1755 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001756 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001757 upgradeIfNecessaryLP();
1758 } catch (IOException | XmlPullParserException e) {
1759 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001760 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001761 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001762 }
1763 }
1764
Amith Yamasani6f34b412012-10-22 18:19:27 -07001765 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001766 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001767 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001768 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001769 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001770 int userVersion = mUserVersion;
1771 if (userVersion < 1) {
1772 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001773 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1774 if ("Primary".equals(userData.info.name)) {
1775 userData.info.name =
1776 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1777 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001778 }
1779 userVersion = 1;
1780 }
1781
Amith Yamasanibc9625052012-11-15 14:39:18 -08001782 if (userVersion < 2) {
1783 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001784 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1785 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1786 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1787 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001788 }
1789 userVersion = 2;
1790 }
1791
Amith Yamasani350962c2013-08-06 11:18:53 -07001792
Amith Yamasani5e486f52013-08-07 11:06:44 -07001793 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001794 userVersion = 4;
1795 }
1796
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001797 if (userVersion < 5) {
1798 initDefaultGuestRestrictions();
1799 userVersion = 5;
1800 }
1801
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001802 if (userVersion < 6) {
1803 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001804 synchronized (mUsersLock) {
1805 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001806 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001807 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001808 if (!splitSystemUser && userData.info.isRestricted()
1809 && (userData.info.restrictedProfileParentId
1810 == UserInfo.NO_PROFILE_GROUP_ID)) {
1811 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1812 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001813 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001814 }
1815 }
1816 userVersion = 6;
1817 }
1818
Amith Yamasani6f34b412012-10-22 18:19:27 -07001819 if (userVersion < USER_VERSION) {
1820 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1821 + USER_VERSION);
1822 } else {
1823 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824
1825 if (originalVersion < mUserVersion) {
1826 writeUserListLP();
1827 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001828 }
1829 }
1830
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001831 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001832 int flags = UserInfo.FLAG_INITIALIZED;
1833 // In split system user mode, the admin and primary flags are assigned to the first human
1834 // user.
1835 if (!UserManager.isSplitSystemUser()) {
1836 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1837 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001838 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001839 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001840 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001841 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001842 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001843
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001844 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001845 try {
1846 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1847 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1848 for (String userRestriction : defaultFirstUserRestrictions) {
1849 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1850 restrictions.putBoolean(userRestriction, true);
1851 }
1852 }
1853 } catch (Resources.NotFoundException e) {
1854 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1855 }
1856
Makoto Onuki068c54a2015-10-13 14:34:03 -07001857 synchronized (mRestrictionsLock) {
1858 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1859 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001860
Fyodor Kupolov82402752015-10-28 14:54:51 -07001861 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001862 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001863
Amith Yamasani12747872015-12-07 14:19:49 -08001864 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001865 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001866 }
1867
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001868 private String getOwnerName() {
1869 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1870 }
1871
Amith Yamasani12747872015-12-07 14:19:49 -08001872 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001873 if (DBG) {
1874 debug("scheduleWriteUser");
1875 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001876 // No need to wrap it within a lock -- worst case, we'll just post the same message
1877 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001878 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1879 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001880 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1881 }
1882 }
1883
Amith Yamasani12747872015-12-07 14:19:49 -08001884 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001885 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001886 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001887 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001888 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001889 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001890 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001891 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001892 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001893 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001894 userFile.finishWrite(fos);
1895 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001896 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001897 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001898 }
1899 }
1900
1901 /*
Kenny Guy02c89902016-11-15 19:36:38 +00001902 * Writes the user file in this format:
1903 *
1904 * <user flags="20039023" id="0">
1905 * <name>Primary</name>
1906 * </user>
1907 */
1908 @VisibleForTesting
1909 void writeUserLP(UserData userData, OutputStream os)
1910 throws IOException, XmlPullParserException {
1911 // XmlSerializer serializer = XmlUtils.serializerInstance();
1912 final XmlSerializer serializer = new FastXmlSerializer();
1913 serializer.setOutput(os, StandardCharsets.UTF_8.name());
1914 serializer.startDocument(null, true);
1915 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1916
1917 final UserInfo userInfo = userData.info;
1918 serializer.startTag(null, TAG_USER);
1919 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
1920 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
1921 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
1922 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1923 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1924 Long.toString(userInfo.lastLoggedInTime));
1925 if (userInfo.lastLoggedInFingerprint != null) {
1926 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1927 userInfo.lastLoggedInFingerprint);
1928 }
1929 if (userInfo.iconPath != null) {
1930 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1931 }
1932 if (userInfo.partial) {
1933 serializer.attribute(null, ATTR_PARTIAL, "true");
1934 }
1935 if (userInfo.guestToRemove) {
1936 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1937 }
1938 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1939 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1940 Integer.toString(userInfo.profileGroupId));
1941 }
1942 serializer.attribute(null, ATTR_PROFILE_BADGE,
1943 Integer.toString(userInfo.profileBadge));
1944 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1945 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1946 Integer.toString(userInfo.restrictedProfileParentId));
1947 }
1948 // Write seed data
1949 if (userData.persistSeedData) {
1950 if (userData.seedAccountName != null) {
1951 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1952 }
1953 if (userData.seedAccountType != null) {
1954 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1955 }
1956 }
1957 if (userInfo.name != null) {
1958 serializer.startTag(null, TAG_NAME);
1959 serializer.text(userInfo.name);
1960 serializer.endTag(null, TAG_NAME);
1961 }
1962 synchronized (mRestrictionsLock) {
1963 UserRestrictionsUtils.writeRestrictions(serializer,
1964 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1965 UserRestrictionsUtils.writeRestrictions(serializer,
1966 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1967 TAG_DEVICE_POLICY_RESTRICTIONS);
1968 }
1969
1970 if (userData.account != null) {
1971 serializer.startTag(null, TAG_ACCOUNT);
1972 serializer.text(userData.account);
1973 serializer.endTag(null, TAG_ACCOUNT);
1974 }
1975
1976 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1977 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1978 userData.seedAccountOptions.saveToXml(serializer);
1979 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1980 }
1981
1982 serializer.endTag(null, TAG_USER);
1983
1984 serializer.endDocument();
1985 }
1986
1987 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001988 * Writes the user list file in this format:
1989 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001990 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001991 * <user id="0"></user>
1992 * <user id="2"></user>
1993 * </users>
1994 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001995 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001996 if (DBG) {
1997 debug("writeUserList");
1998 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001999 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002000 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002001 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002002 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002003 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2004
2005 // XmlSerializer serializer = XmlUtils.serializerInstance();
2006 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002007 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002008 serializer.startDocument(null, true);
2009 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2010
2011 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002012 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002013 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002014
Adam Lesinskieddeb492014-09-08 17:50:03 -07002015 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002016 synchronized (mGuestRestrictions) {
2017 UserRestrictionsUtils
2018 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2019 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302020 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002021 synchronized (mRestrictionsLock) {
2022 UserRestrictionsUtils.writeRestrictions(serializer,
2023 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
2024 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002025 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
2026 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
2027 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002028 int[] userIdsToWrite;
2029 synchronized (mUsersLock) {
2030 userIdsToWrite = new int[mUsers.size()];
2031 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002032 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002033 userIdsToWrite[i] = user.id;
2034 }
2035 }
2036 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002037 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002038 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002039 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002040 }
2041
2042 serializer.endTag(null, TAG_USERS);
2043
2044 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002045 userListFile.finishWrite(fos);
2046 } catch (Exception e) {
2047 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002048 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002049 }
2050 }
2051
Amith Yamasani12747872015-12-07 14:19:49 -08002052 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002053 FileInputStream fis = null;
2054 try {
2055 AtomicFile userFile =
2056 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2057 fis = userFile.openRead();
2058 return readUserLP(id, fis);
2059 } catch (IOException ioe) {
2060 Slog.e(LOG_TAG, "Error reading user list");
2061 } catch (XmlPullParserException pe) {
2062 Slog.e(LOG_TAG, "Error reading user list");
2063 } finally {
2064 IoUtils.closeQuietly(fis);
2065 }
2066 return null;
2067 }
2068
2069 @VisibleForTesting
2070 UserData readUserLP(int id, InputStream is) throws IOException,
2071 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002072 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002073 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002074 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002075 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002076 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002077 long creationTime = 0L;
2078 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002079 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002080 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002081 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002082 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002083 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002084 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002085 boolean persistSeedData = false;
2086 String seedAccountName = null;
2087 String seedAccountType = null;
2088 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002089 Bundle baseRestrictions = new Bundle();
2090 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002091
Kenny Guy02c89902016-11-15 19:36:38 +00002092 XmlPullParser parser = Xml.newPullParser();
2093 parser.setInput(is, StandardCharsets.UTF_8.name());
2094 int type;
2095 while ((type = parser.next()) != XmlPullParser.START_TAG
2096 && type != XmlPullParser.END_DOCUMENT) {
2097 // Skip
2098 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002099
Kenny Guy02c89902016-11-15 19:36:38 +00002100 if (type != XmlPullParser.START_TAG) {
2101 Slog.e(LOG_TAG, "Unable to read user " + id);
2102 return null;
2103 }
2104
2105 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2106 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2107 if (storedId != id) {
2108 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002109 return null;
2110 }
Kenny Guy02c89902016-11-15 19:36:38 +00002111 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2112 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2113 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2114 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2115 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2116 lastLoggedInFingerprint = parser.getAttributeValue(null,
2117 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2118 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2119 UserInfo.NO_PROFILE_GROUP_ID);
2120 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2121 restrictedProfileParentId = readIntAttribute(parser,
2122 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2123 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2124 if ("true".equals(valueString)) {
2125 partial = true;
2126 }
2127 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2128 if ("true".equals(valueString)) {
2129 guestToRemove = true;
2130 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002131
Kenny Guy02c89902016-11-15 19:36:38 +00002132 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2133 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2134 if (seedAccountName != null || seedAccountType != null) {
2135 persistSeedData = true;
2136 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002137
Kenny Guy02c89902016-11-15 19:36:38 +00002138 int outerDepth = parser.getDepth();
2139 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2140 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2141 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2142 continue;
2143 }
2144 String tag = parser.getName();
2145 if (TAG_NAME.equals(tag)) {
2146 type = parser.next();
2147 if (type == XmlPullParser.TEXT) {
2148 name = parser.getText();
2149 }
2150 } else if (TAG_RESTRICTIONS.equals(tag)) {
2151 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2152 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2153 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
2154 } else if (TAG_ACCOUNT.equals(tag)) {
2155 type = parser.next();
2156 if (type == XmlPullParser.TEXT) {
2157 account = parser.getText();
2158 }
2159 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2160 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002161 persistSeedData = true;
2162 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002163 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002164 }
Kenny Guy02c89902016-11-15 19:36:38 +00002165
2166 // Create the UserInfo object that gets passed around
2167 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2168 userInfo.serialNumber = serialNumber;
2169 userInfo.creationTime = creationTime;
2170 userInfo.lastLoggedInTime = lastLoggedInTime;
2171 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2172 userInfo.partial = partial;
2173 userInfo.guestToRemove = guestToRemove;
2174 userInfo.profileGroupId = profileGroupId;
2175 userInfo.profileBadge = profileBadge;
2176 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2177
2178 // Create the UserData object that's internal to this class
2179 UserData userData = new UserData();
2180 userData.info = userInfo;
2181 userData.account = account;
2182 userData.seedAccountName = seedAccountName;
2183 userData.seedAccountType = seedAccountType;
2184 userData.persistSeedData = persistSeedData;
2185 userData.seedAccountOptions = seedAccountOptions;
2186
2187 synchronized (mRestrictionsLock) {
2188 mBaseUserRestrictions.put(id, baseRestrictions);
2189 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2190 }
2191 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002192 }
2193
Amith Yamasani920ace02012-09-20 22:15:37 -07002194 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2195 String valueString = parser.getAttributeValue(null, attr);
2196 if (valueString == null) return defaultValue;
2197 try {
2198 return Integer.parseInt(valueString);
2199 } catch (NumberFormatException nfe) {
2200 return defaultValue;
2201 }
2202 }
2203
2204 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2205 String valueString = parser.getAttributeValue(null, attr);
2206 if (valueString == null) return defaultValue;
2207 try {
2208 return Long.parseLong(valueString);
2209 } catch (NumberFormatException nfe) {
2210 return defaultValue;
2211 }
2212 }
2213
Amith Yamasanib82add22013-07-09 11:24:44 -07002214 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002215 * Removes the app restrictions file for a specific package and user id, if it exists.
2216 */
2217 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2218 synchronized (mPackagesLock) {
2219 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002220 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002221 if (resFile.exists()) {
2222 resFile.delete();
2223 }
2224 }
2225 }
2226
Kenny Guya52dc3e2014-02-11 15:33:14 +00002227 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002228 public UserInfo createProfileForUser(String name, int flags, int userId,
2229 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002230 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002231 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002232 }
2233
Amith Yamasani258848d2012-08-10 17:06:33 -07002234 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002235 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2236 String[] disallowedPackages) {
2237 checkManageOrCreateUsersPermission(flags);
2238 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2239 }
2240
2241 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002242 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002243 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002244 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002245 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002246
Jessica Hummelbe81c802014-04-22 15:49:22 +01002247 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002248 return createUserInternal(name, flags, parentId, null);
2249 }
2250
2251 private UserInfo createUserInternal(String name, int flags, int parentId,
2252 String[] disallowedPackages) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002253 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002254 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2255 return null;
2256 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002257 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2258 }
2259
2260 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2261 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002262 DeviceStorageMonitorInternal dsm = LocalServices
2263 .getService(DeviceStorageMonitorInternal.class);
2264 if (dsm.isMemoryLow()) {
2265 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2266 return null;
2267 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002268 if (ActivityManager.isLowRamDeviceStatic()) {
2269 return null;
2270 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002271 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002272 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002273 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002274 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002275 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002276 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002277 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002278 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002279 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002280 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002281 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002282 if (parentId != UserHandle.USER_NULL) {
2283 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002284 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002285 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002286 if (parent == null) return null;
2287 }
2288 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2289 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2290 return null;
2291 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002292 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2293 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002294 // been reached, cannot add a user.
2295 return null;
2296 }
2297 // If we're adding a guest and there already exists one, bail.
2298 if (isGuest && findCurrentGuestUser() != null) {
2299 return null;
2300 }
2301 // In legacy mode, restricted profile's parent can only be the owner user
2302 if (isRestricted && !UserManager.isSplitSystemUser()
2303 && (parentId != UserHandle.USER_SYSTEM)) {
2304 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2305 return null;
2306 }
2307 if (isRestricted && UserManager.isSplitSystemUser()) {
2308 if (parent == null) {
2309 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2310 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002311 return null;
2312 }
Amith Yamasani12747872015-12-07 14:19:49 -08002313 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002314 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2315 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002316 return null;
2317 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002318 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002319 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2320 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002321 Log.e(LOG_TAG,
2322 "Ephemeral users are supported on split-system-user systems only.");
2323 return null;
2324 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002325 // In split system user mode, we assign the first human user the primary flag.
2326 // And if there is no device owner, we also assign the admin flag to primary user.
2327 if (UserManager.isSplitSystemUser()
2328 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2329 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002330 synchronized (mUsersLock) {
2331 if (!mIsDeviceManaged) {
2332 flags |= UserInfo.FLAG_ADMIN;
2333 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002334 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002335 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002336
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002337 userId = getNextAvailableId();
2338 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002339 boolean ephemeralGuests = Resources.getSystem()
2340 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002341
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002342 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002343 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2344 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2345 || (parent != null && parent.info.isEphemeral())) {
2346 flags |= UserInfo.FLAG_EPHEMERAL;
2347 }
2348
2349 userInfo = new UserInfo(userId, name, null, flags);
2350 userInfo.serialNumber = mNextSerialNumber++;
2351 long now = System.currentTimeMillis();
2352 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2353 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002354 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002355 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2356 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2357 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002358 userData = new UserData();
2359 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002360 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002361 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002362 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002363 writeUserListLP();
2364 if (parent != null) {
2365 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002366 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2367 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002368 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002369 }
Amith Yamasani12747872015-12-07 14:19:49 -08002370 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002371 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002372 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2373 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002374 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002375 }
Amith Yamasani12747872015-12-07 14:19:49 -08002376 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002377 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002378 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002379 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002380 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002381 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002382 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002383 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002384 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002385 userInfo.partial = false;
2386 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002387 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002388 }
2389 updateUserIds();
2390 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002391 if (isGuest) {
2392 synchronized (mGuestRestrictions) {
2393 restrictions.putAll(mGuestRestrictions);
2394 }
2395 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002396 synchronized (mRestrictionsLock) {
2397 mBaseUserRestrictions.append(userId, restrictions);
2398 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002399 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002400 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2401 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2402 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2403 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002404 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002405 } finally {
2406 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002407 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002408 return userInfo;
2409 }
2410
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002411 @VisibleForTesting
2412 UserData putUserInfo(UserInfo userInfo) {
2413 final UserData userData = new UserData();
2414 userData.info = userInfo;
2415 synchronized (mUsers) {
2416 mUsers.put(userInfo.id, userData);
2417 }
2418 return userData;
2419 }
2420
2421 @VisibleForTesting
2422 void removeUserInfo(int userId) {
2423 synchronized (mUsers) {
2424 mUsers.remove(userId);
2425 }
2426 }
2427
Amith Yamasani0b285492011-04-14 17:35:23 -07002428 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002429 * @hide
2430 */
Amith Yamasani12747872015-12-07 14:19:49 -08002431 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002432 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002433 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002434 final UserInfo user = createProfileForUser(
2435 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002436 if (user == null) {
2437 return null;
2438 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002439 long identity = Binder.clearCallingIdentity();
2440 try {
2441 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2442 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2443 // the putIntForUser() will fail.
2444 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2445 android.provider.Settings.Secure.LOCATION_MODE,
2446 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2447 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2448 } finally {
2449 Binder.restoreCallingIdentity(identity);
2450 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002451 return user;
2452 }
2453
2454 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002455 * Find the current guest user. If the Guest user is partial,
2456 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002457 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002458 private UserInfo findCurrentGuestUser() {
2459 synchronized (mUsersLock) {
2460 final int size = mUsers.size();
2461 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002462 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002463 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2464 return user;
2465 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002466 }
2467 }
2468 return null;
2469 }
2470
2471 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002472 * Mark this guest user for deletion to allow us to create another guest
2473 * and switch to that user before actually removing this guest.
2474 * @param userHandle the userid of the current guest
2475 * @return whether the user could be marked for deletion
2476 */
Amith Yamasani12747872015-12-07 14:19:49 -08002477 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002478 public boolean markGuestForDeletion(int userHandle) {
2479 checkManageUsersPermission("Only the system can remove users");
2480 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2481 UserManager.DISALLOW_REMOVE_USER, false)) {
2482 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2483 return false;
2484 }
2485
2486 long ident = Binder.clearCallingIdentity();
2487 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002488 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002489 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002490 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002491 userData = mUsers.get(userHandle);
2492 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002493 return false;
2494 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002495 }
Amith Yamasani12747872015-12-07 14:19:49 -08002496 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002497 return false;
2498 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002499 // We set this to a guest user that is to be removed. This is a temporary state
2500 // where we are allowed to add new Guest users, even if this one is still not
2501 // removed. This user will still show up in getUserInfo() calls.
2502 // If we don't get around to removing this Guest user, it will be purged on next
2503 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002504 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002505 // Mark it as disabled, so that it isn't returned any more when
2506 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002507 userData.info.flags |= UserInfo.FLAG_DISABLED;
2508 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002509 }
2510 } finally {
2511 Binder.restoreCallingIdentity(ident);
2512 }
2513 return true;
2514 }
2515
2516 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002517 * Removes a user and all data directories created for that user. This method should be called
2518 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002519 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002520 */
Amith Yamasani12747872015-12-07 14:19:49 -08002521 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002522 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002523 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002524 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002525 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2526 UserManager.DISALLOW_REMOVE_USER, false)) {
2527 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2528 return false;
2529 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002530 return removeUserUnchecked(userHandle);
2531 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002532
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002533 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002534 long ident = Binder.clearCallingIdentity();
2535 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002536 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002537 int currentUser = ActivityManager.getCurrentUser();
2538 if (currentUser == userHandle) {
2539 Log.w(LOG_TAG, "Current user cannot be removed");
2540 return false;
2541 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002542 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002543 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002544 userData = mUsers.get(userHandle);
2545 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002546 return false;
2547 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002548
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002549 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002550 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002551
Kenny Guyee58b4f2014-05-23 15:19:53 +01002552 try {
2553 mAppOpsService.removeUser(userHandle);
2554 } catch (RemoteException e) {
2555 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2556 }
2557 // Set this to a partially created user, so that the user will be purged
2558 // on next startup, in case the runtime stops now before stopping and
2559 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002560 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002561 // Mark it as disabled, so that it isn't returned any more when
2562 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002563 userData.info.flags |= UserInfo.FLAG_DISABLED;
2564 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002565 }
2566
Amith Yamasani12747872015-12-07 14:19:49 -08002567 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2568 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002569 // Send broadcast to notify system that the user removed was a
2570 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002571 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002572 }
2573
2574 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2575 int res;
2576 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002577 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002578 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002579 @Override
2580 public void userStopped(int userId) {
2581 finishRemoveUser(userId);
2582 }
2583 @Override
2584 public void userStopAborted(int userId) {
2585 }
2586 });
2587 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002588 return false;
2589 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002590 return res == ActivityManager.USER_OP_SUCCESS;
2591 } finally {
2592 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002593 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002594 }
2595
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002596 @VisibleForTesting
2597 void addRemovingUserIdLocked(int userId) {
2598 // We remember deleted user IDs to prevent them from being
2599 // reused during the current boot; they can still be reused
2600 // after a reboot or recycling of userIds.
2601 mRemovingUserIds.put(userId, true);
2602 mRecentlyRemovedIds.add(userId);
2603 // Keep LRU queue of recently removed IDs for recycling
2604 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2605 mRecentlyRemovedIds.removeFirst();
2606 }
2607 }
2608
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002609 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002610 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002611 // Let other services shutdown any activity and clean up their state before completely
2612 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002613 long ident = Binder.clearCallingIdentity();
2614 try {
2615 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2616 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002617 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2618 android.Manifest.permission.MANAGE_USERS,
2619
2620 new BroadcastReceiver() {
2621 @Override
2622 public void onReceive(Context context, Intent intent) {
2623 if (DBG) {
2624 Slog.i(LOG_TAG,
2625 "USER_REMOVED broadcast sent, cleaning up user data "
2626 + userHandle);
2627 }
2628 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002629 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002630 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002631 // Clean up any ActivityManager state
2632 LocalServices.getService(ActivityManagerInternal.class)
2633 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002634 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002635 }
2636 }.start();
2637 }
2638 },
2639
2640 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002641 } finally {
2642 Binder.restoreCallingIdentity(ident);
2643 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002644 }
2645
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002646 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002647 try {
2648 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2649 } catch (IllegalStateException e) {
2650 // This may be simply because the user was partially created.
2651 Slog.i(LOG_TAG,
2652 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2653 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002654
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002655 // Cleanup gatekeeper secure user id
2656 try {
2657 final IGateKeeperService gk = GateKeeper.getService();
2658 if (gk != null) {
2659 gk.clearSecureUserId(userHandle);
2660 }
2661 } catch (Exception ex) {
2662 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2663 }
2664
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002665 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002666 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002667
2668 // Clean up all data before removing metadata
2669 mPm.destroyUserData(userHandle,
2670 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2671
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002672 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002673 synchronized (mUsersLock) {
2674 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002675 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002676 }
2677 synchronized (mUserStates) {
2678 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002679 }
2680 synchronized (mRestrictionsLock) {
2681 mBaseUserRestrictions.remove(userHandle);
2682 mAppliedUserRestrictions.remove(userHandle);
2683 mCachedEffectiveUserRestrictions.remove(userHandle);
2684 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002685 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002686 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002687 synchronized (mPackagesLock) {
2688 writeUserListLP();
2689 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002690 // Remove user file
2691 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2692 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002693 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002694 if (RELEASE_DELETED_USER_ID) {
2695 synchronized (mUsers) {
2696 mRemovingUserIds.delete(userHandle);
2697 }
2698 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002699 }
2700
Kenny Guyf8d3a232014-05-15 16:09:52 +01002701 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002702 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002703 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2704 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002705 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002706 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002707 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002708 }
2709
Amith Yamasani2a003292012-08-14 18:25:45 -07002710 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002711 public Bundle getApplicationRestrictions(String packageName) {
2712 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2713 }
2714
2715 @Override
2716 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002717 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002718 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002719 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002720 }
2721 synchronized (mPackagesLock) {
2722 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002723 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002724 }
2725 }
2726
2727 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002728 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002729 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002730 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002731 if (restrictions != null) {
2732 restrictions.setDefusable(true);
2733 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002734 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002735 if (restrictions == null || restrictions.isEmpty()) {
2736 cleanAppRestrictionsForPackage(packageName, userId);
2737 } else {
2738 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002739 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002740 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002741 }
Robin Lee66e5d962014-04-09 16:44:21 +01002742
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002743 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2744 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2745 changeIntent.setPackage(packageName);
2746 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2747 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002748 }
2749
2750 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002751 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002752 try {
2753 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002754 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002755 } catch (NameNotFoundException nnfe) {
2756 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002757 } finally {
2758 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002759 }
2760 }
2761
Fyodor Kupolov82402752015-10-28 14:54:51 -07002762 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002763 AtomicFile restrictionsFile =
2764 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2765 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002766 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002767 }
2768
2769 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002770 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002771 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002772 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002773 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002774 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002775 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002776
2777 FileInputStream fis = null;
2778 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002779 fis = restrictionsFile.openRead();
2780 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002781 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002782 XmlUtils.nextElement(parser);
2783 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002784 Slog.e(LOG_TAG, "Unable to read restrictions file "
2785 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002786 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002787 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002788 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2789 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002790 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002791 } catch (IOException|XmlPullParserException e) {
2792 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002793 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002794 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002795 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002796 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002797 }
2798
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002799 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2800 XmlPullParser parser) throws XmlPullParserException, IOException {
2801 int type = parser.getEventType();
2802 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2803 String key = parser.getAttributeValue(null, ATTR_KEY);
2804 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2805 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2806 if (multiple != null) {
2807 values.clear();
2808 int count = Integer.parseInt(multiple);
2809 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2810 if (type == XmlPullParser.START_TAG
2811 && parser.getName().equals(TAG_VALUE)) {
2812 values.add(parser.nextText().trim());
2813 count--;
2814 }
2815 }
2816 String [] valueStrings = new String[values.size()];
2817 values.toArray(valueStrings);
2818 restrictions.putStringArray(key, valueStrings);
2819 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2820 restrictions.putBundle(key, readBundleEntry(parser, values));
2821 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2822 final int outerDepth = parser.getDepth();
2823 ArrayList<Bundle> bundleList = new ArrayList<>();
2824 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2825 Bundle childBundle = readBundleEntry(parser, values);
2826 bundleList.add(childBundle);
2827 }
2828 restrictions.putParcelableArray(key,
2829 bundleList.toArray(new Bundle[bundleList.size()]));
2830 } else {
2831 String value = parser.nextText().trim();
2832 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2833 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2834 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2835 restrictions.putInt(key, Integer.parseInt(value));
2836 } else {
2837 restrictions.putString(key, value);
2838 }
2839 }
2840 }
2841 }
2842
2843 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2844 throws IOException, XmlPullParserException {
2845 Bundle childBundle = new Bundle();
2846 final int outerDepth = parser.getDepth();
2847 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2848 readEntry(childBundle, values, parser);
2849 }
2850 return childBundle;
2851 }
2852
Fyodor Kupolov82402752015-10-28 14:54:51 -07002853 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002854 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002855 AtomicFile restrictionsFile = new AtomicFile(
2856 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002857 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002858 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002859 }
2860
2861 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002862 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002863 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002864 try {
2865 fos = restrictionsFile.startWrite();
2866 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2867
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002868 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002869 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002870 serializer.startDocument(null, true);
2871 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2872
2873 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002874 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002875 serializer.endTag(null, TAG_RESTRICTIONS);
2876
2877 serializer.endDocument();
2878 restrictionsFile.finishWrite(fos);
2879 } catch (Exception e) {
2880 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002881 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2882 }
2883 }
2884
2885 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2886 throws IOException {
2887 for (String key : restrictions.keySet()) {
2888 Object value = restrictions.get(key);
2889 serializer.startTag(null, TAG_ENTRY);
2890 serializer.attribute(null, ATTR_KEY, key);
2891
2892 if (value instanceof Boolean) {
2893 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2894 serializer.text(value.toString());
2895 } else if (value instanceof Integer) {
2896 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2897 serializer.text(value.toString());
2898 } else if (value == null || value instanceof String) {
2899 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2900 serializer.text(value != null ? (String) value : "");
2901 } else if (value instanceof Bundle) {
2902 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2903 writeBundle((Bundle) value, serializer);
2904 } else if (value instanceof Parcelable[]) {
2905 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2906 Parcelable[] array = (Parcelable[]) value;
2907 for (Parcelable parcelable : array) {
2908 if (!(parcelable instanceof Bundle)) {
2909 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2910 }
2911 serializer.startTag(null, TAG_ENTRY);
2912 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2913 writeBundle((Bundle) parcelable, serializer);
2914 serializer.endTag(null, TAG_ENTRY);
2915 }
2916 } else {
2917 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2918 String[] values = (String[]) value;
2919 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2920 for (String choice : values) {
2921 serializer.startTag(null, TAG_VALUE);
2922 serializer.text(choice != null ? choice : "");
2923 serializer.endTag(null, TAG_VALUE);
2924 }
2925 }
2926 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002927 }
2928 }
2929
2930 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002931 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002932 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002933 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002934 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002935 }
2936 }
2937
2938 @Override
2939 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002940 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002941 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002942 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002943 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002944 }
2945 // Not found
2946 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002947 }
2948 }
2949
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002950 @Override
2951 public long getUserCreationTime(int userHandle) {
2952 int callingUserId = UserHandle.getCallingUserId();
2953 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002954 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002955 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002956 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002957 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002958 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002959 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002960 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002961 }
2962 }
2963 }
2964 if (userInfo == null) {
2965 throw new SecurityException("userHandle can only be the calling user or a managed "
2966 + "profile associated with this user");
2967 }
2968 return userInfo.creationTime;
2969 }
2970
Amith Yamasani0b285492011-04-14 17:35:23 -07002971 /**
2972 * Caches the list of user ids in an array, adjusting the array size when necessary.
2973 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002974 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002975 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002976 synchronized (mUsersLock) {
2977 final int userSize = mUsers.size();
2978 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002979 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002980 num++;
2981 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002982 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002983 final int[] newUsers = new int[num];
2984 int n = 0;
2985 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002986 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002987 newUsers[n++] = mUsers.keyAt(i);
2988 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002989 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002990 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002991 }
2992 }
2993
2994 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002995 * Called right before a user is started. This gives us a chance to prepare
2996 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002997 */
2998 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002999 UserInfo userInfo = getUserInfo(userId);
3000 if (userInfo == null) {
3001 return;
3002 }
3003 final int userSerial = userInfo.serialNumber;
3004 // Migrate only if build fingerprints mismatch
3005 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003006 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003007 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003008
3009 if (userId != UserHandle.USER_SYSTEM) {
3010 synchronized (mRestrictionsLock) {
3011 applyUserRestrictionsLR(userId);
3012 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003013 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003014
3015 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003016 }
3017
3018 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003019 * Called right before a user is unlocked. This gives us a chance to prepare
3020 * app storage.
3021 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003022 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003023 UserInfo userInfo = getUserInfo(userId);
3024 if (userInfo == null) {
3025 return;
3026 }
3027 final int userSerial = userInfo.serialNumber;
3028 // Migrate only if build fingerprints mismatch
3029 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003030 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003031 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003032 }
3033
3034 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003035 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003036 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003037 * @param userId the user that was just foregrounded
3038 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003039 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003040 UserData userData = getUserDataNoChecks(userId);
3041 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003042 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3043 return;
3044 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003045
3046 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003047 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003048 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003049 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003050 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3051 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003052 }
3053
Amith Yamasanieb437d42016-04-29 09:31:25 -07003054 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07003055 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07003056 String demoLauncher =
3057 mContext.getResources().getString(
3058 com.android.internal.R.string.config_demoModeLauncherComponent);
3059 if (!TextUtils.isEmpty(demoLauncher)) {
3060 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07003061 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00003062 try {
3063 final IPackageManager iPm = AppGlobals.getPackageManager();
3064 iPm.setComponentEnabledSetting(componentToEnable,
3065 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3066 /* userId= */ userId);
3067 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3068 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3069 /* userId= */ userId, null);
3070 } catch (RemoteException re) {
3071 // Internal, shouldn't happen
3072 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003073 }
3074 }
3075 }
3076
Amith Yamasani920ace02012-09-20 22:15:37 -07003077 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003078 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003079 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003080 @VisibleForTesting
3081 int getNextAvailableId() {
3082 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003083 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003084 nextId = scanNextAvailableIdLocked();
3085 if (nextId >= 0) {
3086 return nextId;
3087 }
3088 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3089 // except most recently removed
3090 if (mRemovingUserIds.size() > 0) {
3091 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3092 mRemovingUserIds.clear();
3093 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3094 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003095 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003096 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003097 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003098 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003099 if (nextId < 0) {
3100 throw new IllegalStateException("No user id available!");
3101 }
3102 return nextId;
3103 }
3104
3105 private int scanNextAvailableIdLocked() {
3106 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3107 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3108 return i;
3109 }
3110 }
3111 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003112 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003113
Amith Yamasanifc95e702013-09-26 13:20:17 -07003114 private String packageToRestrictionsFileName(String packageName) {
3115 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3116 }
3117
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003118 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003119 * Enforce that serial number stored in user directory inode matches the
3120 * given expected value. Gracefully sets the serial number if currently
3121 * undefined.
3122 *
3123 * @throws IOException when problem extracting serial number, or serial
3124 * number is mismatched.
3125 */
3126 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003127 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3128 // When we're emulating FBE, the directory may have been chmod
3129 // 000'ed, meaning we can't read the serial number to enforce it;
3130 // instead of destroying the user, just log a warning.
3131 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3132 return;
3133 }
3134
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003135 final int foundSerial = getSerialNumber(file);
3136 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3137
3138 if (foundSerial == -1) {
3139 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3140 try {
3141 setSerialNumber(file, serialNumber);
3142 } catch (IOException e) {
3143 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3144 }
3145
3146 } else if (foundSerial != serialNumber) {
3147 throw new IOException("Found serial number " + foundSerial
3148 + " doesn't match expected " + serialNumber);
3149 }
3150 }
3151
3152 /**
3153 * Set serial number stored in user directory inode.
3154 *
3155 * @throws IOException if serial number was already set
3156 */
3157 private static void setSerialNumber(File file, int serialNumber)
3158 throws IOException {
3159 try {
3160 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3161 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3162 } catch (ErrnoException e) {
3163 throw e.rethrowAsIOException();
3164 }
3165 }
3166
3167 /**
3168 * Return serial number stored in user directory inode.
3169 *
3170 * @return parsed serial number, or -1 if not set
3171 */
3172 private static int getSerialNumber(File file) throws IOException {
3173 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003174 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3175 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003176 try {
3177 return Integer.parseInt(serial);
3178 } catch (NumberFormatException e) {
3179 throw new IOException("Bad serial number: " + serial);
3180 }
3181 } catch (ErrnoException e) {
3182 if (e.errno == OsConstants.ENODATA) {
3183 return -1;
3184 } else {
3185 throw e.rethrowAsIOException();
3186 }
3187 }
3188 }
3189
Amith Yamasani920ace02012-09-20 22:15:37 -07003190 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003191 public void setSeedAccountData(int userId, String accountName, String accountType,
3192 PersistableBundle accountOptions, boolean persist) {
3193 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3194 synchronized (mPackagesLock) {
3195 final UserData userData;
3196 synchronized (mUsersLock) {
3197 userData = getUserDataLU(userId);
3198 if (userData == null) {
3199 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3200 return;
3201 }
3202 userData.seedAccountName = accountName;
3203 userData.seedAccountType = accountType;
3204 userData.seedAccountOptions = accountOptions;
3205 userData.persistSeedData = persist;
3206 }
3207 if (persist) {
3208 writeUserLP(userData);
3209 }
3210 }
3211 }
3212
3213 @Override
3214 public String getSeedAccountName() throws RemoteException {
3215 checkManageUsersPermission("Cannot get seed account information");
3216 synchronized (mUsersLock) {
3217 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3218 return userData.seedAccountName;
3219 }
3220 }
3221
3222 @Override
3223 public String getSeedAccountType() throws RemoteException {
3224 checkManageUsersPermission("Cannot get seed account information");
3225 synchronized (mUsersLock) {
3226 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3227 return userData.seedAccountType;
3228 }
3229 }
3230
3231 @Override
3232 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3233 checkManageUsersPermission("Cannot get seed account information");
3234 synchronized (mUsersLock) {
3235 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3236 return userData.seedAccountOptions;
3237 }
3238 }
3239
3240 @Override
3241 public void clearSeedAccountData() throws RemoteException {
3242 checkManageUsersPermission("Cannot clear seed account information");
3243 synchronized (mPackagesLock) {
3244 UserData userData;
3245 synchronized (mUsersLock) {
3246 userData = getUserDataLU(UserHandle.getCallingUserId());
3247 if (userData == null) return;
3248 userData.clearSeedAccountData();
3249 }
3250 writeUserLP(userData);
3251 }
3252 }
3253
3254 @Override
3255 public boolean someUserHasSeedAccount(String accountName, String accountType)
3256 throws RemoteException {
3257 checkManageUsersPermission("Cannot check seed account information");
3258 synchronized (mUsersLock) {
3259 final int userSize = mUsers.size();
3260 for (int i = 0; i < userSize; i++) {
3261 final UserData data = mUsers.valueAt(i);
3262 if (data.info.isInitialized()) continue;
3263 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3264 continue;
3265 }
3266 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3267 continue;
3268 }
3269 return true;
3270 }
3271 }
3272 return false;
3273 }
3274
3275 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003276 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003277 FileDescriptor err, String[] args, ShellCallback callback,
3278 ResultReceiver resultReceiver) {
3279 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003280 }
3281
3282 int onShellCommand(Shell shell, String cmd) {
3283 if (cmd == null) {
3284 return shell.handleDefaultCommands(cmd);
3285 }
3286
3287 final PrintWriter pw = shell.getOutPrintWriter();
3288 try {
3289 switch(cmd) {
3290 case "list":
3291 return runList(pw);
3292 }
3293 } catch (RemoteException e) {
3294 pw.println("Remote exception: " + e);
3295 }
3296 return -1;
3297 }
3298
3299 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003300 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003301 final List<UserInfo> users = getUsers(false);
3302 if (users == null) {
3303 pw.println("Error: couldn't get users");
3304 return 1;
3305 } else {
3306 pw.println("Users:");
3307 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003308 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003309 pw.println("\t" + users.get(i).toString() + running);
3310 }
3311 return 0;
3312 }
3313 }
3314
3315 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003316 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3317 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3318 != PackageManager.PERMISSION_GRANTED) {
3319 pw.println("Permission Denial: can't dump UserManager from from pid="
3320 + Binder.getCallingPid()
3321 + ", uid=" + Binder.getCallingUid()
3322 + " without permission "
3323 + android.Manifest.permission.DUMP);
3324 return;
3325 }
3326
3327 long now = System.currentTimeMillis();
3328 StringBuilder sb = new StringBuilder();
3329 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003330 synchronized (mUsersLock) {
3331 pw.println("Users:");
3332 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003333 UserData userData = mUsers.valueAt(i);
3334 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003335 continue;
3336 }
Amith Yamasani12747872015-12-07 14:19:49 -08003337 UserInfo userInfo = userData.info;
3338 final int userId = userInfo.id;
3339 pw.print(" "); pw.print(userInfo);
3340 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003341 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003342 pw.print(" <removing> ");
3343 }
Amith Yamasani12747872015-12-07 14:19:49 -08003344 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003345 pw.print(" <partial>");
3346 }
3347 pw.println();
3348 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003349 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003350 pw.println("<unknown>");
3351 } else {
3352 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003353 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003354 sb.append(" ago");
3355 pw.println(sb);
3356 }
3357 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003358 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003359 pw.println("<unknown>");
3360 } else {
3361 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003362 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003363 sb.append(" ago");
3364 pw.println(sb);
3365 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003366 pw.print(" Last logged in fingerprint: ");
3367 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003368 pw.print(" Has profile owner: ");
3369 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003370 pw.println(" Restrictions:");
3371 synchronized (mRestrictionsLock) {
3372 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003373 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003374 pw.println(" Device policy local restrictions:");
3375 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003376 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003377 pw.println(" Effective restrictions:");
3378 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003379 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003380 }
Amith Yamasani12747872015-12-07 14:19:49 -08003381
3382 if (userData.account != null) {
3383 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003384 pw.println();
3385 }
Amith Yamasani12747872015-12-07 14:19:49 -08003386
3387 if (userData.seedAccountName != null) {
3388 pw.print(" Seed account name: " + userData.seedAccountName);
3389 pw.println();
3390 if (userData.seedAccountType != null) {
3391 pw.print(" account type: " + userData.seedAccountType);
3392 pw.println();
3393 }
3394 if (userData.seedAccountOptions != null) {
3395 pw.print(" account options exist");
3396 pw.println();
3397 }
3398 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003399 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003400 }
Amith Yamasani12747872015-12-07 14:19:49 -08003401 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003402 pw.println(" Device policy global restrictions:");
3403 synchronized (mRestrictionsLock) {
3404 UserRestrictionsUtils
3405 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3406 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003407 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003408 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3409 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003410 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003411 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003412 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003413 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003414 synchronized (mUsersLock) {
3415 pw.println();
3416 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003417 if (mRemovingUserIds.size() > 0) {
3418 pw.println();
3419 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3420 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003421 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003422 synchronized (mUserStates) {
3423 pw.println(" Started users state: " + mUserStates);
3424 }
Amith Yamasani12747872015-12-07 14:19:49 -08003425 // Dump some capabilities
3426 pw.println();
3427 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3428 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003429 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3430 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003431 }
3432 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003433
3434 final class MainHandler extends Handler {
3435
3436 @Override
3437 public void handleMessage(Message msg) {
3438 switch (msg.what) {
3439 case WRITE_USER_MSG:
3440 removeMessages(WRITE_USER_MSG, msg.obj);
3441 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003442 int userId = ((UserData) msg.obj).info.id;
3443 UserData userData = getUserDataNoChecks(userId);
3444 if (userData != null) {
3445 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003446 }
3447 }
3448 }
3449 }
3450 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003451
3452 /**
3453 * @param userId
3454 * @return whether the user has been initialized yet
3455 */
3456 boolean isInitialized(int userId) {
3457 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3458 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003459
3460 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003461 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003462 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3463 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003464 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003465 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003466 }
3467
3468 @Override
3469 public Bundle getBaseUserRestrictions(int userId) {
3470 synchronized (mRestrictionsLock) {
3471 return mBaseUserRestrictions.get(userId);
3472 }
3473 }
3474
3475 @Override
3476 public void setBaseUserRestrictionsByDpmsForMigration(
3477 int userId, Bundle baseRestrictions) {
3478 synchronized (mRestrictionsLock) {
3479 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003480 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003481 }
3482
Amith Yamasani12747872015-12-07 14:19:49 -08003483 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003484 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003485 if (userData != null) {
3486 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003487 } else {
3488 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3489 }
3490 }
3491 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003492
3493 @Override
3494 public boolean getUserRestriction(int userId, String key) {
3495 return getUserRestrictions(userId).getBoolean(key);
3496 }
3497
3498 @Override
3499 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3500 synchronized (mUserRestrictionsListeners) {
3501 mUserRestrictionsListeners.add(listener);
3502 }
3503 }
3504
3505 @Override
3506 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3507 synchronized (mUserRestrictionsListeners) {
3508 mUserRestrictionsListeners.remove(listener);
3509 }
3510 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003511
3512 @Override
3513 public void setDeviceManaged(boolean isManaged) {
3514 synchronized (mUsersLock) {
3515 mIsDeviceManaged = isManaged;
3516 }
3517 }
3518
3519 @Override
3520 public void setUserManaged(int userId, boolean isManaged) {
3521 synchronized (mUsersLock) {
3522 mIsUserManaged.put(userId, isManaged);
3523 }
3524 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003525
3526 @Override
3527 public void setUserIcon(int userId, Bitmap bitmap) {
3528 long ident = Binder.clearCallingIdentity();
3529 try {
3530 synchronized (mPackagesLock) {
3531 UserData userData = getUserDataNoChecks(userId);
3532 if (userData == null || userData.info.partial) {
3533 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3534 return;
3535 }
3536 writeBitmapLP(userData.info, bitmap);
3537 writeUserLP(userData);
3538 }
3539 sendUserInfoChangedBroadcast(userId);
3540 } finally {
3541 Binder.restoreCallingIdentity(ident);
3542 }
3543 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003544
3545 @Override
3546 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3547 synchronized (mUsersLock) {
3548 mForceEphemeralUsers = forceEphemeralUsers;
3549 }
3550 }
3551
3552 @Override
3553 public void removeAllUsers() {
3554 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3555 // Remove the non-system users straight away.
3556 removeNonSystemUsers();
3557 } else {
3558 // Switch to the system user first and then remove the other users.
3559 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3560 @Override
3561 public void onReceive(Context context, Intent intent) {
3562 int userId =
3563 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3564 if (userId != UserHandle.USER_SYSTEM) {
3565 return;
3566 }
3567 mContext.unregisterReceiver(this);
3568 removeNonSystemUsers();
3569 }
3570 };
3571 IntentFilter userSwitchedFilter = new IntentFilter();
3572 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3573 mContext.registerReceiver(
3574 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3575
3576 // Switch to the system user.
3577 ActivityManager am =
3578 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3579 am.switchUser(UserHandle.USER_SYSTEM);
3580 }
3581 }
phweisse9c44062016-02-10 12:57:38 +01003582
3583 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003584 public void onEphemeralUserStop(int userId) {
3585 synchronized (mUsersLock) {
3586 UserInfo userInfo = getUserInfoLU(userId);
3587 if (userInfo != null && userInfo.isEphemeral()) {
3588 // Do not allow switching back to the ephemeral user again as the user is going
3589 // to be deleted.
3590 userInfo.flags |= UserInfo.FLAG_DISABLED;
3591 if (userInfo.isGuest()) {
3592 // Indicate that the guest will be deleted after it stops.
3593 userInfo.guestToRemove = true;
3594 }
3595 }
3596 }
3597 }
3598
3599 @Override
phweisse9c44062016-02-10 12:57:38 +01003600 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003601 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003602 // Keep this in sync with UserManager.createUser
3603 if (user != null && !user.isAdmin()) {
3604 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3605 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3606 }
3607 return user;
3608 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003609
3610 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003611 public boolean removeUserEvenWhenDisallowed(int userId) {
3612 return removeUserUnchecked(userId);
3613 }
3614
3615 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003616 public boolean isUserRunning(int userId) {
3617 synchronized (mUserStates) {
3618 return mUserStates.get(userId, -1) >= 0;
3619 }
3620 }
3621
3622 @Override
3623 public void setUserState(int userId, int userState) {
3624 synchronized (mUserStates) {
3625 mUserStates.put(userId, userState);
3626 }
3627 }
3628
3629 @Override
3630 public void removeUserState(int userId) {
3631 synchronized (mUserStates) {
3632 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003633 }
3634 }
3635
3636 @Override
3637 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003638 synchronized (mUserStates) {
3639 int state = mUserStates.get(userId, -1);
3640 return (state == UserState.STATE_RUNNING_UNLOCKING)
3641 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003642 }
3643 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003644 }
3645
3646 /* Remove all the users except of the system one. */
3647 private void removeNonSystemUsers() {
3648 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3649 synchronized (mUsersLock) {
3650 final int userSize = mUsers.size();
3651 for (int i = 0; i < userSize; i++) {
3652 UserInfo ui = mUsers.valueAt(i).info;
3653 if (ui.id != UserHandle.USER_SYSTEM) {
3654 usersToRemove.add(ui);
3655 }
3656 }
3657 }
3658 for (UserInfo ui: usersToRemove) {
3659 removeUser(ui.id);
3660 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003661 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003662
3663 private class Shell extends ShellCommand {
3664 @Override
3665 public int onCommand(String cmd) {
3666 return onShellCommand(this, cmd);
3667 }
3668
3669 @Override
3670 public void onHelp() {
3671 final PrintWriter pw = getOutPrintWriter();
3672 pw.println("User manager (user) commands:");
3673 pw.println(" help");
3674 pw.println(" Print this help text.");
3675 pw.println("");
3676 pw.println(" list");
3677 pw.println(" Prints all users on the system.");
3678 }
3679 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003680
3681 private static void debug(String message) {
3682 Log.d(LOG_TAG, message +
3683 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3684 }
Kenny Guy02c89902016-11-15 19:36:38 +00003685
3686 @VisibleForTesting
3687 static int getMaxManagedProfiles() {
3688 // Allow overriding max managed profiles on debuggable builds for testing
3689 // of multiple profiles.
3690 if (!Build.IS_DEBUGGABLE) {
3691 return MAX_MANAGED_PROFILES;
3692 } else {
3693 return SystemProperties.getInt("persist.sys.max_profiles",
3694 MAX_MANAGED_PROFILES);
3695 }
3696 }
3697
3698 @VisibleForTesting
3699 int getFreeProfileBadgeLU(int parentUserId) {
3700 int maxManagedProfiles = getMaxManagedProfiles();
3701 boolean[] usedBadges = new boolean[maxManagedProfiles];
3702 final int userSize = mUsers.size();
3703 for (int i = 0; i < userSize; i++) {
3704 UserInfo ui = mUsers.valueAt(i).info;
3705 // Check which badge indexes are already used by this profile group.
3706 if (ui.isManagedProfile()
3707 && ui.profileGroupId == parentUserId
3708 && !mRemovingUserIds.get(ui.id)
3709 && ui.profileBadge < maxManagedProfiles) {
3710 usedBadges[ui.profileBadge] = true;
3711 }
3712 }
3713 for (int i = 0; i < maxManagedProfiles; i++) {
3714 if (!usedBadges[i]) {
3715 return i;
3716 }
3717 }
3718 return 0;
3719 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003720}