blob: 627fa545bf5875d12f4b996dee138d730101e6d9 [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;
Andrew Scull85a63bc2016-10-24 13:47:47 +010029import android.app.ActivityManagerNative;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070053import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080054import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010055import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070056import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080057import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070058import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070059import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070060import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010061import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040062import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070063import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070064import android.os.ShellCommand;
Kenny Guy02c89902016-11-15 19:36:38 +000065import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070067import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010068import android.os.UserManager.EnforcingUser;
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;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100120import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700121import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122import java.util.List;
123
Makoto Onuki068c54a2015-10-13 14:34:03 -0700124/**
125 * Service for {@link UserManager}.
126 *
127 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700128 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800129 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700130 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
131 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
132 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700133 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700134public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700135
Amith Yamasani2a003292012-08-14 18:25:45 -0700136 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800137 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800138 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700139 // Can be used for manual testing of id recycling
140 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700141
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800143 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700145 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700147 private static final String ATTR_CREATION_TIME = "created";
148 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600149 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700150 private static final String ATTR_SERIAL_NO = "serialNumber";
151 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700152 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700153 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700154 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100155 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000156 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700157 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800158 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
159 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530160 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700161 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700162 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800163 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800164 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100165 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
166 "device_policy_global_restrictions";
167 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100168 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100169 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800170 private static final String TAG_ENTRY = "entry";
171 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800172 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800173 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700174 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800175 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700176
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700177 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
178 private static final String ATTR_TYPE_STRING = "s";
179 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700180 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700181 private static final String ATTR_TYPE_BUNDLE = "B";
182 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700183
Amith Yamasani0b285492011-04-14 17:35:23 -0700184 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700186 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100187 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800189 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700190 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800191
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700192 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
193 UserInfo.FLAG_MANAGED_PROFILE
194 | UserInfo.FLAG_EPHEMERAL
195 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700196 | UserInfo.FLAG_GUEST
197 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700198
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700199 @VisibleForTesting
200 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700201 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700202 @VisibleForTesting
203 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
204
205 // Max size of the queue of recently removed users
206 @VisibleForTesting
207 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700208
Pavel Grafov6a40f092016-10-25 15:46:51 +0100209 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700210
Amith Yamasani920ace02012-09-20 22:15:37 -0700211 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
212
Nicolas Prevotb8186812015-08-06 15:00:03 +0100213 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700214 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000215 @VisibleForTesting
216 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700217
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800218 static final int WRITE_USER_MSG = 1;
219 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530220
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800221 // Tron counters
222 private static final String TRON_GUEST_CREATED = "users_guest_created";
223 private static final String TRON_USER_CREATED = "users_user_created";
224
Dianne Hackborn4428e172012-08-24 17:43:05 -0700225 private final Context mContext;
226 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700227 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800228 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700229 // Short-term lock for internal state, when interaction/sync with PM is not required
230 private final Object mUsersLock = new Object();
231 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700232
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800233 private final Handler mHandler;
234
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700235 private final File mUsersDir;
236 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700237
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800238 private static final IBinder mUserRestriconToken = new Binder();
239
Makoto Onuki068c54a2015-10-13 14:34:03 -0700240 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800241 * User-related information that is used for persisting to flash. Only UserInfo is
242 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800243 */
Kenny Guy02c89902016-11-15 19:36:38 +0000244 @VisibleForTesting
245 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800246 // Basic user information and properties
247 UserInfo info;
248 // Account name used when there is a strong association between a user and an account
249 String account;
250 // Account information for seeding into a newly created user. This could also be
251 // used for login validation for an existing user, for updating their credentials.
252 // In the latter case, data may not need to be persisted as it is only valid for the
253 // current login session.
254 String seedAccountName;
255 String seedAccountType;
256 PersistableBundle seedAccountOptions;
257 // Whether to perist the seed account information to be available after a boot
258 boolean persistSeedData;
259
260 void clearSeedAccountData() {
261 seedAccountName = null;
262 seedAccountType = null;
263 seedAccountOptions = null;
264 persistSeedData = false;
265 }
266 }
267
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800268 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800269 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800270
271 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700272 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100273 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700274 *
275 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
276 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
277 * maybe shared between {@link #mBaseUserRestrictions} and
278 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
279 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700280 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700281 */
282 @GuardedBy("mRestrictionsLock")
283 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
284
285 /**
286 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
287 * with device / profile owner restrictions. We'll initialize it lazily; use
288 * {@link #getEffectiveUserRestrictions} to access it.
289 *
290 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
291 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
292 * maybe shared between {@link #mBaseUserRestrictions} and
293 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
294 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700295 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700296 */
297 @GuardedBy("mRestrictionsLock")
298 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
299
Makoto Onuki4f160732015-10-27 17:15:38 -0700300 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800301 * User restrictions that have already been applied in
302 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
303 * that have changed since the last
304 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700305 */
306 @GuardedBy("mRestrictionsLock")
307 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
308
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800309 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800310 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100311 * that should be applied to all users, including guests. Only non-empty restriction bundles are
312 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800313 */
314 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100315 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800316
317 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100318 * Id of the user that set global restrictions.
319 */
320 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100321 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100322
323 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800324 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100325 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800326 */
327 @GuardedBy("mRestrictionsLock")
328 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
329
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800330 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530331 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800332
333 /**
334 * Set of user IDs being actively removed. Removed IDs linger in this set
335 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700336 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800337 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700338 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800339 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700340
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700341 /**
342 * Queue of recently removed userIds. Used for recycling of userIds
343 */
344 @GuardedBy("mUsersLock")
345 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
346
Fyodor Kupolov82402752015-10-28 14:54:51 -0700347 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700348 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800349 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700350 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700351 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700352
Jason Monk62062992014-05-06 09:55:28 -0400353 private IAppOpsService mAppOpsService;
354
Makoto Onuki068c54a2015-10-13 14:34:03 -0700355 private final LocalService mLocalService;
356
Makoto Onukie7927da2015-11-25 10:05:17 -0800357 @GuardedBy("mUsersLock")
358 private boolean mIsDeviceManaged;
359
360 @GuardedBy("mUsersLock")
361 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
362
Makoto Onukid45a4a22015-11-02 17:17:38 -0800363 @GuardedBy("mUserRestrictionsListeners")
364 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
365 new ArrayList<>();
366
Clara Bayarria1771112015-12-18 16:29:18 +0000367 private final LockPatternUtils mLockPatternUtils;
368
Ricky Waib1dd80b2016-06-07 18:00:55 +0100369 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
370 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
371
372 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
373 @Override
374 public void onReceive(Context context, Intent intent) {
375 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
376 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
377 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
378 setQuietModeEnabled(userHandle, false);
379 if (target != null) {
380 try {
381 mContext.startIntentSender(target, null, 0, 0, 0);
382 } catch (IntentSender.SendIntentException e) {
383 /* ignore */
384 }
385 }
386 }
387 }
388 };
389
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100390 /**
391 * Whether all users should be created ephemeral.
392 */
393 @GuardedBy("mUsersLock")
394 private boolean mForceEphemeralUsers;
395
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000396 @GuardedBy("mUserStates")
397 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700398
Amith Yamasani258848d2012-08-10 17:06:33 -0700399 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700400
Dianne Hackborn4428e172012-08-24 17:43:05 -0700401 public static UserManagerService getInstance() {
402 synchronized (UserManagerService.class) {
403 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700404 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700405 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700406
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700407 public static class LifeCycle extends SystemService {
408
409 private UserManagerService mUms;
410
411 /**
412 * @param context
413 */
414 public LifeCycle(Context context) {
415 super(context);
416 }
417
418 @Override
419 public void onStart() {
420 mUms = UserManagerService.getInstance();
421 publishBinderService(Context.USER_SERVICE, mUms);
422 }
423
424 @Override
425 public void onBootPhase(int phase) {
426 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
427 mUms.cleanupPartialUsers();
428 }
429 }
430 }
431
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700432 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800433 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700434 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800435 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700436 }
437
Dianne Hackborn4428e172012-08-24 17:43:05 -0700438 /**
439 * Called by package manager to create the service. This is closely
440 * associated with the package manager, and the given lock is the
441 * package manager's own lock.
442 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800443 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
444 Object packagesLock) {
445 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700446 }
447
Dianne Hackborn4428e172012-08-24 17:43:05 -0700448 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800449 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700450 mContext = context;
451 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700452 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800453 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800454 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800455 synchronized (mPackagesLock) {
456 mUsersDir = new File(dataDir, USER_INFO_DIR);
457 mUsersDir.mkdirs();
458 // Make zeroth user directory, for services to migrate their files to that location
459 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
460 userZeroDir.mkdirs();
461 FileUtils.setPermissions(mUsersDir.toString(),
462 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
463 -1, -1);
464 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
465 initDefaultGuestRestrictions();
466 readUserListLP();
467 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700468 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700469 mLocalService = new LocalService();
470 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000471 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000472 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700473 }
474
475 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400476 mAppOpsService = IAppOpsService.Stub.asInterface(
477 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800478
479 synchronized (mRestrictionsLock) {
480 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400481 }
Samuel Tand9453b82016-03-14 15:57:02 -0700482
483 UserInfo currentGuestUser = findCurrentGuestUser();
484 if (currentGuestUser != null && !hasUserRestriction(
485 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
486 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
487 // to it, in case this guest was created in a previous version where this
488 // user restriction was not a default guest restriction.
489 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
490 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700491
Ricky Waib1dd80b2016-06-07 18:00:55 +0100492 mContext.registerReceiver(mDisableQuietModeCallback,
493 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
494 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700495 }
496
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700497 void cleanupPartialUsers() {
498 // Prune out any partially created, partially removed and ephemeral users.
499 ArrayList<UserInfo> partials = new ArrayList<>();
500 synchronized (mUsersLock) {
501 final int userSize = mUsers.size();
502 for (int i = 0; i < userSize; i++) {
503 UserInfo ui = mUsers.valueAt(i).info;
504 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
505 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700506 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700507 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700508 }
509 }
510 }
511 final int partialsSize = partials.size();
512 for (int i = 0; i < partialsSize; i++) {
513 UserInfo ui = partials.get(i);
514 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
515 + " (name=" + ui.name + ")");
516 removeUserState(ui.id);
517 }
518 }
519
Amith Yamasani258848d2012-08-10 17:06:33 -0700520 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800521 public String getUserAccount(int userId) {
522 checkManageUserAndAcrossUsersFullPermission("get user account");
523 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800524 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800525 }
526 }
527
528 @Override
529 public void setUserAccount(int userId, String accountName) {
530 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800531 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800532 synchronized (mPackagesLock) {
533 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800534 final UserData userData = mUsers.get(userId);
535 if (userData == null) {
536 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
537 return;
538 }
539 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800540 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800541 userData.account = accountName;
542 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800543 }
544 }
545
546 if (userToUpdate != null) {
547 writeUserLP(userToUpdate);
548 }
549 }
550 }
551
552 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700553 public UserInfo getPrimaryUser() {
554 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700555 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700556 final int userSize = mUsers.size();
557 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800558 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800559 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700560 return ui;
561 }
562 }
563 }
564 return null;
565 }
566
567 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700568 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700569 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700570 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700571 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700572 final int userSize = mUsers.size();
573 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800574 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700575 if (ui.partial) {
576 continue;
577 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800578 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700579 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700580 }
Amith Yamasani13593602012-03-22 16:16:17 -0700581 }
582 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700583 }
Amith Yamasani13593602012-03-22 16:16:17 -0700584 }
585
Amith Yamasani258848d2012-08-10 17:06:33 -0700586 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100587 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700588 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800589 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700590 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700591 } else {
592 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800593 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700594 final long ident = Binder.clearCallingIdentity();
595 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700596 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700597 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100598 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700599 } finally {
600 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000601 }
602 }
603
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700604 @Override
605 public int[] getProfileIds(int userId, boolean enabledOnly) {
606 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700607 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700608 }
609 final long ident = Binder.clearCallingIdentity();
610 try {
611 synchronized (mUsersLock) {
612 return getProfileIdsLU(userId, enabledOnly).toArray();
613 }
614 } finally {
615 Binder.restoreCallingIdentity(ident);
616 }
617 }
618
Amith Yamasanibe465322014-04-24 13:45:17 -0700619 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700620 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700621 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
622 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
623 for (int i = 0; i < profileIds.size(); i++) {
624 int profileId = profileIds.get(i);
625 UserInfo userInfo = mUsers.get(profileId).info;
626 // If full info is not required - clear PII data to prevent 3P apps from reading it
627 if (!fullInfo) {
628 userInfo = new UserInfo(userInfo);
629 userInfo.name = null;
630 userInfo.iconPath = null;
631 } else {
632 userInfo = userWithName(userInfo);
633 }
634 users.add(userInfo);
635 }
636 return users;
637 }
638
639 /**
640 * Assume permissions already checked and caller's identity cleared
641 */
642 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700643 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700644 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700645 if (user == null) {
646 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700647 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700648 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700649 final int userSize = mUsers.size();
650 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800651 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700652 if (!isProfileOf(user, profile)) {
653 continue;
654 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100655 if (enabledOnly && !profile.isEnabled()) {
656 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700657 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700658 if (mRemovingUserIds.get(profile.id)) {
659 continue;
660 }
Tony Mak80189cd2016-04-05 17:21:42 +0100661 if (profile.partial) {
662 continue;
663 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700664 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700665 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700666 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700667 }
668
Jessica Hummelbe81c802014-04-22 15:49:22 +0100669 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700670 public int getCredentialOwnerProfile(int userHandle) {
671 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000672 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700673 synchronized (mUsersLock) {
674 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700675 if (profileParent != null) {
676 return profileParent.id;
677 }
678 }
679 }
680
681 return userHandle;
682 }
683
684 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700685 public boolean isSameProfileGroup(int userId, int otherUserId) {
686 if (userId == otherUserId) return true;
687 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700688 return isSameProfileGroupNoChecks(userId, otherUserId);
689 }
690
691 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700692 synchronized (mUsersLock) {
693 UserInfo userInfo = getUserInfoLU(userId);
694 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
695 return false;
696 }
697 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
698 if (otherUserInfo == null
699 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
700 return false;
701 }
702 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700703 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700704 }
705
706 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100707 public UserInfo getProfileParent(int userHandle) {
708 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700709 synchronized (mUsersLock) {
710 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700711 }
712 }
713
Fyodor Kupolov82402752015-10-28 14:54:51 -0700714 private UserInfo getProfileParentLU(int userHandle) {
715 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700716 if (profile == null) {
717 return null;
718 }
719 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800720 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700721 return null;
722 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700723 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100724 }
725 }
726
Fyodor Kupolov82402752015-10-28 14:54:51 -0700727 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100728 return user.id == profile.id ||
729 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
730 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000731 }
732
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000733 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000734 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100735 Intent intent = new Intent();
736 if (inQuietMode) {
737 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
738 } else {
739 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
740 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000741 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
742 intent.putExtra(Intent.EXTRA_USER, profileHandle);
743 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000744 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000745 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000746 }
747
748 @Override
749 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
750 checkManageUsersPermission("silence profile");
751 boolean changed = false;
752 UserInfo profile, parent;
753 synchronized (mPackagesLock) {
754 synchronized (mUsersLock) {
755 profile = getUserInfoLU(userHandle);
756 parent = getProfileParentLU(userHandle);
757
758 }
759 if (profile == null || !profile.isManagedProfile()) {
760 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
761 }
762 if (profile.isQuietModeEnabled() != enableQuietMode) {
763 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800764 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000765 changed = true;
766 }
767 }
768 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000769 long identity = Binder.clearCallingIdentity();
770 try {
771 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800772 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100773 LocalServices.getService(ActivityManagerInternal.class)
774 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000775 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800776 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000777 }
778 } catch (RemoteException e) {
779 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
780 } finally {
781 Binder.restoreCallingIdentity(identity);
782 }
783
784 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
785 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000786 }
787 }
788
789 @Override
790 public boolean isQuietModeEnabled(int userHandle) {
791 synchronized (mPackagesLock) {
792 UserInfo info;
793 synchronized (mUsersLock) {
794 info = getUserInfoLU(userHandle);
795 }
796 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000797 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000798 }
799 return info.isQuietModeEnabled();
800 }
801 }
802
Kenny Guya52dc3e2014-02-11 15:33:14 +0000803 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100804 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100805 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600806 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100807 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100808 // if the user is already unlocked, no need to show a profile challenge
809 setQuietModeEnabled(userHandle, false);
810 return true;
811 }
812
813 long identity = Binder.clearCallingIdentity();
814 try {
815 // otherwise, we show a profile challenge to trigger decryption of the user
816 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
817 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100818 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
819 // lock, confirm screenlock page will know and show personal challenge, and unlock
820 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100821 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
822 userHandle);
823 if (unlockIntent == null) {
824 return false;
825 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100826 final Intent callBackIntent = new Intent(
827 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100828 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100829 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100830 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100831 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
832 callBackIntent.setPackage(mContext.getPackageName());
833 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
834 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
835 mContext,
836 0,
837 callBackIntent,
838 PendingIntent.FLAG_CANCEL_CURRENT |
839 PendingIntent.FLAG_ONE_SHOT |
840 PendingIntent.FLAG_IMMUTABLE);
841 // After unlocking the challenge, it will disable quiet mode and run the original
842 // intentSender
843 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100844 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
845 mContext.startActivity(unlockIntent);
846 } finally {
847 Binder.restoreCallingIdentity(identity);
848 }
849 return false;
850 }
851
852 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100853 public void setUserEnabled(int userId) {
854 checkManageUsersPermission("enable user");
855 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700856 UserInfo info;
857 synchronized (mUsersLock) {
858 info = getUserInfoLU(userId);
859 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100860 if (info != null && !info.isEnabled()) {
861 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800862 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100863 }
864 }
865 }
866
Andrew Scull85a63bc2016-10-24 13:47:47 +0100867 /**
868 * Evicts a user's CE key by stopping and restarting the user.
869 *
870 * The key is evicted automatically by the user controller when the user has stopped.
871 */
872 @Override
873 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
874 checkManageUsersPermission("evict CE key");
875 final IActivityManager am = ActivityManagerNative.getDefault();
876 final long identity = Binder.clearCallingIdentity();
877 try {
878 am.restartUserInBackground(userId);
879 } catch (RemoteException re) {
880 throw re.rethrowAsRuntimeException();
881 } finally {
882 Binder.restoreCallingIdentity(identity);
883 }
884 }
885
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100886 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700887 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700888 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000889 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700890 return userWithName(getUserInfoLU(userId));
891 }
892 }
893
894 /**
895 * Returns a UserInfo object with the name filled in, for Owner, or the original
896 * if the name is already set.
897 */
898 private UserInfo userWithName(UserInfo orig) {
899 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
900 UserInfo withName = new UserInfo(orig);
901 withName.name = getOwnerName();
902 return withName;
903 } else {
904 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000905 }
906 }
907
908 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000909 public int getManagedProfileBadge(@UserIdInt int userId) {
910 int callingUserId = UserHandle.getCallingUserId();
911 if (callingUserId != userId && !hasManageUsersPermission()) {
912 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
913 throw new SecurityException(
914 "You need MANAGE_USERS permission to: check if specified user a " +
915 "managed profile outside your profile group");
916 }
917 }
918 synchronized (mUsersLock) {
919 UserInfo userInfo = getUserInfoLU(userId);
920 return userInfo != null ? userInfo.profileBadge : 0;
921 }
922 }
923
924 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000925 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000926 int callingUserId = UserHandle.getCallingUserId();
927 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700928 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700929 throw new SecurityException(
930 "You need MANAGE_USERS permission to: check if specified user a " +
931 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000932 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000933 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700934 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700935 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000936 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700937 }
938 }
939
Amith Yamasani71e6c692013-03-24 17:39:28 -0700940 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700941 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800942 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700943 return mLocalService.isUserUnlockingOrUnlocked(userId);
944 }
945
946 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800947 public boolean isUserUnlocked(int userId) {
948 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
949 return mLocalService.isUserUnlockingOrUnlocked(userId);
950 }
951
952 @Override
953 public boolean isUserRunning(int userId) {
954 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
955 return mLocalService.isUserRunning(userId);
956 }
957
958 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
959 int callingUserId = UserHandle.getCallingUserId();
960 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
961 hasManageUsersPermission()) {
962 return;
963 }
964 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
965 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
966 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
967 + "to: check " + name);
968 }
969 }
970
971 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700972 public boolean isDemoUser(int userId) {
973 int callingUserId = UserHandle.getCallingUserId();
974 if (callingUserId != userId && !hasManageUsersPermission()) {
975 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
976 + " is a demo user");
977 }
978 synchronized (mUsersLock) {
979 UserInfo userInfo = getUserInfoLU(userId);
980 return userInfo != null && userInfo.isDemo();
981 }
982 }
983
984 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700985 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700986 synchronized (mUsersLock) {
987 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700988 }
989 }
990
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700991 @Override
992 public boolean canHaveRestrictedProfile(int userId) {
993 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700994 synchronized (mUsersLock) {
995 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700996 if (userInfo == null || !userInfo.canHaveProfile()) {
997 return false;
998 }
999 if (!userInfo.isAdmin()) {
1000 return false;
1001 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001002 // restricted profile can be created if there is no DO set and the admin user has no PO;
1003 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001004 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001005 }
1006
Amith Yamasani195263742012-08-21 15:40:12 -07001007 /*
1008 * Should be locked on mUsers before calling this.
1009 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001010 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001011 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001012 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001013 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001014 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1015 return null;
1016 }
Amith Yamasani12747872015-12-07 14:19:49 -08001017 return userData != null ? userData.info : null;
1018 }
1019
1020 private UserData getUserDataLU(int userId) {
1021 final UserData userData = mUsers.get(userId);
1022 // If it is partial and not in the process of being removed, return as unknown user.
1023 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1024 return null;
1025 }
1026 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001027 }
1028
Fyodor Kupolov82402752015-10-28 14:54:51 -07001029 /**
1030 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1031 * <p>No permissions checking or any addition checks are made</p>
1032 */
1033 private UserInfo getUserInfoNoChecks(int userId) {
1034 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001035 final UserData userData = mUsers.get(userId);
1036 return userData != null ? userData.info : null;
1037 }
1038 }
1039
1040 /**
1041 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1042 * <p>No permissions checking or any addition checks are made</p>
1043 */
1044 private UserData getUserDataNoChecks(int userId) {
1045 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001046 return mUsers.get(userId);
1047 }
1048 }
1049
Amith Yamasani236b2b52015-08-18 14:32:14 -07001050 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001051 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001052 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001053 }
1054
Amith Yamasani258848d2012-08-10 17:06:33 -07001055 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001056 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001057 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001058 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001059 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001060 UserData userData = getUserDataNoChecks(userId);
1061 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001062 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1063 return;
1064 }
Amith Yamasani12747872015-12-07 14:19:49 -08001065 if (name != null && !name.equals(userData.info.name)) {
1066 userData.info.name = name;
1067 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001068 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001069 }
1070 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001071 if (changed) {
1072 sendUserInfoChangedBroadcast(userId);
1073 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001074 }
1075
Amith Yamasani258848d2012-08-10 17:06:33 -07001076 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001077 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001078 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001079 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1080 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1081 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001082 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001083 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001084 }
1085
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001086
1087
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001088 private void sendUserInfoChangedBroadcast(int userId) {
1089 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1090 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1091 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001092 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001093 }
1094
Amith Yamasani258848d2012-08-10 17:06:33 -07001095 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001096 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001097 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001098 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001099 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1100 if (targetUserInfo == null || targetUserInfo.partial) {
1101 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001102 return null;
1103 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001104
1105 final int callingUserId = UserHandle.getCallingUserId();
1106 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1107 final int targetGroupId = targetUserInfo.profileGroupId;
1108 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1109 && callingGroupId == targetGroupId);
1110 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001111 checkManageUsersPermission("get the icon of a user who is not related");
1112 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001113
1114 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001115 return null;
1116 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001117 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001118 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001119
1120 try {
1121 return ParcelFileDescriptor.open(
1122 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1123 } catch (FileNotFoundException e) {
1124 Log.e(LOG_TAG, "Couldn't find icon file", e);
1125 }
1126 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001127 }
1128
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001129 public void makeInitialized(int userId) {
1130 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001131 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001132 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001133 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001134 userData = mUsers.get(userId);
1135 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001136 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001137 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001138 }
Amith Yamasani12747872015-12-07 14:19:49 -08001139 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1140 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001141 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001142 }
1143 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001144 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001145 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001146 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001147 }
1148
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001149 /**
1150 * If default guest restrictions haven't been initialized yet, add the basic
1151 * restrictions.
1152 */
1153 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001154 synchronized (mGuestRestrictions) {
1155 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001156 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001157 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001158 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1159 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1160 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001161 }
1162 }
1163
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001164 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301165 public Bundle getDefaultGuestRestrictions() {
1166 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001167 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301168 return new Bundle(mGuestRestrictions);
1169 }
1170 }
1171
1172 @Override
1173 public void setDefaultGuestRestrictions(Bundle restrictions) {
1174 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001175 synchronized (mGuestRestrictions) {
1176 mGuestRestrictions.clear();
1177 mGuestRestrictions.putAll(restrictions);
1178 }
1179 synchronized (mPackagesLock) {
1180 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301181 }
1182 }
1183
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001184 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001185 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001186 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001187 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1188 boolean isDeviceOwner, int cameraRestrictionScope) {
1189 final Bundle global = new Bundle();
1190 final Bundle local = new Bundle();
1191
1192 // Sort restrictions into local and global ensuring they don't overlap.
1193 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1194 cameraRestrictionScope, global, local);
1195
1196 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001197 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001198 // Update global and local restrictions if they were changed.
1199 globalChanged = updateRestrictionsIfNeededLR(
1200 userId, global, mDevicePolicyGlobalUserRestrictions);
1201 localChanged = updateRestrictionsIfNeededLR(
1202 userId, local, mDevicePolicyLocalUserRestrictions);
1203
1204 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001205 // Remember the global restriction owner userId to be able to make a distinction
1206 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001207 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001208 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001209 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001210 // When profile owner sets restrictions it passes null global bundle and we
1211 // reset global restriction owner userId.
1212 // This means this user used to have DO, but now the DO is gone and the user
1213 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001214 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001215 }
1216 }
1217 }
1218 if (DBG) {
1219 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1220 + " global=" + global + (globalChanged ? " (changed)" : "")
1221 + " local=" + local + (localChanged ? " (changed)" : "")
1222 );
1223 }
1224 // Don't call them within the mRestrictionsLock.
1225 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001226 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001227 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001228 }
1229 }
1230
1231 synchronized (mRestrictionsLock) {
1232 if (globalChanged) {
1233 applyUserRestrictionsForAllUsersLR();
1234 } else if (localChanged) {
1235 applyUserRestrictionsLR(userId);
1236 }
1237 }
1238 }
1239
Pavel Grafov6a40f092016-10-25 15:46:51 +01001240 /**
1241 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1242 * empty, record is removed from the array.
1243 * @return whether restrictions bundle is different from the old one.
1244 */
1245 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1246 SparseArray<Bundle> restrictionsArray) {
1247 final boolean changed =
1248 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1249 if (changed) {
1250 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1251 restrictionsArray.put(userId, restrictions);
1252 } else {
1253 restrictionsArray.delete(userId);
1254 }
1255 }
1256 return changed;
1257 }
1258
Makoto Onuki068c54a2015-10-13 14:34:03 -07001259 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001260 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001261 final Bundle baseRestrictions =
1262 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001263 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001264 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001265
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001266 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1267 // Common case first.
1268 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001269 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001270 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1271 UserRestrictionsUtils.merge(effective, global);
1272 UserRestrictionsUtils.merge(effective, local);
1273
Makoto Onuki068c54a2015-10-13 14:34:03 -07001274 return effective;
1275 }
1276
1277 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001278 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001279 if (DBG) {
1280 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1281 }
1282 mCachedEffectiveUserRestrictions.remove(userId);
1283 }
1284
1285 private Bundle getEffectiveUserRestrictions(int userId) {
1286 synchronized (mRestrictionsLock) {
1287 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1288 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001289 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001290 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1291 }
1292 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001293 }
1294 }
1295
Makoto Onuki068c54a2015-10-13 14:34:03 -07001296 /** @return a specific user restriction that's in effect currently. */
1297 @Override
1298 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001299 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1300 return false;
1301 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001302 Bundle restrictions = getEffectiveUserRestrictions(userId);
1303 return restrictions != null && restrictions.getBoolean(restrictionKey);
1304 }
1305
1306 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001307 * @hide
1308 *
1309 * Returns who set a user restriction on a user.
1310 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1311 * @param restrictionKey the string key representing the restriction
1312 * @param userId the id of the user for whom to retrieve the restrictions.
1313 * @return The source of user restriction. Any combination of
1314 * {@link UserManager#RESTRICTION_NOT_SET},
1315 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1316 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1317 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1318 */
1319 @Override
1320 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001321 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1322 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001323 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001324 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1325 result |= enforcingUsers.get(i).getUserRestrictionSource();
1326 }
1327 return result;
1328 }
1329
1330 @Override
1331 public List<EnforcingUser> getUserRestrictionSources(
1332 String restrictionKey, @UserIdInt int userId) {
1333 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001334
1335 // Shortcut for the most common case
1336 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001337 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001338 }
1339
Pavel Grafov6a40f092016-10-25 15:46:51 +01001340 final List<EnforcingUser> result = new ArrayList<>();
1341
1342 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001343 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001344 result.add(new EnforcingUser(
1345 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001346 }
1347
Pavel Grafov6a40f092016-10-25 15:46:51 +01001348 synchronized (mRestrictionsLock) {
1349 // Check if it is set by profile owner.
1350 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1351 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1352 result.add(getEnforcingUserLocked(userId));
1353 }
1354
1355 // Iterate over all users who enforce global restrictions.
1356 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1357 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1358 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1359 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1360 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001361 }
1362 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001363 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001364 return result;
1365 }
1366
Pavel Grafov6a40f092016-10-25 15:46:51 +01001367 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1368 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1369 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1370 return new EnforcingUser(userId, source);
1371 }
1372
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001373 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001374 * @return UserRestrictions that are in effect currently. This always returns a new
1375 * {@link Bundle}.
1376 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001377 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001378 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001379 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001380 }
1381
1382 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001383 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1384 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001385 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1386 return false;
1387 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001388 synchronized (mRestrictionsLock) {
1389 Bundle bundle = mBaseUserRestrictions.get(userId);
1390 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1391 }
1392 }
1393
1394 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001395 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001396 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001397 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1398 return;
1399 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001400 synchronized (mRestrictionsLock) {
1401 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1402 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001403 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1404 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001405 newRestrictions.putBoolean(key, value);
1406
Fyodor Kupolov82402752015-10-28 14:54:51 -07001407 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001408 }
1409 }
1410
Makoto Onuki068c54a2015-10-13 14:34:03 -07001411 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001412 * Optionally updating user restrictions, calculate the effective user restrictions and also
1413 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001414 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001415 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001416 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001417 * @param userId target user ID.
1418 */
1419 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001420 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001421 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001422 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1423 mAppliedUserRestrictions.get(userId));
1424
1425 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001426 if (newBaseRestrictions != null) {
1427 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001428 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1429
Pavel Grafov6a40f092016-10-25 15:46:51 +01001430 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001431 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001432 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001433
Pavel Grafov6a40f092016-10-25 15:46:51 +01001434 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001435 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001436 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001437 }
1438
Fyodor Kupolov82402752015-10-28 14:54:51 -07001439 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001440
Makoto Onuki759a7632015-10-28 16:43:10 -07001441 mCachedEffectiveUserRestrictions.put(userId, effective);
1442
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001443 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001444 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001445 debug("Applying user restrictions: userId=" + userId
1446 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001447 }
1448
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001449 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001450 mHandler.post(new Runnable() {
1451 @Override
1452 public void run() {
1453 try {
1454 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1455 } catch (RemoteException e) {
1456 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1457 }
1458 }
1459 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001460 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001461
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001463
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001465 }
1466
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001467 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001468 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001469 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1470 // actually, but we still need some kind of synchronization otherwise we might end up
1471 // calling listeners out-of-order, thus "LR".
1472
1473 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1474 return;
1475 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001476
1477 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1478 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1479
1480 mHandler.post(new Runnable() {
1481 @Override
1482 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001483 UserRestrictionsUtils.applyUserRestrictions(
1484 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001485
Makoto Onukid45a4a22015-11-02 17:17:38 -08001486 final UserRestrictionsListener[] listeners;
1487 synchronized (mUserRestrictionsListeners) {
1488 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1489 mUserRestrictionsListeners.toArray(listeners);
1490 }
1491 for (int i = 0; i < listeners.length; i++) {
1492 listeners[i].onUserRestrictionsChanged(userId,
1493 newRestrictionsFinal, prevRestrictionsFinal);
1494 }
1495 }
1496 });
1497 }
1498
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001499 // Package private for the inner class.
1500 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001501 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001502 }
1503
1504 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001505 // Package private for the inner class.
1506 void applyUserRestrictionsForAllUsersLR() {
1507 if (DBG) {
1508 debug("applyUserRestrictionsForAllUsersLR");
1509 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001510 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001511 mCachedEffectiveUserRestrictions.clear();
1512
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001513 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001514 // it on a handler.
1515 final Runnable r = new Runnable() {
1516 @Override
1517 public void run() {
1518 // Then get the list of running users.
1519 final int[] runningUsers;
1520 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001521 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001522 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001523 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001524 return;
1525 }
1526 // Then re-calculate the effective restrictions and apply, only for running users.
1527 // It's okay if a new user has started after the getRunningUserIds() call,
1528 // because we'll do the same thing (re-calculate the restrictions and apply)
1529 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001530 synchronized (mRestrictionsLock) {
1531 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001532 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001533 }
1534 }
1535 }
1536 };
1537 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001538 }
1539
Amith Yamasani258848d2012-08-10 17:06:33 -07001540 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001541 * Check if we've hit the limit of how many users can be created.
1542 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001543 private boolean isUserLimitReached() {
1544 int count;
1545 synchronized (mUsersLock) {
1546 count = getAliveUsersExcludingGuestsCountLU();
1547 }
1548 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001549 }
1550
1551 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001552 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001553 checkManageUsersPermission("check if more managed profiles can be added.");
1554 if (ActivityManager.isLowRamDeviceStatic()) {
1555 return false;
1556 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001557 if (!mContext.getPackageManager().hasSystemFeature(
1558 PackageManager.FEATURE_MANAGED_USERS)) {
1559 return false;
1560 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001561 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001562 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001563 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001564 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001565 return false;
1566 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001567 synchronized(mUsersLock) {
1568 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001569 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001570 return false;
1571 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001572 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1573 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001574 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001575 return usersCountAfterRemoving == 1
1576 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001577 }
1578 }
1579
Fyodor Kupolov82402752015-10-28 14:54:51 -07001580 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001581 int aliveUserCount = 0;
1582 final int totalUserCount = mUsers.size();
1583 // Skip over users being removed
1584 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001585 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001586 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001587 aliveUserCount++;
1588 }
1589 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001590 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001591 }
1592
1593 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001594 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001595 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1596 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1597 * permissions can make certain calls to the UserManager.
1598 *
1599 * @param message used as message if SecurityException is thrown
1600 * @throws SecurityException if the caller does not have enough privilege.
1601 */
1602 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1603 final int uid = Binder.getCallingUid();
1604 if (uid != Process.SYSTEM_UID && uid != 0
1605 && ActivityManager.checkComponentPermission(
1606 Manifest.permission.MANAGE_USERS,
1607 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1608 && ActivityManager.checkComponentPermission(
1609 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1610 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1611 throw new SecurityException(
1612 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1613 + message);
1614 }
1615 }
1616
1617 /**
1618 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001619 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001620 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001621 *
1622 * @param message used as message if SecurityException is thrown
1623 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001624 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001625 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001626 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001627 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001628 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1629 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001630 }
1631
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001632 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001633 * Enforces that only the system UID or root's UID or apps that have the
1634 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1635 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1636 * can make certain calls to the UserManager.
1637 *
1638 * @param message used as message if SecurityException is thrown
1639 * @throws SecurityException if the caller is not system or root
1640 * @see #hasManageOrCreateUsersPermission()
1641 */
1642 private static final void checkManageOrCreateUsersPermission(String message) {
1643 if (!hasManageOrCreateUsersPermission()) {
1644 throw new SecurityException(
1645 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1646 }
1647 }
1648
1649 /**
1650 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1651 * to create user/profiles other than what is allowed for
1652 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1653 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1654 */
1655 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1656 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1657 if (!hasManageOrCreateUsersPermission()) {
1658 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1659 + "permission to create an user with flags: " + creationFlags);
1660 }
1661 } else if (!hasManageUsersPermission()) {
1662 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1663 + " with flags: " + creationFlags);
1664 }
1665 }
1666
1667 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001668 * @return whether the calling UID is system UID or root's UID or the calling app has the
1669 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1670 */
1671 private static final boolean hasManageUsersPermission() {
1672 final int callingUid = Binder.getCallingUid();
1673 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1674 || callingUid == Process.ROOT_UID
1675 || ActivityManager.checkComponentPermission(
1676 android.Manifest.permission.MANAGE_USERS,
1677 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1678 }
1679
1680 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001681 * @return whether the calling UID is system UID or root's UID or the calling app has the
1682 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1683 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1684 */
1685 private static final boolean hasManageOrCreateUsersPermission() {
1686 final int callingUid = Binder.getCallingUid();
1687 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1688 || callingUid == Process.ROOT_UID
1689 || ActivityManager.checkComponentPermission(
1690 android.Manifest.permission.MANAGE_USERS,
1691 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1692 || ActivityManager.checkComponentPermission(
1693 android.Manifest.permission.CREATE_USERS,
1694 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1695 }
1696
1697 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001698 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1699 * UserManager.
1700 *
1701 * @param message used as message if SecurityException is thrown
1702 * @throws SecurityException if the caller is not system or root
1703 */
1704 private static void checkSystemOrRoot(String message) {
1705 final int uid = Binder.getCallingUid();
1706 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1707 throw new SecurityException("Only system may: " + message);
1708 }
1709 }
1710
Fyodor Kupolov82402752015-10-28 14:54:51 -07001711 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001712 try {
1713 File dir = new File(mUsersDir, Integer.toString(info.id));
1714 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001715 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001716 if (!dir.exists()) {
1717 dir.mkdir();
1718 FileUtils.setPermissions(
1719 dir.getPath(),
1720 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1721 -1, -1);
1722 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001723 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001724 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001725 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001726 info.iconPath = file.getAbsolutePath();
1727 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001728 try {
1729 os.close();
1730 } catch (IOException ioe) {
1731 // What the ... !
1732 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001733 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001734 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001735 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001736 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001737 }
1738
Amith Yamasani0b285492011-04-14 17:35:23 -07001739 /**
1740 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1741 * cache it elsewhere.
1742 * @return the array of user ids.
1743 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001744 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001745 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001746 return mUserIds;
1747 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001748 }
1749
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001750 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001751 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001752 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001753 return;
1754 }
1755 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001756 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001757 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001758 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001759 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001760 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001761 int type;
1762 while ((type = parser.next()) != XmlPullParser.START_TAG
1763 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001764 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001765 }
1766
1767 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001768 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001769 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001770 return;
1771 }
1772
Amith Yamasani2a003292012-08-14 18:25:45 -07001773 mNextSerialNumber = -1;
1774 if (parser.getName().equals(TAG_USERS)) {
1775 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1776 if (lastSerialNumber != null) {
1777 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1778 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001779 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1780 if (versionNumber != null) {
1781 mUserVersion = Integer.parseInt(versionNumber);
1782 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001783 }
1784
Pavel Grafov6a40f092016-10-25 15:46:51 +01001785 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1786 // currently), take care of it in case of upgrade.
1787 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001789 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301790 if (type == XmlPullParser.START_TAG) {
1791 final String name = parser.getName();
1792 if (name.equals(TAG_USER)) {
1793 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001794
Amith Yamasani12747872015-12-07 14:19:49 -08001795 UserData userData = readUserLP(Integer.parseInt(id));
1796
1797 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001798 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001799 mUsers.put(userData.info.id, userData);
1800 if (mNextSerialNumber < 0
1801 || mNextSerialNumber <= userData.info.id) {
1802 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001803 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301804 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001805 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301806 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001807 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1808 && type != XmlPullParser.END_TAG) {
1809 if (type == XmlPullParser.START_TAG) {
1810 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001811 synchronized (mGuestRestrictions) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001812 mGuestRestrictions.putAll(
1813 UserRestrictionsUtils.readRestrictions(parser));
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001814 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001815 }
1816 break;
1817 }
1818 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001819 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1820 // Legacy name, should only be encountered when upgrading from pre-O.
1821 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001822 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1823 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001824 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001825 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001826 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1827 // Should only happen when upgrading from pre-O (version < 7).
1828 oldDevicePolicyGlobalUserRestrictions =
1829 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001830 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001831 }
1832 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001833
Fyodor Kupolov82402752015-10-28 14:54:51 -07001834 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001835 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001836 } catch (IOException | XmlPullParserException e) {
1837 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001838 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001839 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001840 }
1841 }
1842
Amith Yamasani6f34b412012-10-22 18:19:27 -07001843 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001844 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001845 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001846 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001847 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001848 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001849 int userVersion = mUserVersion;
1850 if (userVersion < 1) {
1851 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001852 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1853 if ("Primary".equals(userData.info.name)) {
1854 userData.info.name =
1855 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1856 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001857 }
1858 userVersion = 1;
1859 }
1860
Amith Yamasanibc9625052012-11-15 14:39:18 -08001861 if (userVersion < 2) {
1862 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001863 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1864 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1865 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1866 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001867 }
1868 userVersion = 2;
1869 }
1870
Amith Yamasani350962c2013-08-06 11:18:53 -07001871
Amith Yamasani5e486f52013-08-07 11:06:44 -07001872 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001873 userVersion = 4;
1874 }
1875
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001876 if (userVersion < 5) {
1877 initDefaultGuestRestrictions();
1878 userVersion = 5;
1879 }
1880
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001881 if (userVersion < 6) {
1882 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001883 synchronized (mUsersLock) {
1884 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001885 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001886 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001887 if (!splitSystemUser && userData.info.isRestricted()
1888 && (userData.info.restrictedProfileParentId
1889 == UserInfo.NO_PROFILE_GROUP_ID)) {
1890 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1891 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001892 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001893 }
1894 }
1895 userVersion = 6;
1896 }
1897
Pavel Grafov6a40f092016-10-25 15:46:51 +01001898 if (userVersion < 7) {
1899 // Previously only one user could enforce global restrictions, now it is per-user.
1900 synchronized (mRestrictionsLock) {
1901 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1902 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1903 mDevicePolicyGlobalUserRestrictions.put(
1904 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1905 }
1906 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1907 // it from local to global bundle for all users who set it.
1908 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1909 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1910 );
1911 }
1912 userVersion = 7;
1913 }
1914
Amith Yamasani6f34b412012-10-22 18:19:27 -07001915 if (userVersion < USER_VERSION) {
1916 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1917 + USER_VERSION);
1918 } else {
1919 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001920
1921 if (originalVersion < mUserVersion) {
1922 writeUserListLP();
1923 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001924 }
1925 }
1926
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001927 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001928 int flags = UserInfo.FLAG_INITIALIZED;
1929 // In split system user mode, the admin and primary flags are assigned to the first human
1930 // user.
1931 if (!UserManager.isSplitSystemUser()) {
1932 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1933 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001934 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001935 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001936 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001937 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001938 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001939
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001940 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001941 try {
1942 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1943 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1944 for (String userRestriction : defaultFirstUserRestrictions) {
1945 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1946 restrictions.putBoolean(userRestriction, true);
1947 }
1948 }
1949 } catch (Resources.NotFoundException e) {
1950 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1951 }
1952
Pavel Grafov6a40f092016-10-25 15:46:51 +01001953 if (!restrictions.isEmpty()) {
1954 synchronized (mRestrictionsLock) {
1955 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1956 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001957 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001958
Fyodor Kupolov82402752015-10-28 14:54:51 -07001959 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001960 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001961
Amith Yamasani12747872015-12-07 14:19:49 -08001962 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001963 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001964 }
1965
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001966 private String getOwnerName() {
1967 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1968 }
1969
Amith Yamasani12747872015-12-07 14:19:49 -08001970 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001971 if (DBG) {
1972 debug("scheduleWriteUser");
1973 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001974 // No need to wrap it within a lock -- worst case, we'll just post the same message
1975 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001976 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1977 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001978 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1979 }
1980 }
1981
Amith Yamasani12747872015-12-07 14:19:49 -08001982 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001983 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001984 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001985 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001986 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001987 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001988 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001989 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001990 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001991 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001992 userFile.finishWrite(fos);
1993 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001994 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001995 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001996 }
1997 }
1998
1999 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002000 * Writes the user file in this format:
2001 *
2002 * <user flags="20039023" id="0">
2003 * <name>Primary</name>
2004 * </user>
2005 */
2006 @VisibleForTesting
2007 void writeUserLP(UserData userData, OutputStream os)
2008 throws IOException, XmlPullParserException {
2009 // XmlSerializer serializer = XmlUtils.serializerInstance();
2010 final XmlSerializer serializer = new FastXmlSerializer();
2011 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2012 serializer.startDocument(null, true);
2013 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2014
2015 final UserInfo userInfo = userData.info;
2016 serializer.startTag(null, TAG_USER);
2017 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2018 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2019 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2020 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2021 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2022 Long.toString(userInfo.lastLoggedInTime));
2023 if (userInfo.lastLoggedInFingerprint != null) {
2024 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2025 userInfo.lastLoggedInFingerprint);
2026 }
2027 if (userInfo.iconPath != null) {
2028 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2029 }
2030 if (userInfo.partial) {
2031 serializer.attribute(null, ATTR_PARTIAL, "true");
2032 }
2033 if (userInfo.guestToRemove) {
2034 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2035 }
2036 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2037 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2038 Integer.toString(userInfo.profileGroupId));
2039 }
2040 serializer.attribute(null, ATTR_PROFILE_BADGE,
2041 Integer.toString(userInfo.profileBadge));
2042 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2043 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2044 Integer.toString(userInfo.restrictedProfileParentId));
2045 }
2046 // Write seed data
2047 if (userData.persistSeedData) {
2048 if (userData.seedAccountName != null) {
2049 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2050 }
2051 if (userData.seedAccountType != null) {
2052 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2053 }
2054 }
2055 if (userInfo.name != null) {
2056 serializer.startTag(null, TAG_NAME);
2057 serializer.text(userInfo.name);
2058 serializer.endTag(null, TAG_NAME);
2059 }
2060 synchronized (mRestrictionsLock) {
2061 UserRestrictionsUtils.writeRestrictions(serializer,
2062 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2063 UserRestrictionsUtils.writeRestrictions(serializer,
2064 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2065 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002066 UserRestrictionsUtils.writeRestrictions(serializer,
2067 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2068 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002069 }
2070
2071 if (userData.account != null) {
2072 serializer.startTag(null, TAG_ACCOUNT);
2073 serializer.text(userData.account);
2074 serializer.endTag(null, TAG_ACCOUNT);
2075 }
2076
2077 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2078 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2079 userData.seedAccountOptions.saveToXml(serializer);
2080 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2081 }
2082
2083 serializer.endTag(null, TAG_USER);
2084
2085 serializer.endDocument();
2086 }
2087
2088 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002089 * Writes the user list file in this format:
2090 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002091 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002092 * <user id="0"></user>
2093 * <user id="2"></user>
2094 * </users>
2095 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002096 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002097 if (DBG) {
2098 debug("writeUserList");
2099 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002100 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002101 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002102 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002103 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002104 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2105
2106 // XmlSerializer serializer = XmlUtils.serializerInstance();
2107 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002108 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002109 serializer.startDocument(null, true);
2110 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2111
2112 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002113 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002114 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002115
Adam Lesinskieddeb492014-09-08 17:50:03 -07002116 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002117 synchronized (mGuestRestrictions) {
2118 UserRestrictionsUtils
2119 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2120 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302121 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002122 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2123 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2124 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002125 int[] userIdsToWrite;
2126 synchronized (mUsersLock) {
2127 userIdsToWrite = new int[mUsers.size()];
2128 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002129 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002130 userIdsToWrite[i] = user.id;
2131 }
2132 }
2133 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002134 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002135 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002136 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002137 }
2138
2139 serializer.endTag(null, TAG_USERS);
2140
2141 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002142 userListFile.finishWrite(fos);
2143 } catch (Exception e) {
2144 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002145 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002146 }
2147 }
2148
Amith Yamasani12747872015-12-07 14:19:49 -08002149 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002150 FileInputStream fis = null;
2151 try {
2152 AtomicFile userFile =
2153 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2154 fis = userFile.openRead();
2155 return readUserLP(id, fis);
2156 } catch (IOException ioe) {
2157 Slog.e(LOG_TAG, "Error reading user list");
2158 } catch (XmlPullParserException pe) {
2159 Slog.e(LOG_TAG, "Error reading user list");
2160 } finally {
2161 IoUtils.closeQuietly(fis);
2162 }
2163 return null;
2164 }
2165
2166 @VisibleForTesting
2167 UserData readUserLP(int id, InputStream is) throws IOException,
2168 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002169 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002170 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002171 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002172 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002173 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002174 long creationTime = 0L;
2175 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002176 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002177 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002178 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002179 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002180 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002181 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002182 boolean persistSeedData = false;
2183 String seedAccountName = null;
2184 String seedAccountType = null;
2185 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002186 Bundle baseRestrictions = null;
2187 Bundle localRestrictions = null;
2188 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002189
Kenny Guy02c89902016-11-15 19:36:38 +00002190 XmlPullParser parser = Xml.newPullParser();
2191 parser.setInput(is, StandardCharsets.UTF_8.name());
2192 int type;
2193 while ((type = parser.next()) != XmlPullParser.START_TAG
2194 && type != XmlPullParser.END_DOCUMENT) {
2195 // Skip
2196 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002197
Kenny Guy02c89902016-11-15 19:36:38 +00002198 if (type != XmlPullParser.START_TAG) {
2199 Slog.e(LOG_TAG, "Unable to read user " + id);
2200 return null;
2201 }
2202
2203 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2204 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2205 if (storedId != id) {
2206 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002207 return null;
2208 }
Kenny Guy02c89902016-11-15 19:36:38 +00002209 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2210 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2211 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2212 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2213 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2214 lastLoggedInFingerprint = parser.getAttributeValue(null,
2215 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2216 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2217 UserInfo.NO_PROFILE_GROUP_ID);
2218 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2219 restrictedProfileParentId = readIntAttribute(parser,
2220 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2221 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2222 if ("true".equals(valueString)) {
2223 partial = true;
2224 }
2225 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2226 if ("true".equals(valueString)) {
2227 guestToRemove = true;
2228 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002229
Kenny Guy02c89902016-11-15 19:36:38 +00002230 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2231 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2232 if (seedAccountName != null || seedAccountType != null) {
2233 persistSeedData = true;
2234 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002235
Kenny Guy02c89902016-11-15 19:36:38 +00002236 int outerDepth = parser.getDepth();
2237 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2238 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2239 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2240 continue;
2241 }
2242 String tag = parser.getName();
2243 if (TAG_NAME.equals(tag)) {
2244 type = parser.next();
2245 if (type == XmlPullParser.TEXT) {
2246 name = parser.getText();
2247 }
2248 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002249 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002250 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002251 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2252 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2253 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002254 } else if (TAG_ACCOUNT.equals(tag)) {
2255 type = parser.next();
2256 if (type == XmlPullParser.TEXT) {
2257 account = parser.getText();
2258 }
2259 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2260 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002261 persistSeedData = true;
2262 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002263 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002264 }
Kenny Guy02c89902016-11-15 19:36:38 +00002265
2266 // Create the UserInfo object that gets passed around
2267 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2268 userInfo.serialNumber = serialNumber;
2269 userInfo.creationTime = creationTime;
2270 userInfo.lastLoggedInTime = lastLoggedInTime;
2271 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2272 userInfo.partial = partial;
2273 userInfo.guestToRemove = guestToRemove;
2274 userInfo.profileGroupId = profileGroupId;
2275 userInfo.profileBadge = profileBadge;
2276 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2277
2278 // Create the UserData object that's internal to this class
2279 UserData userData = new UserData();
2280 userData.info = userInfo;
2281 userData.account = account;
2282 userData.seedAccountName = seedAccountName;
2283 userData.seedAccountType = seedAccountType;
2284 userData.persistSeedData = persistSeedData;
2285 userData.seedAccountOptions = seedAccountOptions;
2286
2287 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002288 if (baseRestrictions != null) {
2289 mBaseUserRestrictions.put(id, baseRestrictions);
2290 }
2291 if (localRestrictions != null) {
2292 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2293 }
2294 if (globalRestrictions != null) {
2295 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2296 }
Kenny Guy02c89902016-11-15 19:36:38 +00002297 }
2298 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002299 }
2300
Amith Yamasani920ace02012-09-20 22:15:37 -07002301 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2302 String valueString = parser.getAttributeValue(null, attr);
2303 if (valueString == null) return defaultValue;
2304 try {
2305 return Integer.parseInt(valueString);
2306 } catch (NumberFormatException nfe) {
2307 return defaultValue;
2308 }
2309 }
2310
2311 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2312 String valueString = parser.getAttributeValue(null, attr);
2313 if (valueString == null) return defaultValue;
2314 try {
2315 return Long.parseLong(valueString);
2316 } catch (NumberFormatException nfe) {
2317 return defaultValue;
2318 }
2319 }
2320
Amith Yamasanib82add22013-07-09 11:24:44 -07002321 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002322 * Removes the app restrictions file for a specific package and user id, if it exists.
2323 */
2324 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2325 synchronized (mPackagesLock) {
2326 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002327 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002328 if (resFile.exists()) {
2329 resFile.delete();
2330 }
2331 }
2332 }
2333
Kenny Guya52dc3e2014-02-11 15:33:14 +00002334 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002335 public UserInfo createProfileForUser(String name, int flags, int userId,
2336 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002337 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002338 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002339 }
2340
Amith Yamasani258848d2012-08-10 17:06:33 -07002341 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002342 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2343 String[] disallowedPackages) {
2344 checkManageOrCreateUsersPermission(flags);
2345 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2346 }
2347
2348 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002349 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2350 checkManageOrCreateUsersPermission("Only the system can remove users");
2351 return removeUserUnchecked(userHandle);
2352 }
2353
2354 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002355 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002356 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002357 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002358 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002359
Jessica Hummelbe81c802014-04-22 15:49:22 +01002360 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002361 return createUserInternal(name, flags, parentId, null);
2362 }
2363
2364 private UserInfo createUserInternal(String name, int flags, int parentId,
2365 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002366 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2367 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2368 : UserManager.DISALLOW_ADD_USER;
2369 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2370 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002371 return null;
2372 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002373 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2374 }
2375
2376 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2377 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002378 DeviceStorageMonitorInternal dsm = LocalServices
2379 .getService(DeviceStorageMonitorInternal.class);
2380 if (dsm.isMemoryLow()) {
2381 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2382 return null;
2383 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002384 if (ActivityManager.isLowRamDeviceStatic()) {
2385 return null;
2386 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002387 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002388 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002389 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002390 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002391 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002392 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002393 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002394 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002395 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002396 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002397 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002398 if (parentId != UserHandle.USER_NULL) {
2399 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002400 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002401 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002402 if (parent == null) return null;
2403 }
2404 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2405 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2406 return null;
2407 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002408 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2409 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002410 // been reached, cannot add a user.
2411 return null;
2412 }
2413 // If we're adding a guest and there already exists one, bail.
2414 if (isGuest && findCurrentGuestUser() != null) {
2415 return null;
2416 }
2417 // In legacy mode, restricted profile's parent can only be the owner user
2418 if (isRestricted && !UserManager.isSplitSystemUser()
2419 && (parentId != UserHandle.USER_SYSTEM)) {
2420 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2421 return null;
2422 }
2423 if (isRestricted && UserManager.isSplitSystemUser()) {
2424 if (parent == null) {
2425 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2426 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002427 return null;
2428 }
Amith Yamasani12747872015-12-07 14:19:49 -08002429 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002430 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2431 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002432 return null;
2433 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002434 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002435 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2436 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002437 Log.e(LOG_TAG,
2438 "Ephemeral users are supported on split-system-user systems only.");
2439 return null;
2440 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002441 // In split system user mode, we assign the first human user the primary flag.
2442 // And if there is no device owner, we also assign the admin flag to primary user.
2443 if (UserManager.isSplitSystemUser()
2444 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2445 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002446 synchronized (mUsersLock) {
2447 if (!mIsDeviceManaged) {
2448 flags |= UserInfo.FLAG_ADMIN;
2449 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002450 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002451 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002452
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002453 userId = getNextAvailableId();
2454 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002455 boolean ephemeralGuests = Resources.getSystem()
2456 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002457
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002458 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002459 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2460 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2461 || (parent != null && parent.info.isEphemeral())) {
2462 flags |= UserInfo.FLAG_EPHEMERAL;
2463 }
2464
2465 userInfo = new UserInfo(userId, name, null, flags);
2466 userInfo.serialNumber = mNextSerialNumber++;
2467 long now = System.currentTimeMillis();
2468 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2469 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002470 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002471 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2472 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2473 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002474 userData = new UserData();
2475 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002476 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002477 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002478 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002479 writeUserListLP();
2480 if (parent != null) {
2481 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002482 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2483 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002484 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002485 }
Amith Yamasani12747872015-12-07 14:19:49 -08002486 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002487 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002488 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2489 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002490 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002491 }
Amith Yamasani12747872015-12-07 14:19:49 -08002492 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002493 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002494 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002495 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002496 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002497 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002498 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002499 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002500 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002501 userInfo.partial = false;
2502 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002503 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002504 }
2505 updateUserIds();
2506 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002507 if (isGuest) {
2508 synchronized (mGuestRestrictions) {
2509 restrictions.putAll(mGuestRestrictions);
2510 }
2511 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002512 synchronized (mRestrictionsLock) {
2513 mBaseUserRestrictions.append(userId, restrictions);
2514 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002515 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002516 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2517 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2518 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2519 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002520 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002521 } finally {
2522 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002523 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002524 return userInfo;
2525 }
2526
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002527 @VisibleForTesting
2528 UserData putUserInfo(UserInfo userInfo) {
2529 final UserData userData = new UserData();
2530 userData.info = userInfo;
2531 synchronized (mUsers) {
2532 mUsers.put(userInfo.id, userData);
2533 }
2534 return userData;
2535 }
2536
2537 @VisibleForTesting
2538 void removeUserInfo(int userId) {
2539 synchronized (mUsers) {
2540 mUsers.remove(userId);
2541 }
2542 }
2543
Amith Yamasani0b285492011-04-14 17:35:23 -07002544 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002545 * @hide
2546 */
Amith Yamasani12747872015-12-07 14:19:49 -08002547 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002548 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002549 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002550 final UserInfo user = createProfileForUser(
2551 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002552 if (user == null) {
2553 return null;
2554 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002555 long identity = Binder.clearCallingIdentity();
2556 try {
2557 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2558 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2559 // the putIntForUser() will fail.
2560 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2561 android.provider.Settings.Secure.LOCATION_MODE,
2562 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2563 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2564 } finally {
2565 Binder.restoreCallingIdentity(identity);
2566 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002567 return user;
2568 }
2569
2570 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002571 * Find the current guest user. If the Guest user is partial,
2572 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002573 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002574 private UserInfo findCurrentGuestUser() {
2575 synchronized (mUsersLock) {
2576 final int size = mUsers.size();
2577 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002578 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002579 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2580 return user;
2581 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002582 }
2583 }
2584 return null;
2585 }
2586
2587 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002588 * Mark this guest user for deletion to allow us to create another guest
2589 * and switch to that user before actually removing this guest.
2590 * @param userHandle the userid of the current guest
2591 * @return whether the user could be marked for deletion
2592 */
Amith Yamasani12747872015-12-07 14:19:49 -08002593 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002594 public boolean markGuestForDeletion(int userHandle) {
2595 checkManageUsersPermission("Only the system can remove users");
2596 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2597 UserManager.DISALLOW_REMOVE_USER, false)) {
2598 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2599 return false;
2600 }
2601
2602 long ident = Binder.clearCallingIdentity();
2603 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002604 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002605 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002606 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002607 userData = mUsers.get(userHandle);
2608 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002609 return false;
2610 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002611 }
Amith Yamasani12747872015-12-07 14:19:49 -08002612 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002613 return false;
2614 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002615 // We set this to a guest user that is to be removed. This is a temporary state
2616 // where we are allowed to add new Guest users, even if this one is still not
2617 // removed. This user will still show up in getUserInfo() calls.
2618 // If we don't get around to removing this Guest user, it will be purged on next
2619 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002620 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002621 // Mark it as disabled, so that it isn't returned any more when
2622 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002623 userData.info.flags |= UserInfo.FLAG_DISABLED;
2624 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002625 }
2626 } finally {
2627 Binder.restoreCallingIdentity(ident);
2628 }
2629 return true;
2630 }
2631
2632 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002633 * Removes a user and all data directories created for that user. This method should be called
2634 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002635 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002636 */
Amith Yamasani12747872015-12-07 14:19:49 -08002637 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002638 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002639 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002640 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002641
2642 final boolean isManagedProfile;
2643 synchronized (mUsersLock) {
2644 UserInfo userInfo = getUserInfoLU(userHandle);
2645 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2646 }
2647 String restriction = isManagedProfile
2648 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2649 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2650 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002651 return false;
2652 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002653 return removeUserUnchecked(userHandle);
2654 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002655
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002656 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002657 long ident = Binder.clearCallingIdentity();
2658 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002659 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002660 int currentUser = ActivityManager.getCurrentUser();
2661 if (currentUser == userHandle) {
2662 Log.w(LOG_TAG, "Current user cannot be removed");
2663 return false;
2664 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002665 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002666 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002667 userData = mUsers.get(userHandle);
2668 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002669 return false;
2670 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002671
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002672 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002673 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002674
Kenny Guyee58b4f2014-05-23 15:19:53 +01002675 try {
2676 mAppOpsService.removeUser(userHandle);
2677 } catch (RemoteException e) {
2678 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2679 }
2680 // Set this to a partially created user, so that the user will be purged
2681 // on next startup, in case the runtime stops now before stopping and
2682 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002683 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002684 // Mark it as disabled, so that it isn't returned any more when
2685 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002686 userData.info.flags |= UserInfo.FLAG_DISABLED;
2687 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002688 }
2689
Amith Yamasani12747872015-12-07 14:19:49 -08002690 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2691 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002692 // Send broadcast to notify system that the user removed was a
2693 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002694 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002695 }
2696
2697 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2698 int res;
2699 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002700 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002701 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002702 @Override
2703 public void userStopped(int userId) {
2704 finishRemoveUser(userId);
2705 }
2706 @Override
2707 public void userStopAborted(int userId) {
2708 }
2709 });
2710 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002711 return false;
2712 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002713 return res == ActivityManager.USER_OP_SUCCESS;
2714 } finally {
2715 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002716 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002717 }
2718
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002719 @VisibleForTesting
2720 void addRemovingUserIdLocked(int userId) {
2721 // We remember deleted user IDs to prevent them from being
2722 // reused during the current boot; they can still be reused
2723 // after a reboot or recycling of userIds.
2724 mRemovingUserIds.put(userId, true);
2725 mRecentlyRemovedIds.add(userId);
2726 // Keep LRU queue of recently removed IDs for recycling
2727 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2728 mRecentlyRemovedIds.removeFirst();
2729 }
2730 }
2731
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002732 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002733 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002734 // Let other services shutdown any activity and clean up their state before completely
2735 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002736 long ident = Binder.clearCallingIdentity();
2737 try {
2738 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2739 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002740 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2741 android.Manifest.permission.MANAGE_USERS,
2742
2743 new BroadcastReceiver() {
2744 @Override
2745 public void onReceive(Context context, Intent intent) {
2746 if (DBG) {
2747 Slog.i(LOG_TAG,
2748 "USER_REMOVED broadcast sent, cleaning up user data "
2749 + userHandle);
2750 }
2751 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002752 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002753 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002754 // Clean up any ActivityManager state
2755 LocalServices.getService(ActivityManagerInternal.class)
2756 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002757 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002758 }
2759 }.start();
2760 }
2761 },
2762
2763 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002764 } finally {
2765 Binder.restoreCallingIdentity(ident);
2766 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002767 }
2768
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002769 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002770 try {
2771 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2772 } catch (IllegalStateException e) {
2773 // This may be simply because the user was partially created.
2774 Slog.i(LOG_TAG,
2775 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2776 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002777
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002778 // Cleanup gatekeeper secure user id
2779 try {
2780 final IGateKeeperService gk = GateKeeper.getService();
2781 if (gk != null) {
2782 gk.clearSecureUserId(userHandle);
2783 }
2784 } catch (Exception ex) {
2785 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2786 }
2787
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002788 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002789 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002790
2791 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002792 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002793 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2794
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002795 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002796 synchronized (mUsersLock) {
2797 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002798 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002799 }
2800 synchronized (mUserStates) {
2801 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002802 }
2803 synchronized (mRestrictionsLock) {
2804 mBaseUserRestrictions.remove(userHandle);
2805 mAppliedUserRestrictions.remove(userHandle);
2806 mCachedEffectiveUserRestrictions.remove(userHandle);
2807 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002808 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2809 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2810 applyUserRestrictionsForAllUsersLR();
2811 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002812 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002813 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002814 synchronized (mPackagesLock) {
2815 writeUserListLP();
2816 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002817 // Remove user file
2818 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2819 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002820 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002821 if (RELEASE_DELETED_USER_ID) {
2822 synchronized (mUsers) {
2823 mRemovingUserIds.delete(userHandle);
2824 }
2825 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002826 }
2827
Kenny Guyf8d3a232014-05-15 16:09:52 +01002828 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002829 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002830 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2831 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002832 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002833 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002834 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002835 }
2836
Amith Yamasani2a003292012-08-14 18:25:45 -07002837 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002838 public Bundle getApplicationRestrictions(String packageName) {
2839 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2840 }
2841
2842 @Override
2843 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002844 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002845 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002846 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002847 }
2848 synchronized (mPackagesLock) {
2849 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002850 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002851 }
2852 }
2853
2854 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002855 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002856 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002857 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002858 if (restrictions != null) {
2859 restrictions.setDefusable(true);
2860 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002861 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002862 if (restrictions == null || restrictions.isEmpty()) {
2863 cleanAppRestrictionsForPackage(packageName, userId);
2864 } else {
2865 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002866 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002867 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002868 }
Robin Lee66e5d962014-04-09 16:44:21 +01002869
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002870 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2871 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2872 changeIntent.setPackage(packageName);
2873 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2874 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002875 }
2876
2877 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002878 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002879 try {
2880 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002881 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002882 } catch (NameNotFoundException nnfe) {
2883 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002884 } finally {
2885 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002886 }
2887 }
2888
Fyodor Kupolov82402752015-10-28 14:54:51 -07002889 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002890 AtomicFile restrictionsFile =
2891 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2892 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002893 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002894 }
2895
2896 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002897 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002898 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002899 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002900 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002901 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002902 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002903
2904 FileInputStream fis = null;
2905 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002906 fis = restrictionsFile.openRead();
2907 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002908 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002909 XmlUtils.nextElement(parser);
2910 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002911 Slog.e(LOG_TAG, "Unable to read restrictions file "
2912 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002913 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002914 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002915 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2916 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002917 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002918 } catch (IOException|XmlPullParserException e) {
2919 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002920 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002921 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002922 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002923 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002924 }
2925
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002926 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2927 XmlPullParser parser) throws XmlPullParserException, IOException {
2928 int type = parser.getEventType();
2929 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2930 String key = parser.getAttributeValue(null, ATTR_KEY);
2931 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2932 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2933 if (multiple != null) {
2934 values.clear();
2935 int count = Integer.parseInt(multiple);
2936 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2937 if (type == XmlPullParser.START_TAG
2938 && parser.getName().equals(TAG_VALUE)) {
2939 values.add(parser.nextText().trim());
2940 count--;
2941 }
2942 }
2943 String [] valueStrings = new String[values.size()];
2944 values.toArray(valueStrings);
2945 restrictions.putStringArray(key, valueStrings);
2946 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2947 restrictions.putBundle(key, readBundleEntry(parser, values));
2948 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2949 final int outerDepth = parser.getDepth();
2950 ArrayList<Bundle> bundleList = new ArrayList<>();
2951 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2952 Bundle childBundle = readBundleEntry(parser, values);
2953 bundleList.add(childBundle);
2954 }
2955 restrictions.putParcelableArray(key,
2956 bundleList.toArray(new Bundle[bundleList.size()]));
2957 } else {
2958 String value = parser.nextText().trim();
2959 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2960 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2961 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2962 restrictions.putInt(key, Integer.parseInt(value));
2963 } else {
2964 restrictions.putString(key, value);
2965 }
2966 }
2967 }
2968 }
2969
2970 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2971 throws IOException, XmlPullParserException {
2972 Bundle childBundle = new Bundle();
2973 final int outerDepth = parser.getDepth();
2974 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2975 readEntry(childBundle, values, parser);
2976 }
2977 return childBundle;
2978 }
2979
Fyodor Kupolov82402752015-10-28 14:54:51 -07002980 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002981 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002982 AtomicFile restrictionsFile = new AtomicFile(
2983 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002984 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002985 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002986 }
2987
2988 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002989 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002990 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002991 try {
2992 fos = restrictionsFile.startWrite();
2993 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2994
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002995 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002996 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002997 serializer.startDocument(null, true);
2998 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2999
3000 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003001 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003002 serializer.endTag(null, TAG_RESTRICTIONS);
3003
3004 serializer.endDocument();
3005 restrictionsFile.finishWrite(fos);
3006 } catch (Exception e) {
3007 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003008 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3009 }
3010 }
3011
3012 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3013 throws IOException {
3014 for (String key : restrictions.keySet()) {
3015 Object value = restrictions.get(key);
3016 serializer.startTag(null, TAG_ENTRY);
3017 serializer.attribute(null, ATTR_KEY, key);
3018
3019 if (value instanceof Boolean) {
3020 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3021 serializer.text(value.toString());
3022 } else if (value instanceof Integer) {
3023 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3024 serializer.text(value.toString());
3025 } else if (value == null || value instanceof String) {
3026 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3027 serializer.text(value != null ? (String) value : "");
3028 } else if (value instanceof Bundle) {
3029 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3030 writeBundle((Bundle) value, serializer);
3031 } else if (value instanceof Parcelable[]) {
3032 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3033 Parcelable[] array = (Parcelable[]) value;
3034 for (Parcelable parcelable : array) {
3035 if (!(parcelable instanceof Bundle)) {
3036 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3037 }
3038 serializer.startTag(null, TAG_ENTRY);
3039 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3040 writeBundle((Bundle) parcelable, serializer);
3041 serializer.endTag(null, TAG_ENTRY);
3042 }
3043 } else {
3044 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3045 String[] values = (String[]) value;
3046 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3047 for (String choice : values) {
3048 serializer.startTag(null, TAG_VALUE);
3049 serializer.text(choice != null ? choice : "");
3050 serializer.endTag(null, TAG_VALUE);
3051 }
3052 }
3053 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003054 }
3055 }
3056
3057 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003058 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003059 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003060 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003061 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003062 }
3063 }
3064
3065 @Override
3066 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003067 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003068 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003069 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003070 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003071 }
3072 // Not found
3073 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003074 }
3075 }
3076
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003077 @Override
3078 public long getUserCreationTime(int userHandle) {
3079 int callingUserId = UserHandle.getCallingUserId();
3080 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003081 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003082 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003083 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003084 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003085 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003086 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003087 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003088 }
3089 }
3090 }
3091 if (userInfo == null) {
3092 throw new SecurityException("userHandle can only be the calling user or a managed "
3093 + "profile associated with this user");
3094 }
3095 return userInfo.creationTime;
3096 }
3097
Amith Yamasani0b285492011-04-14 17:35:23 -07003098 /**
3099 * Caches the list of user ids in an array, adjusting the array size when necessary.
3100 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003101 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003102 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003103 synchronized (mUsersLock) {
3104 final int userSize = mUsers.size();
3105 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003106 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003107 num++;
3108 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003109 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003110 final int[] newUsers = new int[num];
3111 int n = 0;
3112 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003113 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003114 newUsers[n++] = mUsers.keyAt(i);
3115 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003116 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003117 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003118 }
3119 }
3120
3121 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003122 * Called right before a user is started. This gives us a chance to prepare
3123 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003124 */
3125 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003126 UserInfo userInfo = getUserInfo(userId);
3127 if (userInfo == null) {
3128 return;
3129 }
3130 final int userSerial = userInfo.serialNumber;
3131 // Migrate only if build fingerprints mismatch
3132 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003133 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003134 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003135
3136 if (userId != UserHandle.USER_SYSTEM) {
3137 synchronized (mRestrictionsLock) {
3138 applyUserRestrictionsLR(userId);
3139 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003140 }
3141 }
3142
3143 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003144 * Called right before a user is unlocked. This gives us a chance to prepare
3145 * app storage.
3146 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003147 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003148 UserInfo userInfo = getUserInfo(userId);
3149 if (userInfo == null) {
3150 return;
3151 }
3152 final int userSerial = userInfo.serialNumber;
3153 // Migrate only if build fingerprints mismatch
3154 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003155 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003156 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003157 }
3158
3159 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003160 * Examine all users present on given mounted volume, and destroy data
3161 * belonging to users that are no longer valid, or whose user ID has been
3162 * recycled.
3163 */
3164 void reconcileUsers(String volumeUuid) {
3165 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3166 }
3167
3168 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003169 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003170 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003171 * @param userId the user that was just foregrounded
3172 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003173 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003174 UserData userData = getUserDataNoChecks(userId);
3175 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003176 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3177 return;
3178 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003179
3180 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003181 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003182 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003183 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003184 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3185 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003186 }
3187
3188 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003189 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003190 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003191 @VisibleForTesting
3192 int getNextAvailableId() {
3193 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003194 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003195 nextId = scanNextAvailableIdLocked();
3196 if (nextId >= 0) {
3197 return nextId;
3198 }
3199 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3200 // except most recently removed
3201 if (mRemovingUserIds.size() > 0) {
3202 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3203 mRemovingUserIds.clear();
3204 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3205 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003206 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003207 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003208 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003209 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003210 if (nextId < 0) {
3211 throw new IllegalStateException("No user id available!");
3212 }
3213 return nextId;
3214 }
3215
3216 private int scanNextAvailableIdLocked() {
3217 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3218 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3219 return i;
3220 }
3221 }
3222 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003223 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003224
Amith Yamasanifc95e702013-09-26 13:20:17 -07003225 private String packageToRestrictionsFileName(String packageName) {
3226 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3227 }
3228
Amith Yamasani920ace02012-09-20 22:15:37 -07003229 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003230 public void setSeedAccountData(int userId, String accountName, String accountType,
3231 PersistableBundle accountOptions, boolean persist) {
3232 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3233 synchronized (mPackagesLock) {
3234 final UserData userData;
3235 synchronized (mUsersLock) {
3236 userData = getUserDataLU(userId);
3237 if (userData == null) {
3238 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3239 return;
3240 }
3241 userData.seedAccountName = accountName;
3242 userData.seedAccountType = accountType;
3243 userData.seedAccountOptions = accountOptions;
3244 userData.persistSeedData = persist;
3245 }
3246 if (persist) {
3247 writeUserLP(userData);
3248 }
3249 }
3250 }
3251
3252 @Override
3253 public String getSeedAccountName() throws RemoteException {
3254 checkManageUsersPermission("Cannot get seed account information");
3255 synchronized (mUsersLock) {
3256 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3257 return userData.seedAccountName;
3258 }
3259 }
3260
3261 @Override
3262 public String getSeedAccountType() throws RemoteException {
3263 checkManageUsersPermission("Cannot get seed account information");
3264 synchronized (mUsersLock) {
3265 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3266 return userData.seedAccountType;
3267 }
3268 }
3269
3270 @Override
3271 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3272 checkManageUsersPermission("Cannot get seed account information");
3273 synchronized (mUsersLock) {
3274 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3275 return userData.seedAccountOptions;
3276 }
3277 }
3278
3279 @Override
3280 public void clearSeedAccountData() throws RemoteException {
3281 checkManageUsersPermission("Cannot clear seed account information");
3282 synchronized (mPackagesLock) {
3283 UserData userData;
3284 synchronized (mUsersLock) {
3285 userData = getUserDataLU(UserHandle.getCallingUserId());
3286 if (userData == null) return;
3287 userData.clearSeedAccountData();
3288 }
3289 writeUserLP(userData);
3290 }
3291 }
3292
3293 @Override
3294 public boolean someUserHasSeedAccount(String accountName, String accountType)
3295 throws RemoteException {
3296 checkManageUsersPermission("Cannot check seed account information");
3297 synchronized (mUsersLock) {
3298 final int userSize = mUsers.size();
3299 for (int i = 0; i < userSize; i++) {
3300 final UserData data = mUsers.valueAt(i);
3301 if (data.info.isInitialized()) continue;
3302 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3303 continue;
3304 }
3305 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3306 continue;
3307 }
3308 return true;
3309 }
3310 }
3311 return false;
3312 }
3313
3314 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003315 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003316 FileDescriptor err, String[] args, ShellCallback callback,
3317 ResultReceiver resultReceiver) {
3318 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003319 }
3320
3321 int onShellCommand(Shell shell, String cmd) {
3322 if (cmd == null) {
3323 return shell.handleDefaultCommands(cmd);
3324 }
3325
3326 final PrintWriter pw = shell.getOutPrintWriter();
3327 try {
3328 switch(cmd) {
3329 case "list":
3330 return runList(pw);
3331 }
3332 } catch (RemoteException e) {
3333 pw.println("Remote exception: " + e);
3334 }
3335 return -1;
3336 }
3337
3338 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003339 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003340 final List<UserInfo> users = getUsers(false);
3341 if (users == null) {
3342 pw.println("Error: couldn't get users");
3343 return 1;
3344 } else {
3345 pw.println("Users:");
3346 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003347 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003348 pw.println("\t" + users.get(i).toString() + running);
3349 }
3350 return 0;
3351 }
3352 }
3353
3354 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003355 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3356 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3357 != PackageManager.PERMISSION_GRANTED) {
3358 pw.println("Permission Denial: can't dump UserManager from from pid="
3359 + Binder.getCallingPid()
3360 + ", uid=" + Binder.getCallingUid()
3361 + " without permission "
3362 + android.Manifest.permission.DUMP);
3363 return;
3364 }
3365
3366 long now = System.currentTimeMillis();
3367 StringBuilder sb = new StringBuilder();
3368 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003369 synchronized (mUsersLock) {
3370 pw.println("Users:");
3371 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003372 UserData userData = mUsers.valueAt(i);
3373 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003374 continue;
3375 }
Amith Yamasani12747872015-12-07 14:19:49 -08003376 UserInfo userInfo = userData.info;
3377 final int userId = userInfo.id;
3378 pw.print(" "); pw.print(userInfo);
3379 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003380 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003381 pw.print(" <removing> ");
3382 }
Amith Yamasani12747872015-12-07 14:19:49 -08003383 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003384 pw.print(" <partial>");
3385 }
3386 pw.println();
3387 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003388 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003389 pw.println("<unknown>");
3390 } else {
3391 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003392 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003393 sb.append(" ago");
3394 pw.println(sb);
3395 }
3396 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003397 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003398 pw.println("<unknown>");
3399 } else {
3400 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003401 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003402 sb.append(" ago");
3403 pw.println(sb);
3404 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003405 pw.print(" Last logged in fingerprint: ");
3406 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003407 pw.print(" Has profile owner: ");
3408 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003409 pw.println(" Restrictions:");
3410 synchronized (mRestrictionsLock) {
3411 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003412 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003413 pw.println(" Device policy global restrictions:");
3414 UserRestrictionsUtils.dumpRestrictions(
3415 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003416 pw.println(" Device policy local restrictions:");
3417 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003418 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003419 pw.println(" Effective restrictions:");
3420 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003421 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003422 }
Amith Yamasani12747872015-12-07 14:19:49 -08003423
3424 if (userData.account != null) {
3425 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003426 pw.println();
3427 }
Amith Yamasani12747872015-12-07 14:19:49 -08003428
3429 if (userData.seedAccountName != null) {
3430 pw.print(" Seed account name: " + userData.seedAccountName);
3431 pw.println();
3432 if (userData.seedAccountType != null) {
3433 pw.print(" account type: " + userData.seedAccountType);
3434 pw.println();
3435 }
3436 if (userData.seedAccountOptions != null) {
3437 pw.print(" account options exist");
3438 pw.println();
3439 }
3440 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003441 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003442 }
Amith Yamasani12747872015-12-07 14:19:49 -08003443 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003444 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003445 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003446 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003447 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003448 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003449 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003450 synchronized (mUsersLock) {
3451 pw.println();
3452 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003453 if (mRemovingUserIds.size() > 0) {
3454 pw.println();
3455 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3456 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003457 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003458 synchronized (mUserStates) {
3459 pw.println(" Started users state: " + mUserStates);
3460 }
Amith Yamasani12747872015-12-07 14:19:49 -08003461 // Dump some capabilities
3462 pw.println();
3463 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3464 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003465 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3466 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003467 }
3468 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003469
3470 final class MainHandler extends Handler {
3471
3472 @Override
3473 public void handleMessage(Message msg) {
3474 switch (msg.what) {
3475 case WRITE_USER_MSG:
3476 removeMessages(WRITE_USER_MSG, msg.obj);
3477 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003478 int userId = ((UserData) msg.obj).info.id;
3479 UserData userData = getUserDataNoChecks(userId);
3480 if (userData != null) {
3481 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003482 }
3483 }
3484 }
3485 }
3486 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003487
3488 /**
3489 * @param userId
3490 * @return whether the user has been initialized yet
3491 */
3492 boolean isInitialized(int userId) {
3493 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3494 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003495
3496 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003497 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003498 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3499 boolean isDeviceOwner, int cameraRestrictionScope) {
3500 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3501 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003502 }
3503
3504 @Override
3505 public Bundle getBaseUserRestrictions(int userId) {
3506 synchronized (mRestrictionsLock) {
3507 return mBaseUserRestrictions.get(userId);
3508 }
3509 }
3510
3511 @Override
3512 public void setBaseUserRestrictionsByDpmsForMigration(
3513 int userId, Bundle baseRestrictions) {
3514 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003515 if (updateRestrictionsIfNeededLR(
3516 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3517 invalidateEffectiveUserRestrictionsLR(userId);
3518 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003519 }
3520
Amith Yamasani12747872015-12-07 14:19:49 -08003521 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003522 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003523 if (userData != null) {
3524 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003525 } else {
3526 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3527 }
3528 }
3529 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003530
3531 @Override
3532 public boolean getUserRestriction(int userId, String key) {
3533 return getUserRestrictions(userId).getBoolean(key);
3534 }
3535
3536 @Override
3537 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3538 synchronized (mUserRestrictionsListeners) {
3539 mUserRestrictionsListeners.add(listener);
3540 }
3541 }
3542
3543 @Override
3544 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3545 synchronized (mUserRestrictionsListeners) {
3546 mUserRestrictionsListeners.remove(listener);
3547 }
3548 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003549
3550 @Override
3551 public void setDeviceManaged(boolean isManaged) {
3552 synchronized (mUsersLock) {
3553 mIsDeviceManaged = isManaged;
3554 }
3555 }
3556
3557 @Override
3558 public void setUserManaged(int userId, boolean isManaged) {
3559 synchronized (mUsersLock) {
3560 mIsUserManaged.put(userId, isManaged);
3561 }
3562 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003563
3564 @Override
3565 public void setUserIcon(int userId, Bitmap bitmap) {
3566 long ident = Binder.clearCallingIdentity();
3567 try {
3568 synchronized (mPackagesLock) {
3569 UserData userData = getUserDataNoChecks(userId);
3570 if (userData == null || userData.info.partial) {
3571 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3572 return;
3573 }
3574 writeBitmapLP(userData.info, bitmap);
3575 writeUserLP(userData);
3576 }
3577 sendUserInfoChangedBroadcast(userId);
3578 } finally {
3579 Binder.restoreCallingIdentity(ident);
3580 }
3581 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003582
3583 @Override
3584 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3585 synchronized (mUsersLock) {
3586 mForceEphemeralUsers = forceEphemeralUsers;
3587 }
3588 }
3589
3590 @Override
3591 public void removeAllUsers() {
3592 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3593 // Remove the non-system users straight away.
3594 removeNonSystemUsers();
3595 } else {
3596 // Switch to the system user first and then remove the other users.
3597 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3598 @Override
3599 public void onReceive(Context context, Intent intent) {
3600 int userId =
3601 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3602 if (userId != UserHandle.USER_SYSTEM) {
3603 return;
3604 }
3605 mContext.unregisterReceiver(this);
3606 removeNonSystemUsers();
3607 }
3608 };
3609 IntentFilter userSwitchedFilter = new IntentFilter();
3610 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3611 mContext.registerReceiver(
3612 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3613
3614 // Switch to the system user.
3615 ActivityManager am =
3616 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3617 am.switchUser(UserHandle.USER_SYSTEM);
3618 }
3619 }
phweisse9c44062016-02-10 12:57:38 +01003620
3621 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003622 public void onEphemeralUserStop(int userId) {
3623 synchronized (mUsersLock) {
3624 UserInfo userInfo = getUserInfoLU(userId);
3625 if (userInfo != null && userInfo.isEphemeral()) {
3626 // Do not allow switching back to the ephemeral user again as the user is going
3627 // to be deleted.
3628 userInfo.flags |= UserInfo.FLAG_DISABLED;
3629 if (userInfo.isGuest()) {
3630 // Indicate that the guest will be deleted after it stops.
3631 userInfo.guestToRemove = true;
3632 }
3633 }
3634 }
3635 }
3636
3637 @Override
phweisse9c44062016-02-10 12:57:38 +01003638 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003639 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003640 // Keep this in sync with UserManager.createUser
3641 if (user != null && !user.isAdmin()) {
3642 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3643 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3644 }
3645 return user;
3646 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003647
3648 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003649 public boolean removeUserEvenWhenDisallowed(int userId) {
3650 return removeUserUnchecked(userId);
3651 }
3652
3653 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003654 public boolean isUserRunning(int userId) {
3655 synchronized (mUserStates) {
3656 return mUserStates.get(userId, -1) >= 0;
3657 }
3658 }
3659
3660 @Override
3661 public void setUserState(int userId, int userState) {
3662 synchronized (mUserStates) {
3663 mUserStates.put(userId, userState);
3664 }
3665 }
3666
3667 @Override
3668 public void removeUserState(int userId) {
3669 synchronized (mUserStates) {
3670 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003671 }
3672 }
3673
3674 @Override
3675 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003676 synchronized (mUserStates) {
3677 int state = mUserStates.get(userId, -1);
3678 return (state == UserState.STATE_RUNNING_UNLOCKING)
3679 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003680 }
3681 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003682
3683 @Override
3684 public boolean isUserUnlocked(int userId) {
3685 synchronized (mUserStates) {
3686 int state = mUserStates.get(userId, -1);
3687 return state == UserState.STATE_RUNNING_UNLOCKED;
3688 }
3689 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003690 }
3691
3692 /* Remove all the users except of the system one. */
3693 private void removeNonSystemUsers() {
3694 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3695 synchronized (mUsersLock) {
3696 final int userSize = mUsers.size();
3697 for (int i = 0; i < userSize; i++) {
3698 UserInfo ui = mUsers.valueAt(i).info;
3699 if (ui.id != UserHandle.USER_SYSTEM) {
3700 usersToRemove.add(ui);
3701 }
3702 }
3703 }
3704 for (UserInfo ui: usersToRemove) {
3705 removeUser(ui.id);
3706 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003707 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003708
3709 private class Shell extends ShellCommand {
3710 @Override
3711 public int onCommand(String cmd) {
3712 return onShellCommand(this, cmd);
3713 }
3714
3715 @Override
3716 public void onHelp() {
3717 final PrintWriter pw = getOutPrintWriter();
3718 pw.println("User manager (user) commands:");
3719 pw.println(" help");
3720 pw.println(" Print this help text.");
3721 pw.println("");
3722 pw.println(" list");
3723 pw.println(" Prints all users on the system.");
3724 }
3725 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003726
3727 private static void debug(String message) {
3728 Log.d(LOG_TAG, message +
3729 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3730 }
Kenny Guy02c89902016-11-15 19:36:38 +00003731
3732 @VisibleForTesting
3733 static int getMaxManagedProfiles() {
3734 // Allow overriding max managed profiles on debuggable builds for testing
3735 // of multiple profiles.
3736 if (!Build.IS_DEBUGGABLE) {
3737 return MAX_MANAGED_PROFILES;
3738 } else {
3739 return SystemProperties.getInt("persist.sys.max_profiles",
3740 MAX_MANAGED_PROFILES);
3741 }
3742 }
3743
3744 @VisibleForTesting
3745 int getFreeProfileBadgeLU(int parentUserId) {
3746 int maxManagedProfiles = getMaxManagedProfiles();
3747 boolean[] usedBadges = new boolean[maxManagedProfiles];
3748 final int userSize = mUsers.size();
3749 for (int i = 0; i < userSize; i++) {
3750 UserInfo ui = mUsers.valueAt(i).info;
3751 // Check which badge indexes are already used by this profile group.
3752 if (ui.isManagedProfile()
3753 && ui.profileGroupId == parentUserId
3754 && !mRemovingUserIds.get(ui.id)
3755 && ui.profileBadge < maxManagedProfiles) {
3756 usedBadges[ui.profileBadge] = true;
3757 }
3758 }
3759 for (int i = 0; i < maxManagedProfiles; i++) {
3760 if (!usedBadges[i]) {
3761 return i;
3762 }
3763 }
3764 return 0;
3765 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003766
3767 /**
3768 * Checks if the given user has a managed profile associated with it.
3769 * @param userId The parent user
3770 * @return
3771 */
3772 boolean hasManagedProfile(int userId) {
3773 synchronized (mUsersLock) {
3774 UserInfo userInfo = getUserInfoLU(userId);
3775 final int userSize = mUsers.size();
3776 for (int i = 0; i < userSize; i++) {
3777 UserInfo profile = mUsers.valueAt(i).info;
3778 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3779 return true;
3780 }
3781 }
3782 return false;
3783 }
3784 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003785}