blob: 455d3e4f0820a0d7a7f4c069bc6bafc5e8ed4a6a [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
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700221 private static final String XATTR_SERIAL = "user.serial";
222
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800223 // Tron counters
224 private static final String TRON_GUEST_CREATED = "users_guest_created";
225 private static final String TRON_USER_CREATED = "users_user_created";
226
Dianne Hackborn4428e172012-08-24 17:43:05 -0700227 private final Context mContext;
228 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800230 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700231 // Short-term lock for internal state, when interaction/sync with PM is not required
232 private final Object mUsersLock = new Object();
233 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700234
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800235 private final Handler mHandler;
236
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700237 private final File mUsersDir;
238 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700239
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800240 private static final IBinder mUserRestriconToken = new Binder();
241
Makoto Onuki068c54a2015-10-13 14:34:03 -0700242 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800243 * User-related information that is used for persisting to flash. Only UserInfo is
244 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800245 */
Kenny Guy02c89902016-11-15 19:36:38 +0000246 @VisibleForTesting
247 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800248 // Basic user information and properties
249 UserInfo info;
250 // Account name used when there is a strong association between a user and an account
251 String account;
252 // Account information for seeding into a newly created user. This could also be
253 // used for login validation for an existing user, for updating their credentials.
254 // In the latter case, data may not need to be persisted as it is only valid for the
255 // current login session.
256 String seedAccountName;
257 String seedAccountType;
258 PersistableBundle seedAccountOptions;
259 // Whether to perist the seed account information to be available after a boot
260 boolean persistSeedData;
261
262 void clearSeedAccountData() {
263 seedAccountName = null;
264 seedAccountType = null;
265 seedAccountOptions = null;
266 persistSeedData = false;
267 }
268 }
269
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800270 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800271 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800272
273 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700274 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100275 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700276 *
277 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
278 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
279 * maybe shared between {@link #mBaseUserRestrictions} and
280 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
281 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700282 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700283 */
284 @GuardedBy("mRestrictionsLock")
285 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
286
287 /**
288 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
289 * with device / profile owner restrictions. We'll initialize it lazily; use
290 * {@link #getEffectiveUserRestrictions} to access it.
291 *
292 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
293 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
294 * maybe shared between {@link #mBaseUserRestrictions} and
295 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
296 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700297 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700298 */
299 @GuardedBy("mRestrictionsLock")
300 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
301
Makoto Onuki4f160732015-10-27 17:15:38 -0700302 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800303 * User restrictions that have already been applied in
304 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
305 * that have changed since the last
306 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700307 */
308 @GuardedBy("mRestrictionsLock")
309 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
310
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800311 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800312 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100313 * that should be applied to all users, including guests. Only non-empty restriction bundles are
314 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800315 */
316 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100317 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800318
319 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100320 * Id of the user that set global restrictions.
321 */
322 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100323 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100324
325 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800326 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100327 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800328 */
329 @GuardedBy("mRestrictionsLock")
330 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
331
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800332 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530333 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800334
335 /**
336 * Set of user IDs being actively removed. Removed IDs linger in this set
337 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700338 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800339 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700340 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800341 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700342
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700343 /**
344 * Queue of recently removed userIds. Used for recycling of userIds
345 */
346 @GuardedBy("mUsersLock")
347 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
348
Fyodor Kupolov82402752015-10-28 14:54:51 -0700349 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700350 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800351 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700352 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700353 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700354
Jason Monk62062992014-05-06 09:55:28 -0400355 private IAppOpsService mAppOpsService;
356
Makoto Onuki068c54a2015-10-13 14:34:03 -0700357 private final LocalService mLocalService;
358
Makoto Onukie7927da2015-11-25 10:05:17 -0800359 @GuardedBy("mUsersLock")
360 private boolean mIsDeviceManaged;
361
362 @GuardedBy("mUsersLock")
363 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
364
Makoto Onukid45a4a22015-11-02 17:17:38 -0800365 @GuardedBy("mUserRestrictionsListeners")
366 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
367 new ArrayList<>();
368
Clara Bayarria1771112015-12-18 16:29:18 +0000369 private final LockPatternUtils mLockPatternUtils;
370
Ricky Waib1dd80b2016-06-07 18:00:55 +0100371 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
372 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
373
374 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
375 @Override
376 public void onReceive(Context context, Intent intent) {
377 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
378 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
379 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
380 setQuietModeEnabled(userHandle, false);
381 if (target != null) {
382 try {
383 mContext.startIntentSender(target, null, 0, 0, 0);
384 } catch (IntentSender.SendIntentException e) {
385 /* ignore */
386 }
387 }
388 }
389 }
390 };
391
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100392 /**
393 * Whether all users should be created ephemeral.
394 */
395 @GuardedBy("mUsersLock")
396 private boolean mForceEphemeralUsers;
397
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000398 @GuardedBy("mUserStates")
399 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700400
Amith Yamasani258848d2012-08-10 17:06:33 -0700401 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700402
Dianne Hackborn4428e172012-08-24 17:43:05 -0700403 public static UserManagerService getInstance() {
404 synchronized (UserManagerService.class) {
405 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700406 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700407 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700408
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700409 public static class LifeCycle extends SystemService {
410
411 private UserManagerService mUms;
412
413 /**
414 * @param context
415 */
416 public LifeCycle(Context context) {
417 super(context);
418 }
419
420 @Override
421 public void onStart() {
422 mUms = UserManagerService.getInstance();
423 publishBinderService(Context.USER_SERVICE, mUms);
424 }
425
426 @Override
427 public void onBootPhase(int phase) {
428 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
429 mUms.cleanupPartialUsers();
430 }
431 }
432 }
433
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700434 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800435 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700436 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800437 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700438 }
439
Dianne Hackborn4428e172012-08-24 17:43:05 -0700440 /**
441 * Called by package manager to create the service. This is closely
442 * associated with the package manager, and the given lock is the
443 * package manager's own lock.
444 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800445 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
446 Object packagesLock) {
447 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700448 }
449
Dianne Hackborn4428e172012-08-24 17:43:05 -0700450 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800451 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700452 mContext = context;
453 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700454 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800455 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800456 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800457 synchronized (mPackagesLock) {
458 mUsersDir = new File(dataDir, USER_INFO_DIR);
459 mUsersDir.mkdirs();
460 // Make zeroth user directory, for services to migrate their files to that location
461 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
462 userZeroDir.mkdirs();
463 FileUtils.setPermissions(mUsersDir.toString(),
464 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
465 -1, -1);
466 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
467 initDefaultGuestRestrictions();
468 readUserListLP();
469 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700470 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700471 mLocalService = new LocalService();
472 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000473 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000474 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700475 }
476
477 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400478 mAppOpsService = IAppOpsService.Stub.asInterface(
479 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800480
481 synchronized (mRestrictionsLock) {
482 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400483 }
Samuel Tand9453b82016-03-14 15:57:02 -0700484
485 UserInfo currentGuestUser = findCurrentGuestUser();
486 if (currentGuestUser != null && !hasUserRestriction(
487 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
488 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
489 // to it, in case this guest was created in a previous version where this
490 // user restriction was not a default guest restriction.
491 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
492 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700493
Ricky Waib1dd80b2016-06-07 18:00:55 +0100494 mContext.registerReceiver(mDisableQuietModeCallback,
495 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
496 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700497 }
498
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700499 void cleanupPartialUsers() {
500 // Prune out any partially created, partially removed and ephemeral users.
501 ArrayList<UserInfo> partials = new ArrayList<>();
502 synchronized (mUsersLock) {
503 final int userSize = mUsers.size();
504 for (int i = 0; i < userSize; i++) {
505 UserInfo ui = mUsers.valueAt(i).info;
506 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
507 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700508 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700509 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700510 }
511 }
512 }
513 final int partialsSize = partials.size();
514 for (int i = 0; i < partialsSize; i++) {
515 UserInfo ui = partials.get(i);
516 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
517 + " (name=" + ui.name + ")");
518 removeUserState(ui.id);
519 }
520 }
521
Amith Yamasani258848d2012-08-10 17:06:33 -0700522 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800523 public String getUserAccount(int userId) {
524 checkManageUserAndAcrossUsersFullPermission("get user account");
525 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800526 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800527 }
528 }
529
530 @Override
531 public void setUserAccount(int userId, String accountName) {
532 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800533 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800534 synchronized (mPackagesLock) {
535 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800536 final UserData userData = mUsers.get(userId);
537 if (userData == null) {
538 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
539 return;
540 }
541 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800542 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800543 userData.account = accountName;
544 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800545 }
546 }
547
548 if (userToUpdate != null) {
549 writeUserLP(userToUpdate);
550 }
551 }
552 }
553
554 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700555 public UserInfo getPrimaryUser() {
556 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700557 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700558 final int userSize = mUsers.size();
559 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800560 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800561 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700562 return ui;
563 }
564 }
565 }
566 return null;
567 }
568
569 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700570 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700571 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700572 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700573 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700574 final int userSize = mUsers.size();
575 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800576 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700577 if (ui.partial) {
578 continue;
579 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800580 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700581 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700582 }
Amith Yamasani13593602012-03-22 16:16:17 -0700583 }
584 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700585 }
Amith Yamasani13593602012-03-22 16:16:17 -0700586 }
587
Amith Yamasani258848d2012-08-10 17:06:33 -0700588 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100589 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700590 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800591 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700592 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700593 } else {
594 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800595 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700596 final long ident = Binder.clearCallingIdentity();
597 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700598 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700599 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100600 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700601 } finally {
602 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000603 }
604 }
605
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700606 @Override
607 public int[] getProfileIds(int userId, boolean enabledOnly) {
608 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700609 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700610 }
611 final long ident = Binder.clearCallingIdentity();
612 try {
613 synchronized (mUsersLock) {
614 return getProfileIdsLU(userId, enabledOnly).toArray();
615 }
616 } finally {
617 Binder.restoreCallingIdentity(ident);
618 }
619 }
620
Amith Yamasanibe465322014-04-24 13:45:17 -0700621 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700622 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700623 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
624 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
625 for (int i = 0; i < profileIds.size(); i++) {
626 int profileId = profileIds.get(i);
627 UserInfo userInfo = mUsers.get(profileId).info;
628 // If full info is not required - clear PII data to prevent 3P apps from reading it
629 if (!fullInfo) {
630 userInfo = new UserInfo(userInfo);
631 userInfo.name = null;
632 userInfo.iconPath = null;
633 } else {
634 userInfo = userWithName(userInfo);
635 }
636 users.add(userInfo);
637 }
638 return users;
639 }
640
641 /**
642 * Assume permissions already checked and caller's identity cleared
643 */
644 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700645 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700646 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700647 if (user == null) {
648 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700649 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700650 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700651 final int userSize = mUsers.size();
652 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800653 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700654 if (!isProfileOf(user, profile)) {
655 continue;
656 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100657 if (enabledOnly && !profile.isEnabled()) {
658 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700659 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700660 if (mRemovingUserIds.get(profile.id)) {
661 continue;
662 }
Tony Mak80189cd2016-04-05 17:21:42 +0100663 if (profile.partial) {
664 continue;
665 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700666 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700667 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700668 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700669 }
670
Jessica Hummelbe81c802014-04-22 15:49:22 +0100671 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700672 public int getCredentialOwnerProfile(int userHandle) {
673 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000674 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700675 synchronized (mUsersLock) {
676 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700677 if (profileParent != null) {
678 return profileParent.id;
679 }
680 }
681 }
682
683 return userHandle;
684 }
685
686 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700687 public boolean isSameProfileGroup(int userId, int otherUserId) {
688 if (userId == otherUserId) return true;
689 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700690 return isSameProfileGroupNoChecks(userId, otherUserId);
691 }
692
693 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700694 synchronized (mUsersLock) {
695 UserInfo userInfo = getUserInfoLU(userId);
696 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
697 return false;
698 }
699 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
700 if (otherUserInfo == null
701 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
702 return false;
703 }
704 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700705 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700706 }
707
708 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100709 public UserInfo getProfileParent(int userHandle) {
710 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700711 synchronized (mUsersLock) {
712 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700713 }
714 }
715
Fyodor Kupolov82402752015-10-28 14:54:51 -0700716 private UserInfo getProfileParentLU(int userHandle) {
717 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700718 if (profile == null) {
719 return null;
720 }
721 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800722 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700723 return null;
724 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700725 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100726 }
727 }
728
Fyodor Kupolov82402752015-10-28 14:54:51 -0700729 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100730 return user.id == profile.id ||
731 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
732 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000733 }
734
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000735 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000736 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100737 Intent intent = new Intent();
738 if (inQuietMode) {
739 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
740 } else {
741 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
742 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000743 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
744 intent.putExtra(Intent.EXTRA_USER, profileHandle);
745 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000746 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000747 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000748 }
749
750 @Override
751 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
752 checkManageUsersPermission("silence profile");
753 boolean changed = false;
754 UserInfo profile, parent;
755 synchronized (mPackagesLock) {
756 synchronized (mUsersLock) {
757 profile = getUserInfoLU(userHandle);
758 parent = getProfileParentLU(userHandle);
759
760 }
761 if (profile == null || !profile.isManagedProfile()) {
762 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
763 }
764 if (profile.isQuietModeEnabled() != enableQuietMode) {
765 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800766 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000767 changed = true;
768 }
769 }
770 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000771 long identity = Binder.clearCallingIdentity();
772 try {
773 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800774 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100775 LocalServices.getService(ActivityManagerInternal.class)
776 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000777 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800778 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000779 }
780 } catch (RemoteException e) {
781 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
782 } finally {
783 Binder.restoreCallingIdentity(identity);
784 }
785
786 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
787 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000788 }
789 }
790
791 @Override
792 public boolean isQuietModeEnabled(int userHandle) {
793 synchronized (mPackagesLock) {
794 UserInfo info;
795 synchronized (mUsersLock) {
796 info = getUserInfoLU(userHandle);
797 }
798 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000799 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000800 }
801 return info.isQuietModeEnabled();
802 }
803 }
804
Kenny Guya52dc3e2014-02-11 15:33:14 +0000805 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100806 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100807 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600808 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100809 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100810 // if the user is already unlocked, no need to show a profile challenge
811 setQuietModeEnabled(userHandle, false);
812 return true;
813 }
814
815 long identity = Binder.clearCallingIdentity();
816 try {
817 // otherwise, we show a profile challenge to trigger decryption of the user
818 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
819 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100820 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
821 // lock, confirm screenlock page will know and show personal challenge, and unlock
822 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100823 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
824 userHandle);
825 if (unlockIntent == null) {
826 return false;
827 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100828 final Intent callBackIntent = new Intent(
829 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100830 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100831 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100832 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100833 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
834 callBackIntent.setPackage(mContext.getPackageName());
835 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
836 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
837 mContext,
838 0,
839 callBackIntent,
840 PendingIntent.FLAG_CANCEL_CURRENT |
841 PendingIntent.FLAG_ONE_SHOT |
842 PendingIntent.FLAG_IMMUTABLE);
843 // After unlocking the challenge, it will disable quiet mode and run the original
844 // intentSender
845 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100846 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
847 mContext.startActivity(unlockIntent);
848 } finally {
849 Binder.restoreCallingIdentity(identity);
850 }
851 return false;
852 }
853
854 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100855 public void setUserEnabled(int userId) {
856 checkManageUsersPermission("enable user");
857 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700858 UserInfo info;
859 synchronized (mUsersLock) {
860 info = getUserInfoLU(userId);
861 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100862 if (info != null && !info.isEnabled()) {
863 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800864 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100865 }
866 }
867 }
868
Andrew Scull85a63bc2016-10-24 13:47:47 +0100869 /**
870 * Evicts a user's CE key by stopping and restarting the user.
871 *
872 * The key is evicted automatically by the user controller when the user has stopped.
873 */
874 @Override
875 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
876 checkManageUsersPermission("evict CE key");
877 final IActivityManager am = ActivityManagerNative.getDefault();
878 final long identity = Binder.clearCallingIdentity();
879 try {
880 am.restartUserInBackground(userId);
881 } catch (RemoteException re) {
882 throw re.rethrowAsRuntimeException();
883 } finally {
884 Binder.restoreCallingIdentity(identity);
885 }
886 }
887
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100888 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700889 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700890 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000891 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700892 return userWithName(getUserInfoLU(userId));
893 }
894 }
895
896 /**
897 * Returns a UserInfo object with the name filled in, for Owner, or the original
898 * if the name is already set.
899 */
900 private UserInfo userWithName(UserInfo orig) {
901 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
902 UserInfo withName = new UserInfo(orig);
903 withName.name = getOwnerName();
904 return withName;
905 } else {
906 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000907 }
908 }
909
910 @Override
Kenny Guy02c89902016-11-15 19:36:38 +0000911 public int getManagedProfileBadge(@UserIdInt int userId) {
912 int callingUserId = UserHandle.getCallingUserId();
913 if (callingUserId != userId && !hasManageUsersPermission()) {
914 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
915 throw new SecurityException(
916 "You need MANAGE_USERS permission to: check if specified user a " +
917 "managed profile outside your profile group");
918 }
919 }
920 synchronized (mUsersLock) {
921 UserInfo userInfo = getUserInfoLU(userId);
922 return userInfo != null ? userInfo.profileBadge : 0;
923 }
924 }
925
926 @Override
Tony Mak8673b282016-03-21 21:10:59 +0000927 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000928 int callingUserId = UserHandle.getCallingUserId();
929 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700930 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700931 throw new SecurityException(
932 "You need MANAGE_USERS permission to: check if specified user a " +
933 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000934 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000935 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700936 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700937 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000938 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700939 }
940 }
941
Amith Yamasani71e6c692013-03-24 17:39:28 -0700942 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700943 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800944 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700945 return mLocalService.isUserUnlockingOrUnlocked(userId);
946 }
947
948 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -0800949 public boolean isUserUnlocked(int userId) {
950 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
951 return mLocalService.isUserUnlockingOrUnlocked(userId);
952 }
953
954 @Override
955 public boolean isUserRunning(int userId) {
956 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
957 return mLocalService.isUserRunning(userId);
958 }
959
960 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
961 int callingUserId = UserHandle.getCallingUserId();
962 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
963 hasManageUsersPermission()) {
964 return;
965 }
966 if (ActivityManager.checkComponentPermission(Manifest.permission.INTERACT_ACROSS_USERS,
967 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
968 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
969 + "to: check " + name);
970 }
971 }
972
973 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700974 public boolean isDemoUser(int userId) {
975 int callingUserId = UserHandle.getCallingUserId();
976 if (callingUserId != userId && !hasManageUsersPermission()) {
977 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
978 + " is a demo user");
979 }
980 synchronized (mUsersLock) {
981 UserInfo userInfo = getUserInfoLU(userId);
982 return userInfo != null && userInfo.isDemo();
983 }
984 }
985
986 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700987 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700988 synchronized (mUsersLock) {
989 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700990 }
991 }
992
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700993 @Override
994 public boolean canHaveRestrictedProfile(int userId) {
995 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700996 synchronized (mUsersLock) {
997 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700998 if (userInfo == null || !userInfo.canHaveProfile()) {
999 return false;
1000 }
1001 if (!userInfo.isAdmin()) {
1002 return false;
1003 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001004 // restricted profile can be created if there is no DO set and the admin user has no PO;
1005 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001006 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001007 }
1008
Amith Yamasani195263742012-08-21 15:40:12 -07001009 /*
1010 * Should be locked on mUsers before calling this.
1011 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001012 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001013 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001014 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001015 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001016 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1017 return null;
1018 }
Amith Yamasani12747872015-12-07 14:19:49 -08001019 return userData != null ? userData.info : null;
1020 }
1021
1022 private UserData getUserDataLU(int userId) {
1023 final UserData userData = mUsers.get(userId);
1024 // If it is partial and not in the process of being removed, return as unknown user.
1025 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1026 return null;
1027 }
1028 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001029 }
1030
Fyodor Kupolov82402752015-10-28 14:54:51 -07001031 /**
1032 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1033 * <p>No permissions checking or any addition checks are made</p>
1034 */
1035 private UserInfo getUserInfoNoChecks(int userId) {
1036 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001037 final UserData userData = mUsers.get(userId);
1038 return userData != null ? userData.info : null;
1039 }
1040 }
1041
1042 /**
1043 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1044 * <p>No permissions checking or any addition checks are made</p>
1045 */
1046 private UserData getUserDataNoChecks(int userId) {
1047 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001048 return mUsers.get(userId);
1049 }
1050 }
1051
Amith Yamasani236b2b52015-08-18 14:32:14 -07001052 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001053 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001054 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -07001055 }
1056
Amith Yamasani258848d2012-08-10 17:06:33 -07001057 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001058 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001059 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001060 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001061 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001062 UserData userData = getUserDataNoChecks(userId);
1063 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001064 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1065 return;
1066 }
Amith Yamasani12747872015-12-07 14:19:49 -08001067 if (name != null && !name.equals(userData.info.name)) {
1068 userData.info.name = name;
1069 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001070 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001071 }
1072 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001073 if (changed) {
1074 sendUserInfoChangedBroadcast(userId);
1075 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001076 }
1077
Amith Yamasani258848d2012-08-10 17:06:33 -07001078 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001079 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001080 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001081 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1082 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1083 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001084 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001085 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001086 }
1087
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001088
1089
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001090 private void sendUserInfoChangedBroadcast(int userId) {
1091 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1092 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1093 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001094 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001095 }
1096
Amith Yamasani258848d2012-08-10 17:06:33 -07001097 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001098 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001099 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001100 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001101 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1102 if (targetUserInfo == null || targetUserInfo.partial) {
1103 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001104 return null;
1105 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001106
1107 final int callingUserId = UserHandle.getCallingUserId();
1108 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1109 final int targetGroupId = targetUserInfo.profileGroupId;
1110 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1111 && callingGroupId == targetGroupId);
1112 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001113 checkManageUsersPermission("get the icon of a user who is not related");
1114 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001115
1116 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001117 return null;
1118 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001119 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001120 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001121
1122 try {
1123 return ParcelFileDescriptor.open(
1124 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1125 } catch (FileNotFoundException e) {
1126 Log.e(LOG_TAG, "Couldn't find icon file", e);
1127 }
1128 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001129 }
1130
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001131 public void makeInitialized(int userId) {
1132 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001133 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001134 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001135 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001136 userData = mUsers.get(userId);
1137 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001138 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001139 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001140 }
Amith Yamasani12747872015-12-07 14:19:49 -08001141 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1142 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001143 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001144 }
1145 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001146 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001147 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001148 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001149 }
1150
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001151 /**
1152 * If default guest restrictions haven't been initialized yet, add the basic
1153 * restrictions.
1154 */
1155 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001156 synchronized (mGuestRestrictions) {
1157 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001158 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001159 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001160 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1161 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1162 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001163 }
1164 }
1165
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001166 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301167 public Bundle getDefaultGuestRestrictions() {
1168 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001169 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301170 return new Bundle(mGuestRestrictions);
1171 }
1172 }
1173
1174 @Override
1175 public void setDefaultGuestRestrictions(Bundle restrictions) {
1176 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001177 synchronized (mGuestRestrictions) {
1178 mGuestRestrictions.clear();
1179 mGuestRestrictions.putAll(restrictions);
1180 }
1181 synchronized (mPackagesLock) {
1182 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301183 }
1184 }
1185
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001186 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001187 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001188 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001189 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1190 boolean isDeviceOwner, int cameraRestrictionScope) {
1191 final Bundle global = new Bundle();
1192 final Bundle local = new Bundle();
1193
1194 // Sort restrictions into local and global ensuring they don't overlap.
1195 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1196 cameraRestrictionScope, global, local);
1197
1198 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001199 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001200 // Update global and local restrictions if they were changed.
1201 globalChanged = updateRestrictionsIfNeededLR(
1202 userId, global, mDevicePolicyGlobalUserRestrictions);
1203 localChanged = updateRestrictionsIfNeededLR(
1204 userId, local, mDevicePolicyLocalUserRestrictions);
1205
1206 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001207 // Remember the global restriction owner userId to be able to make a distinction
1208 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001209 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001210 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001211 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001212 // When profile owner sets restrictions it passes null global bundle and we
1213 // reset global restriction owner userId.
1214 // This means this user used to have DO, but now the DO is gone and the user
1215 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001216 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001217 }
1218 }
1219 }
1220 if (DBG) {
1221 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1222 + " global=" + global + (globalChanged ? " (changed)" : "")
1223 + " local=" + local + (localChanged ? " (changed)" : "")
1224 );
1225 }
1226 // Don't call them within the mRestrictionsLock.
1227 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001228 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001229 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001230 }
1231 }
1232
1233 synchronized (mRestrictionsLock) {
1234 if (globalChanged) {
1235 applyUserRestrictionsForAllUsersLR();
1236 } else if (localChanged) {
1237 applyUserRestrictionsLR(userId);
1238 }
1239 }
1240 }
1241
Pavel Grafov6a40f092016-10-25 15:46:51 +01001242 /**
1243 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1244 * empty, record is removed from the array.
1245 * @return whether restrictions bundle is different from the old one.
1246 */
1247 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1248 SparseArray<Bundle> restrictionsArray) {
1249 final boolean changed =
1250 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1251 if (changed) {
1252 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1253 restrictionsArray.put(userId, restrictions);
1254 } else {
1255 restrictionsArray.delete(userId);
1256 }
1257 }
1258 return changed;
1259 }
1260
Makoto Onuki068c54a2015-10-13 14:34:03 -07001261 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001262 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001263 final Bundle baseRestrictions =
1264 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001265 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001266 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001267
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001268 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1269 // Common case first.
1270 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001271 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001272 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1273 UserRestrictionsUtils.merge(effective, global);
1274 UserRestrictionsUtils.merge(effective, local);
1275
Makoto Onuki068c54a2015-10-13 14:34:03 -07001276 return effective;
1277 }
1278
1279 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001280 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001281 if (DBG) {
1282 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1283 }
1284 mCachedEffectiveUserRestrictions.remove(userId);
1285 }
1286
1287 private Bundle getEffectiveUserRestrictions(int userId) {
1288 synchronized (mRestrictionsLock) {
1289 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1290 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001291 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001292 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1293 }
1294 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001295 }
1296 }
1297
Makoto Onuki068c54a2015-10-13 14:34:03 -07001298 /** @return a specific user restriction that's in effect currently. */
1299 @Override
1300 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001301 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1302 return false;
1303 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001304 Bundle restrictions = getEffectiveUserRestrictions(userId);
1305 return restrictions != null && restrictions.getBoolean(restrictionKey);
1306 }
1307
1308 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001309 * @hide
1310 *
1311 * Returns who set a user restriction on a user.
1312 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1313 * @param restrictionKey the string key representing the restriction
1314 * @param userId the id of the user for whom to retrieve the restrictions.
1315 * @return The source of user restriction. Any combination of
1316 * {@link UserManager#RESTRICTION_NOT_SET},
1317 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1318 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1319 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1320 */
1321 @Override
1322 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001323 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1324 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001325 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001326 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1327 result |= enforcingUsers.get(i).getUserRestrictionSource();
1328 }
1329 return result;
1330 }
1331
1332 @Override
1333 public List<EnforcingUser> getUserRestrictionSources(
1334 String restrictionKey, @UserIdInt int userId) {
1335 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001336
1337 // Shortcut for the most common case
1338 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001339 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001340 }
1341
Pavel Grafov6a40f092016-10-25 15:46:51 +01001342 final List<EnforcingUser> result = new ArrayList<>();
1343
1344 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001345 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001346 result.add(new EnforcingUser(
1347 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001348 }
1349
Pavel Grafov6a40f092016-10-25 15:46:51 +01001350 synchronized (mRestrictionsLock) {
1351 // Check if it is set by profile owner.
1352 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1353 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1354 result.add(getEnforcingUserLocked(userId));
1355 }
1356
1357 // Iterate over all users who enforce global restrictions.
1358 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1359 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1360 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1361 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1362 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001363 }
1364 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001365 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001366 return result;
1367 }
1368
Pavel Grafov6a40f092016-10-25 15:46:51 +01001369 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1370 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1371 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1372 return new EnforcingUser(userId, source);
1373 }
1374
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001375 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001376 * @return UserRestrictions that are in effect currently. This always returns a new
1377 * {@link Bundle}.
1378 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001379 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001380 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001381 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001382 }
1383
1384 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001385 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1386 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001387 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1388 return false;
1389 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001390 synchronized (mRestrictionsLock) {
1391 Bundle bundle = mBaseUserRestrictions.get(userId);
1392 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1393 }
1394 }
1395
1396 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001397 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001398 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001399 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1400 return;
1401 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001402 synchronized (mRestrictionsLock) {
1403 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1404 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001405 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1406 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001407 newRestrictions.putBoolean(key, value);
1408
Fyodor Kupolov82402752015-10-28 14:54:51 -07001409 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001410 }
1411 }
1412
Makoto Onuki068c54a2015-10-13 14:34:03 -07001413 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001414 * Optionally updating user restrictions, calculate the effective user restrictions and also
1415 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001416 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001417 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001418 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001419 * @param userId target user ID.
1420 */
1421 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001422 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001423 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001424 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1425 mAppliedUserRestrictions.get(userId));
1426
1427 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001428 if (newBaseRestrictions != null) {
1429 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001430 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1431
Pavel Grafov6a40f092016-10-25 15:46:51 +01001432 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001433 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001434 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001435
Pavel Grafov6a40f092016-10-25 15:46:51 +01001436 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001437 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001438 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001439 }
1440
Fyodor Kupolov82402752015-10-28 14:54:51 -07001441 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001442
Makoto Onuki759a7632015-10-28 16:43:10 -07001443 mCachedEffectiveUserRestrictions.put(userId, effective);
1444
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001445 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001446 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001447 debug("Applying user restrictions: userId=" + userId
1448 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001449 }
1450
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001451 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001452 mHandler.post(new Runnable() {
1453 @Override
1454 public void run() {
1455 try {
1456 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1457 } catch (RemoteException e) {
1458 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1459 }
1460 }
1461 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001462 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001463
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001465
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001466 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001467 }
1468
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001469 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001470 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001471 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1472 // actually, but we still need some kind of synchronization otherwise we might end up
1473 // calling listeners out-of-order, thus "LR".
1474
1475 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1476 return;
1477 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001478
1479 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1480 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1481
1482 mHandler.post(new Runnable() {
1483 @Override
1484 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001485 UserRestrictionsUtils.applyUserRestrictions(
1486 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001487
Makoto Onukid45a4a22015-11-02 17:17:38 -08001488 final UserRestrictionsListener[] listeners;
1489 synchronized (mUserRestrictionsListeners) {
1490 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1491 mUserRestrictionsListeners.toArray(listeners);
1492 }
1493 for (int i = 0; i < listeners.length; i++) {
1494 listeners[i].onUserRestrictionsChanged(userId,
1495 newRestrictionsFinal, prevRestrictionsFinal);
1496 }
1497 }
1498 });
1499 }
1500
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001501 // Package private for the inner class.
1502 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001503 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001504 }
1505
1506 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001507 // Package private for the inner class.
1508 void applyUserRestrictionsForAllUsersLR() {
1509 if (DBG) {
1510 debug("applyUserRestrictionsForAllUsersLR");
1511 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001512 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001513 mCachedEffectiveUserRestrictions.clear();
1514
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001515 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001516 // it on a handler.
1517 final Runnable r = new Runnable() {
1518 @Override
1519 public void run() {
1520 // Then get the list of running users.
1521 final int[] runningUsers;
1522 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001523 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001524 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001525 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001526 return;
1527 }
1528 // Then re-calculate the effective restrictions and apply, only for running users.
1529 // It's okay if a new user has started after the getRunningUserIds() call,
1530 // because we'll do the same thing (re-calculate the restrictions and apply)
1531 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001532 synchronized (mRestrictionsLock) {
1533 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001534 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001535 }
1536 }
1537 }
1538 };
1539 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001540 }
1541
Amith Yamasani258848d2012-08-10 17:06:33 -07001542 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001543 * Check if we've hit the limit of how many users can be created.
1544 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001545 private boolean isUserLimitReached() {
1546 int count;
1547 synchronized (mUsersLock) {
1548 count = getAliveUsersExcludingGuestsCountLU();
1549 }
1550 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001551 }
1552
1553 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001554 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001555 checkManageUsersPermission("check if more managed profiles can be added.");
1556 if (ActivityManager.isLowRamDeviceStatic()) {
1557 return false;
1558 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001559 if (!mContext.getPackageManager().hasSystemFeature(
1560 PackageManager.FEATURE_MANAGED_USERS)) {
1561 return false;
1562 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001563 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001564 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001565 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001566 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001567 return false;
1568 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001569 synchronized(mUsersLock) {
1570 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001571 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001572 return false;
1573 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001574 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1575 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001576 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001577 return usersCountAfterRemoving == 1
1578 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001579 }
1580 }
1581
Fyodor Kupolov82402752015-10-28 14:54:51 -07001582 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001583 int aliveUserCount = 0;
1584 final int totalUserCount = mUsers.size();
1585 // Skip over users being removed
1586 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001587 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001588 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001589 aliveUserCount++;
1590 }
1591 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001592 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001593 }
1594
1595 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001596 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001597 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1598 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1599 * permissions can make certain calls to the UserManager.
1600 *
1601 * @param message used as message if SecurityException is thrown
1602 * @throws SecurityException if the caller does not have enough privilege.
1603 */
1604 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1605 final int uid = Binder.getCallingUid();
1606 if (uid != Process.SYSTEM_UID && uid != 0
1607 && ActivityManager.checkComponentPermission(
1608 Manifest.permission.MANAGE_USERS,
1609 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1610 && ActivityManager.checkComponentPermission(
1611 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1612 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1613 throw new SecurityException(
1614 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1615 + message);
1616 }
1617 }
1618
1619 /**
1620 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001621 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001622 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001623 *
1624 * @param message used as message if SecurityException is thrown
1625 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001626 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001627 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001628 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001629 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001630 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1631 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001632 }
1633
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001634 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001635 * Enforces that only the system UID or root's UID or apps that have the
1636 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1637 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1638 * can make certain calls to the UserManager.
1639 *
1640 * @param message used as message if SecurityException is thrown
1641 * @throws SecurityException if the caller is not system or root
1642 * @see #hasManageOrCreateUsersPermission()
1643 */
1644 private static final void checkManageOrCreateUsersPermission(String message) {
1645 if (!hasManageOrCreateUsersPermission()) {
1646 throw new SecurityException(
1647 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1648 }
1649 }
1650
1651 /**
1652 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1653 * to create user/profiles other than what is allowed for
1654 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1655 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1656 */
1657 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1658 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1659 if (!hasManageOrCreateUsersPermission()) {
1660 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1661 + "permission to create an user with flags: " + creationFlags);
1662 }
1663 } else if (!hasManageUsersPermission()) {
1664 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1665 + " with flags: " + creationFlags);
1666 }
1667 }
1668
1669 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001670 * @return whether the calling UID is system UID or root's UID or the calling app has the
1671 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1672 */
1673 private static final boolean hasManageUsersPermission() {
1674 final int callingUid = Binder.getCallingUid();
1675 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1676 || callingUid == Process.ROOT_UID
1677 || ActivityManager.checkComponentPermission(
1678 android.Manifest.permission.MANAGE_USERS,
1679 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1680 }
1681
1682 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001683 * @return whether the calling UID is system UID or root's UID or the calling app has the
1684 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1685 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1686 */
1687 private static final boolean hasManageOrCreateUsersPermission() {
1688 final int callingUid = Binder.getCallingUid();
1689 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1690 || callingUid == Process.ROOT_UID
1691 || ActivityManager.checkComponentPermission(
1692 android.Manifest.permission.MANAGE_USERS,
1693 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1694 || ActivityManager.checkComponentPermission(
1695 android.Manifest.permission.CREATE_USERS,
1696 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1697 }
1698
1699 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001700 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1701 * UserManager.
1702 *
1703 * @param message used as message if SecurityException is thrown
1704 * @throws SecurityException if the caller is not system or root
1705 */
1706 private static void checkSystemOrRoot(String message) {
1707 final int uid = Binder.getCallingUid();
1708 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1709 throw new SecurityException("Only system may: " + message);
1710 }
1711 }
1712
Fyodor Kupolov82402752015-10-28 14:54:51 -07001713 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001714 try {
1715 File dir = new File(mUsersDir, Integer.toString(info.id));
1716 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001717 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001718 if (!dir.exists()) {
1719 dir.mkdir();
1720 FileUtils.setPermissions(
1721 dir.getPath(),
1722 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1723 -1, -1);
1724 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001725 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001726 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001727 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001728 info.iconPath = file.getAbsolutePath();
1729 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001730 try {
1731 os.close();
1732 } catch (IOException ioe) {
1733 // What the ... !
1734 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001735 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001736 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001737 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001738 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001739 }
1740
Amith Yamasani0b285492011-04-14 17:35:23 -07001741 /**
1742 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1743 * cache it elsewhere.
1744 * @return the array of user ids.
1745 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001746 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001747 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001748 return mUserIds;
1749 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001750 }
1751
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001752 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001753 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001754 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001755 return;
1756 }
1757 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001758 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001759 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001760 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001761 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001762 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001763 int type;
1764 while ((type = parser.next()) != XmlPullParser.START_TAG
1765 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001766 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001767 }
1768
1769 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001770 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001771 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001772 return;
1773 }
1774
Amith Yamasani2a003292012-08-14 18:25:45 -07001775 mNextSerialNumber = -1;
1776 if (parser.getName().equals(TAG_USERS)) {
1777 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1778 if (lastSerialNumber != null) {
1779 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1780 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001781 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1782 if (versionNumber != null) {
1783 mUserVersion = Integer.parseInt(versionNumber);
1784 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001785 }
1786
Pavel Grafov6a40f092016-10-25 15:46:51 +01001787 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
1788 // currently), take care of it in case of upgrade.
1789 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001790
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001791 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301792 if (type == XmlPullParser.START_TAG) {
1793 final String name = parser.getName();
1794 if (name.equals(TAG_USER)) {
1795 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001796
Amith Yamasani12747872015-12-07 14:19:49 -08001797 UserData userData = readUserLP(Integer.parseInt(id));
1798
1799 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001800 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001801 mUsers.put(userData.info.id, userData);
1802 if (mNextSerialNumber < 0
1803 || mNextSerialNumber <= userData.info.id) {
1804 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001805 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301806 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001807 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301808 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001809 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1810 && type != XmlPullParser.END_TAG) {
1811 if (type == XmlPullParser.START_TAG) {
1812 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001813 synchronized (mGuestRestrictions) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001814 mGuestRestrictions.putAll(
1815 UserRestrictionsUtils.readRestrictions(parser));
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001816 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001817 }
1818 break;
1819 }
1820 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001821 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
1822 // Legacy name, should only be encountered when upgrading from pre-O.
1823 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001824 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1825 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001826 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001827 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001828 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1829 // Should only happen when upgrading from pre-O (version < 7).
1830 oldDevicePolicyGlobalUserRestrictions =
1831 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07001832 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001833 }
1834 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01001835
Fyodor Kupolov82402752015-10-28 14:54:51 -07001836 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001837 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001838 } catch (IOException | XmlPullParserException e) {
1839 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001840 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001841 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001842 }
1843 }
1844
Amith Yamasani6f34b412012-10-22 18:19:27 -07001845 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001846 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001847 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001848 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001849 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001850 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001851 int userVersion = mUserVersion;
1852 if (userVersion < 1) {
1853 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001854 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1855 if ("Primary".equals(userData.info.name)) {
1856 userData.info.name =
1857 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1858 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001859 }
1860 userVersion = 1;
1861 }
1862
Amith Yamasanibc9625052012-11-15 14:39:18 -08001863 if (userVersion < 2) {
1864 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001865 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1866 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1867 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1868 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001869 }
1870 userVersion = 2;
1871 }
1872
Amith Yamasani350962c2013-08-06 11:18:53 -07001873
Amith Yamasani5e486f52013-08-07 11:06:44 -07001874 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001875 userVersion = 4;
1876 }
1877
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001878 if (userVersion < 5) {
1879 initDefaultGuestRestrictions();
1880 userVersion = 5;
1881 }
1882
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001883 if (userVersion < 6) {
1884 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001885 synchronized (mUsersLock) {
1886 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001887 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001888 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001889 if (!splitSystemUser && userData.info.isRestricted()
1890 && (userData.info.restrictedProfileParentId
1891 == UserInfo.NO_PROFILE_GROUP_ID)) {
1892 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1893 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001894 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001895 }
1896 }
1897 userVersion = 6;
1898 }
1899
Pavel Grafov6a40f092016-10-25 15:46:51 +01001900 if (userVersion < 7) {
1901 // Previously only one user could enforce global restrictions, now it is per-user.
1902 synchronized (mRestrictionsLock) {
1903 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
1904 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
1905 mDevicePolicyGlobalUserRestrictions.put(
1906 mDeviceOwnerUserId, oldGlobalUserRestrictions);
1907 }
1908 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
1909 // it from local to global bundle for all users who set it.
1910 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
1911 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
1912 );
1913 }
1914 userVersion = 7;
1915 }
1916
Amith Yamasani6f34b412012-10-22 18:19:27 -07001917 if (userVersion < USER_VERSION) {
1918 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1919 + USER_VERSION);
1920 } else {
1921 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001922
1923 if (originalVersion < mUserVersion) {
1924 writeUserListLP();
1925 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001926 }
1927 }
1928
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001929 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001930 int flags = UserInfo.FLAG_INITIALIZED;
1931 // In split system user mode, the admin and primary flags are assigned to the first human
1932 // user.
1933 if (!UserManager.isSplitSystemUser()) {
1934 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1935 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001936 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001937 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001938 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001939 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001940 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001941
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001942 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001943 try {
1944 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1945 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1946 for (String userRestriction : defaultFirstUserRestrictions) {
1947 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1948 restrictions.putBoolean(userRestriction, true);
1949 }
1950 }
1951 } catch (Resources.NotFoundException e) {
1952 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1953 }
1954
Pavel Grafov6a40f092016-10-25 15:46:51 +01001955 if (!restrictions.isEmpty()) {
1956 synchronized (mRestrictionsLock) {
1957 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1958 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001959 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001960
Fyodor Kupolov82402752015-10-28 14:54:51 -07001961 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001962 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001963
Amith Yamasani12747872015-12-07 14:19:49 -08001964 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001965 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001966 }
1967
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001968 private String getOwnerName() {
1969 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1970 }
1971
Amith Yamasani12747872015-12-07 14:19:49 -08001972 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001973 if (DBG) {
1974 debug("scheduleWriteUser");
1975 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001976 // No need to wrap it within a lock -- worst case, we'll just post the same message
1977 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001978 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1979 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001980 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1981 }
1982 }
1983
Amith Yamasani12747872015-12-07 14:19:49 -08001984 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001985 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001986 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001987 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001988 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001989 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001990 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001991 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001992 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00001993 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07001994 userFile.finishWrite(fos);
1995 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001996 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001997 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001998 }
1999 }
2000
2001 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002002 * Writes the user file in this format:
2003 *
2004 * <user flags="20039023" id="0">
2005 * <name>Primary</name>
2006 * </user>
2007 */
2008 @VisibleForTesting
2009 void writeUserLP(UserData userData, OutputStream os)
2010 throws IOException, XmlPullParserException {
2011 // XmlSerializer serializer = XmlUtils.serializerInstance();
2012 final XmlSerializer serializer = new FastXmlSerializer();
2013 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2014 serializer.startDocument(null, true);
2015 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2016
2017 final UserInfo userInfo = userData.info;
2018 serializer.startTag(null, TAG_USER);
2019 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2020 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2021 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2022 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2023 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2024 Long.toString(userInfo.lastLoggedInTime));
2025 if (userInfo.lastLoggedInFingerprint != null) {
2026 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2027 userInfo.lastLoggedInFingerprint);
2028 }
2029 if (userInfo.iconPath != null) {
2030 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2031 }
2032 if (userInfo.partial) {
2033 serializer.attribute(null, ATTR_PARTIAL, "true");
2034 }
2035 if (userInfo.guestToRemove) {
2036 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2037 }
2038 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2039 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2040 Integer.toString(userInfo.profileGroupId));
2041 }
2042 serializer.attribute(null, ATTR_PROFILE_BADGE,
2043 Integer.toString(userInfo.profileBadge));
2044 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2045 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2046 Integer.toString(userInfo.restrictedProfileParentId));
2047 }
2048 // Write seed data
2049 if (userData.persistSeedData) {
2050 if (userData.seedAccountName != null) {
2051 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2052 }
2053 if (userData.seedAccountType != null) {
2054 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2055 }
2056 }
2057 if (userInfo.name != null) {
2058 serializer.startTag(null, TAG_NAME);
2059 serializer.text(userInfo.name);
2060 serializer.endTag(null, TAG_NAME);
2061 }
2062 synchronized (mRestrictionsLock) {
2063 UserRestrictionsUtils.writeRestrictions(serializer,
2064 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2065 UserRestrictionsUtils.writeRestrictions(serializer,
2066 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2067 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002068 UserRestrictionsUtils.writeRestrictions(serializer,
2069 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2070 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002071 }
2072
2073 if (userData.account != null) {
2074 serializer.startTag(null, TAG_ACCOUNT);
2075 serializer.text(userData.account);
2076 serializer.endTag(null, TAG_ACCOUNT);
2077 }
2078
2079 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2080 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2081 userData.seedAccountOptions.saveToXml(serializer);
2082 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2083 }
2084
2085 serializer.endTag(null, TAG_USER);
2086
2087 serializer.endDocument();
2088 }
2089
2090 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002091 * Writes the user list file in this format:
2092 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002093 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002094 * <user id="0"></user>
2095 * <user id="2"></user>
2096 * </users>
2097 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002098 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002099 if (DBG) {
2100 debug("writeUserList");
2101 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002102 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002103 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002104 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002105 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002106 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2107
2108 // XmlSerializer serializer = XmlUtils.serializerInstance();
2109 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002110 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002111 serializer.startDocument(null, true);
2112 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2113
2114 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002115 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002116 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002117
Adam Lesinskieddeb492014-09-08 17:50:03 -07002118 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002119 synchronized (mGuestRestrictions) {
2120 UserRestrictionsUtils
2121 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2122 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302123 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002124 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2125 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2126 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002127 int[] userIdsToWrite;
2128 synchronized (mUsersLock) {
2129 userIdsToWrite = new int[mUsers.size()];
2130 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002131 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002132 userIdsToWrite[i] = user.id;
2133 }
2134 }
2135 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002136 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002137 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002138 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002139 }
2140
2141 serializer.endTag(null, TAG_USERS);
2142
2143 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002144 userListFile.finishWrite(fos);
2145 } catch (Exception e) {
2146 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002147 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002148 }
2149 }
2150
Amith Yamasani12747872015-12-07 14:19:49 -08002151 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002152 FileInputStream fis = null;
2153 try {
2154 AtomicFile userFile =
2155 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2156 fis = userFile.openRead();
2157 return readUserLP(id, fis);
2158 } catch (IOException ioe) {
2159 Slog.e(LOG_TAG, "Error reading user list");
2160 } catch (XmlPullParserException pe) {
2161 Slog.e(LOG_TAG, "Error reading user list");
2162 } finally {
2163 IoUtils.closeQuietly(fis);
2164 }
2165 return null;
2166 }
2167
2168 @VisibleForTesting
2169 UserData readUserLP(int id, InputStream is) throws IOException,
2170 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002171 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002172 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002173 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002174 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002175 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002176 long creationTime = 0L;
2177 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002178 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002179 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002180 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002181 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002182 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002183 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002184 boolean persistSeedData = false;
2185 String seedAccountName = null;
2186 String seedAccountType = null;
2187 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002188 Bundle baseRestrictions = null;
2189 Bundle localRestrictions = null;
2190 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002191
Kenny Guy02c89902016-11-15 19:36:38 +00002192 XmlPullParser parser = Xml.newPullParser();
2193 parser.setInput(is, StandardCharsets.UTF_8.name());
2194 int type;
2195 while ((type = parser.next()) != XmlPullParser.START_TAG
2196 && type != XmlPullParser.END_DOCUMENT) {
2197 // Skip
2198 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002199
Kenny Guy02c89902016-11-15 19:36:38 +00002200 if (type != XmlPullParser.START_TAG) {
2201 Slog.e(LOG_TAG, "Unable to read user " + id);
2202 return null;
2203 }
2204
2205 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2206 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2207 if (storedId != id) {
2208 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002209 return null;
2210 }
Kenny Guy02c89902016-11-15 19:36:38 +00002211 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2212 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2213 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2214 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2215 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2216 lastLoggedInFingerprint = parser.getAttributeValue(null,
2217 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2218 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2219 UserInfo.NO_PROFILE_GROUP_ID);
2220 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2221 restrictedProfileParentId = readIntAttribute(parser,
2222 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2223 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2224 if ("true".equals(valueString)) {
2225 partial = true;
2226 }
2227 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2228 if ("true".equals(valueString)) {
2229 guestToRemove = true;
2230 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002231
Kenny Guy02c89902016-11-15 19:36:38 +00002232 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2233 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2234 if (seedAccountName != null || seedAccountType != null) {
2235 persistSeedData = true;
2236 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002237
Kenny Guy02c89902016-11-15 19:36:38 +00002238 int outerDepth = parser.getDepth();
2239 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2240 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2241 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2242 continue;
2243 }
2244 String tag = parser.getName();
2245 if (TAG_NAME.equals(tag)) {
2246 type = parser.next();
2247 if (type == XmlPullParser.TEXT) {
2248 name = parser.getText();
2249 }
2250 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002251 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002252 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002253 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2254 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2255 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002256 } else if (TAG_ACCOUNT.equals(tag)) {
2257 type = parser.next();
2258 if (type == XmlPullParser.TEXT) {
2259 account = parser.getText();
2260 }
2261 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2262 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002263 persistSeedData = true;
2264 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002265 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002266 }
Kenny Guy02c89902016-11-15 19:36:38 +00002267
2268 // Create the UserInfo object that gets passed around
2269 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2270 userInfo.serialNumber = serialNumber;
2271 userInfo.creationTime = creationTime;
2272 userInfo.lastLoggedInTime = lastLoggedInTime;
2273 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2274 userInfo.partial = partial;
2275 userInfo.guestToRemove = guestToRemove;
2276 userInfo.profileGroupId = profileGroupId;
2277 userInfo.profileBadge = profileBadge;
2278 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2279
2280 // Create the UserData object that's internal to this class
2281 UserData userData = new UserData();
2282 userData.info = userInfo;
2283 userData.account = account;
2284 userData.seedAccountName = seedAccountName;
2285 userData.seedAccountType = seedAccountType;
2286 userData.persistSeedData = persistSeedData;
2287 userData.seedAccountOptions = seedAccountOptions;
2288
2289 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002290 if (baseRestrictions != null) {
2291 mBaseUserRestrictions.put(id, baseRestrictions);
2292 }
2293 if (localRestrictions != null) {
2294 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2295 }
2296 if (globalRestrictions != null) {
2297 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2298 }
Kenny Guy02c89902016-11-15 19:36:38 +00002299 }
2300 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002301 }
2302
Amith Yamasani920ace02012-09-20 22:15:37 -07002303 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2304 String valueString = parser.getAttributeValue(null, attr);
2305 if (valueString == null) return defaultValue;
2306 try {
2307 return Integer.parseInt(valueString);
2308 } catch (NumberFormatException nfe) {
2309 return defaultValue;
2310 }
2311 }
2312
2313 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2314 String valueString = parser.getAttributeValue(null, attr);
2315 if (valueString == null) return defaultValue;
2316 try {
2317 return Long.parseLong(valueString);
2318 } catch (NumberFormatException nfe) {
2319 return defaultValue;
2320 }
2321 }
2322
Amith Yamasanib82add22013-07-09 11:24:44 -07002323 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002324 * Removes the app restrictions file for a specific package and user id, if it exists.
2325 */
2326 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2327 synchronized (mPackagesLock) {
2328 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002329 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002330 if (resFile.exists()) {
2331 resFile.delete();
2332 }
2333 }
2334 }
2335
Kenny Guya52dc3e2014-02-11 15:33:14 +00002336 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002337 public UserInfo createProfileForUser(String name, int flags, int userId,
2338 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002339 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002340 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002341 }
2342
Amith Yamasani258848d2012-08-10 17:06:33 -07002343 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002344 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2345 String[] disallowedPackages) {
2346 checkManageOrCreateUsersPermission(flags);
2347 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2348 }
2349
2350 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002351 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2352 checkManageOrCreateUsersPermission("Only the system can remove users");
2353 return removeUserUnchecked(userHandle);
2354 }
2355
2356 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002357 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002358 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002359 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002360 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002361
Jessica Hummelbe81c802014-04-22 15:49:22 +01002362 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002363 return createUserInternal(name, flags, parentId, null);
2364 }
2365
2366 private UserInfo createUserInternal(String name, int flags, int parentId,
2367 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002368 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2369 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2370 : UserManager.DISALLOW_ADD_USER;
2371 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2372 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002373 return null;
2374 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002375 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2376 }
2377
2378 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2379 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002380 DeviceStorageMonitorInternal dsm = LocalServices
2381 .getService(DeviceStorageMonitorInternal.class);
2382 if (dsm.isMemoryLow()) {
2383 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2384 return null;
2385 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002386 if (ActivityManager.isLowRamDeviceStatic()) {
2387 return null;
2388 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002389 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002390 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002391 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002392 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002393 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002394 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002395 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002396 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002397 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002398 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002399 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002400 if (parentId != UserHandle.USER_NULL) {
2401 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002402 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002403 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002404 if (parent == null) return null;
2405 }
2406 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2407 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2408 return null;
2409 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002410 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2411 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002412 // been reached, cannot add a user.
2413 return null;
2414 }
2415 // If we're adding a guest and there already exists one, bail.
2416 if (isGuest && findCurrentGuestUser() != null) {
2417 return null;
2418 }
2419 // In legacy mode, restricted profile's parent can only be the owner user
2420 if (isRestricted && !UserManager.isSplitSystemUser()
2421 && (parentId != UserHandle.USER_SYSTEM)) {
2422 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2423 return null;
2424 }
2425 if (isRestricted && UserManager.isSplitSystemUser()) {
2426 if (parent == null) {
2427 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2428 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002429 return null;
2430 }
Amith Yamasani12747872015-12-07 14:19:49 -08002431 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002432 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2433 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002434 return null;
2435 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002436 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002437 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2438 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002439 Log.e(LOG_TAG,
2440 "Ephemeral users are supported on split-system-user systems only.");
2441 return null;
2442 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002443 // In split system user mode, we assign the first human user the primary flag.
2444 // And if there is no device owner, we also assign the admin flag to primary user.
2445 if (UserManager.isSplitSystemUser()
2446 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2447 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002448 synchronized (mUsersLock) {
2449 if (!mIsDeviceManaged) {
2450 flags |= UserInfo.FLAG_ADMIN;
2451 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002452 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002453 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002454
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002455 userId = getNextAvailableId();
2456 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002457 boolean ephemeralGuests = Resources.getSystem()
2458 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002459
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002460 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002461 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2462 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2463 || (parent != null && parent.info.isEphemeral())) {
2464 flags |= UserInfo.FLAG_EPHEMERAL;
2465 }
2466
2467 userInfo = new UserInfo(userId, name, null, flags);
2468 userInfo.serialNumber = mNextSerialNumber++;
2469 long now = System.currentTimeMillis();
2470 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2471 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002472 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002473 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2474 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2475 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002476 userData = new UserData();
2477 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002478 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002479 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002480 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002481 writeUserListLP();
2482 if (parent != null) {
2483 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002484 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2485 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002486 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002487 }
Amith Yamasani12747872015-12-07 14:19:49 -08002488 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002489 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002490 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2491 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002492 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002493 }
Amith Yamasani12747872015-12-07 14:19:49 -08002494 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002495 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002496 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002497 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002498 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002499 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002500 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002501 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002502 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002503 userInfo.partial = false;
2504 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002505 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002506 }
2507 updateUserIds();
2508 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002509 if (isGuest) {
2510 synchronized (mGuestRestrictions) {
2511 restrictions.putAll(mGuestRestrictions);
2512 }
2513 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002514 synchronized (mRestrictionsLock) {
2515 mBaseUserRestrictions.append(userId, restrictions);
2516 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002517 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002518 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2519 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2520 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2521 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002522 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002523 } finally {
2524 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002525 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002526 return userInfo;
2527 }
2528
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002529 @VisibleForTesting
2530 UserData putUserInfo(UserInfo userInfo) {
2531 final UserData userData = new UserData();
2532 userData.info = userInfo;
2533 synchronized (mUsers) {
2534 mUsers.put(userInfo.id, userData);
2535 }
2536 return userData;
2537 }
2538
2539 @VisibleForTesting
2540 void removeUserInfo(int userId) {
2541 synchronized (mUsers) {
2542 mUsers.remove(userId);
2543 }
2544 }
2545
Amith Yamasani0b285492011-04-14 17:35:23 -07002546 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002547 * @hide
2548 */
Amith Yamasani12747872015-12-07 14:19:49 -08002549 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002550 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002551 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002552 final UserInfo user = createProfileForUser(
2553 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002554 if (user == null) {
2555 return null;
2556 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002557 long identity = Binder.clearCallingIdentity();
2558 try {
2559 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2560 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2561 // the putIntForUser() will fail.
2562 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2563 android.provider.Settings.Secure.LOCATION_MODE,
2564 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2565 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2566 } finally {
2567 Binder.restoreCallingIdentity(identity);
2568 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002569 return user;
2570 }
2571
2572 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002573 * Find the current guest user. If the Guest user is partial,
2574 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002575 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002576 private UserInfo findCurrentGuestUser() {
2577 synchronized (mUsersLock) {
2578 final int size = mUsers.size();
2579 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002580 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002581 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2582 return user;
2583 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002584 }
2585 }
2586 return null;
2587 }
2588
2589 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002590 * Mark this guest user for deletion to allow us to create another guest
2591 * and switch to that user before actually removing this guest.
2592 * @param userHandle the userid of the current guest
2593 * @return whether the user could be marked for deletion
2594 */
Amith Yamasani12747872015-12-07 14:19:49 -08002595 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002596 public boolean markGuestForDeletion(int userHandle) {
2597 checkManageUsersPermission("Only the system can remove users");
2598 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2599 UserManager.DISALLOW_REMOVE_USER, false)) {
2600 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2601 return false;
2602 }
2603
2604 long ident = Binder.clearCallingIdentity();
2605 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002606 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002607 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002608 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002609 userData = mUsers.get(userHandle);
2610 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002611 return false;
2612 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002613 }
Amith Yamasani12747872015-12-07 14:19:49 -08002614 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002615 return false;
2616 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002617 // We set this to a guest user that is to be removed. This is a temporary state
2618 // where we are allowed to add new Guest users, even if this one is still not
2619 // removed. This user will still show up in getUserInfo() calls.
2620 // If we don't get around to removing this Guest user, it will be purged on next
2621 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002622 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002623 // Mark it as disabled, so that it isn't returned any more when
2624 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002625 userData.info.flags |= UserInfo.FLAG_DISABLED;
2626 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002627 }
2628 } finally {
2629 Binder.restoreCallingIdentity(ident);
2630 }
2631 return true;
2632 }
2633
2634 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002635 * Removes a user and all data directories created for that user. This method should be called
2636 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002637 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002638 */
Amith Yamasani12747872015-12-07 14:19:49 -08002639 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002640 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002641 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002642 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002643
2644 final boolean isManagedProfile;
2645 synchronized (mUsersLock) {
2646 UserInfo userInfo = getUserInfoLU(userHandle);
2647 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2648 }
2649 String restriction = isManagedProfile
2650 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2651 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2652 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002653 return false;
2654 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002655 return removeUserUnchecked(userHandle);
2656 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002657
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002658 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002659 long ident = Binder.clearCallingIdentity();
2660 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002661 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002662 int currentUser = ActivityManager.getCurrentUser();
2663 if (currentUser == userHandle) {
2664 Log.w(LOG_TAG, "Current user cannot be removed");
2665 return false;
2666 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002667 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002668 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002669 userData = mUsers.get(userHandle);
2670 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002671 return false;
2672 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002673
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002674 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002675 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002676
Kenny Guyee58b4f2014-05-23 15:19:53 +01002677 try {
2678 mAppOpsService.removeUser(userHandle);
2679 } catch (RemoteException e) {
2680 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2681 }
2682 // Set this to a partially created user, so that the user will be purged
2683 // on next startup, in case the runtime stops now before stopping and
2684 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002685 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002686 // Mark it as disabled, so that it isn't returned any more when
2687 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002688 userData.info.flags |= UserInfo.FLAG_DISABLED;
2689 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002690 }
2691
Amith Yamasani12747872015-12-07 14:19:49 -08002692 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2693 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002694 // Send broadcast to notify system that the user removed was a
2695 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002696 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002697 }
2698
2699 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2700 int res;
2701 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002702 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002703 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002704 @Override
2705 public void userStopped(int userId) {
2706 finishRemoveUser(userId);
2707 }
2708 @Override
2709 public void userStopAborted(int userId) {
2710 }
2711 });
2712 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002713 return false;
2714 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002715 return res == ActivityManager.USER_OP_SUCCESS;
2716 } finally {
2717 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002718 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002719 }
2720
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002721 @VisibleForTesting
2722 void addRemovingUserIdLocked(int userId) {
2723 // We remember deleted user IDs to prevent them from being
2724 // reused during the current boot; they can still be reused
2725 // after a reboot or recycling of userIds.
2726 mRemovingUserIds.put(userId, true);
2727 mRecentlyRemovedIds.add(userId);
2728 // Keep LRU queue of recently removed IDs for recycling
2729 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2730 mRecentlyRemovedIds.removeFirst();
2731 }
2732 }
2733
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002734 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002735 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002736 // Let other services shutdown any activity and clean up their state before completely
2737 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002738 long ident = Binder.clearCallingIdentity();
2739 try {
2740 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2741 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002742 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2743 android.Manifest.permission.MANAGE_USERS,
2744
2745 new BroadcastReceiver() {
2746 @Override
2747 public void onReceive(Context context, Intent intent) {
2748 if (DBG) {
2749 Slog.i(LOG_TAG,
2750 "USER_REMOVED broadcast sent, cleaning up user data "
2751 + userHandle);
2752 }
2753 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002754 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002755 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002756 // Clean up any ActivityManager state
2757 LocalServices.getService(ActivityManagerInternal.class)
2758 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002759 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002760 }
2761 }.start();
2762 }
2763 },
2764
2765 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002769 }
2770
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002771 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002772 try {
2773 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2774 } catch (IllegalStateException e) {
2775 // This may be simply because the user was partially created.
2776 Slog.i(LOG_TAG,
2777 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2778 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002779
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002780 // Cleanup gatekeeper secure user id
2781 try {
2782 final IGateKeeperService gk = GateKeeper.getService();
2783 if (gk != null) {
2784 gk.clearSecureUserId(userHandle);
2785 }
2786 } catch (Exception ex) {
2787 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2788 }
2789
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002790 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002791 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002792
2793 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002794 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002795 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2796
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002797 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002798 synchronized (mUsersLock) {
2799 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002800 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002801 }
2802 synchronized (mUserStates) {
2803 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002804 }
2805 synchronized (mRestrictionsLock) {
2806 mBaseUserRestrictions.remove(userHandle);
2807 mAppliedUserRestrictions.remove(userHandle);
2808 mCachedEffectiveUserRestrictions.remove(userHandle);
2809 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002810 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
2811 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
2812 applyUserRestrictionsForAllUsersLR();
2813 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002814 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002815 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002816 synchronized (mPackagesLock) {
2817 writeUserListLP();
2818 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002819 // Remove user file
2820 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2821 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002822 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002823 if (RELEASE_DELETED_USER_ID) {
2824 synchronized (mUsers) {
2825 mRemovingUserIds.delete(userHandle);
2826 }
2827 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002828 }
2829
Kenny Guyf8d3a232014-05-15 16:09:52 +01002830 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002831 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002832 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2833 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002834 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002835 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002836 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002837 }
2838
Amith Yamasani2a003292012-08-14 18:25:45 -07002839 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002840 public Bundle getApplicationRestrictions(String packageName) {
2841 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2842 }
2843
2844 @Override
2845 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002846 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002847 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002848 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002849 }
2850 synchronized (mPackagesLock) {
2851 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002852 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002853 }
2854 }
2855
2856 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002857 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002858 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002859 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002860 if (restrictions != null) {
2861 restrictions.setDefusable(true);
2862 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002863 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002864 if (restrictions == null || restrictions.isEmpty()) {
2865 cleanAppRestrictionsForPackage(packageName, userId);
2866 } else {
2867 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002868 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002869 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002870 }
Robin Lee66e5d962014-04-09 16:44:21 +01002871
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002872 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2873 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2874 changeIntent.setPackage(packageName);
2875 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2876 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002877 }
2878
2879 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002880 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002881 try {
2882 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002883 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002884 } catch (NameNotFoundException nnfe) {
2885 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002886 } finally {
2887 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002888 }
2889 }
2890
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002892 AtomicFile restrictionsFile =
2893 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2894 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002895 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002896 }
2897
2898 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002899 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002900 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002901 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002902 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002903 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002904 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002905
2906 FileInputStream fis = null;
2907 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002908 fis = restrictionsFile.openRead();
2909 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002910 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002911 XmlUtils.nextElement(parser);
2912 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002913 Slog.e(LOG_TAG, "Unable to read restrictions file "
2914 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002915 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002916 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002917 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2918 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002919 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002920 } catch (IOException|XmlPullParserException e) {
2921 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002922 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002923 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002924 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002925 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002926 }
2927
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002928 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2929 XmlPullParser parser) throws XmlPullParserException, IOException {
2930 int type = parser.getEventType();
2931 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2932 String key = parser.getAttributeValue(null, ATTR_KEY);
2933 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2934 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2935 if (multiple != null) {
2936 values.clear();
2937 int count = Integer.parseInt(multiple);
2938 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2939 if (type == XmlPullParser.START_TAG
2940 && parser.getName().equals(TAG_VALUE)) {
2941 values.add(parser.nextText().trim());
2942 count--;
2943 }
2944 }
2945 String [] valueStrings = new String[values.size()];
2946 values.toArray(valueStrings);
2947 restrictions.putStringArray(key, valueStrings);
2948 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2949 restrictions.putBundle(key, readBundleEntry(parser, values));
2950 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2951 final int outerDepth = parser.getDepth();
2952 ArrayList<Bundle> bundleList = new ArrayList<>();
2953 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2954 Bundle childBundle = readBundleEntry(parser, values);
2955 bundleList.add(childBundle);
2956 }
2957 restrictions.putParcelableArray(key,
2958 bundleList.toArray(new Bundle[bundleList.size()]));
2959 } else {
2960 String value = parser.nextText().trim();
2961 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2962 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2963 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2964 restrictions.putInt(key, Integer.parseInt(value));
2965 } else {
2966 restrictions.putString(key, value);
2967 }
2968 }
2969 }
2970 }
2971
2972 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2973 throws IOException, XmlPullParserException {
2974 Bundle childBundle = new Bundle();
2975 final int outerDepth = parser.getDepth();
2976 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2977 readEntry(childBundle, values, parser);
2978 }
2979 return childBundle;
2980 }
2981
Fyodor Kupolov82402752015-10-28 14:54:51 -07002982 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002983 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002984 AtomicFile restrictionsFile = new AtomicFile(
2985 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002986 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002987 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002988 }
2989
2990 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002991 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002992 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002993 try {
2994 fos = restrictionsFile.startWrite();
2995 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2996
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002997 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002998 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002999 serializer.startDocument(null, true);
3000 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3001
3002 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003003 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003004 serializer.endTag(null, TAG_RESTRICTIONS);
3005
3006 serializer.endDocument();
3007 restrictionsFile.finishWrite(fos);
3008 } catch (Exception e) {
3009 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003010 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3011 }
3012 }
3013
3014 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3015 throws IOException {
3016 for (String key : restrictions.keySet()) {
3017 Object value = restrictions.get(key);
3018 serializer.startTag(null, TAG_ENTRY);
3019 serializer.attribute(null, ATTR_KEY, key);
3020
3021 if (value instanceof Boolean) {
3022 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3023 serializer.text(value.toString());
3024 } else if (value instanceof Integer) {
3025 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3026 serializer.text(value.toString());
3027 } else if (value == null || value instanceof String) {
3028 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3029 serializer.text(value != null ? (String) value : "");
3030 } else if (value instanceof Bundle) {
3031 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3032 writeBundle((Bundle) value, serializer);
3033 } else if (value instanceof Parcelable[]) {
3034 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3035 Parcelable[] array = (Parcelable[]) value;
3036 for (Parcelable parcelable : array) {
3037 if (!(parcelable instanceof Bundle)) {
3038 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3039 }
3040 serializer.startTag(null, TAG_ENTRY);
3041 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3042 writeBundle((Bundle) parcelable, serializer);
3043 serializer.endTag(null, TAG_ENTRY);
3044 }
3045 } else {
3046 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3047 String[] values = (String[]) value;
3048 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3049 for (String choice : values) {
3050 serializer.startTag(null, TAG_VALUE);
3051 serializer.text(choice != null ? choice : "");
3052 serializer.endTag(null, TAG_VALUE);
3053 }
3054 }
3055 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003056 }
3057 }
3058
3059 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003060 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003061 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003062 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003063 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003064 }
3065 }
3066
3067 @Override
3068 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003069 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003070 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003071 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003072 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003073 }
3074 // Not found
3075 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003076 }
3077 }
3078
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003079 @Override
3080 public long getUserCreationTime(int userHandle) {
3081 int callingUserId = UserHandle.getCallingUserId();
3082 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003083 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003084 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003085 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003086 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003087 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003088 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003089 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003090 }
3091 }
3092 }
3093 if (userInfo == null) {
3094 throw new SecurityException("userHandle can only be the calling user or a managed "
3095 + "profile associated with this user");
3096 }
3097 return userInfo.creationTime;
3098 }
3099
Amith Yamasani0b285492011-04-14 17:35:23 -07003100 /**
3101 * Caches the list of user ids in an array, adjusting the array size when necessary.
3102 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003103 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003104 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003105 synchronized (mUsersLock) {
3106 final int userSize = mUsers.size();
3107 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003108 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003109 num++;
3110 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003111 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003112 final int[] newUsers = new int[num];
3113 int n = 0;
3114 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003115 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003116 newUsers[n++] = mUsers.keyAt(i);
3117 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003118 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003119 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003120 }
3121 }
3122
3123 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003124 * Called right before a user is started. This gives us a chance to prepare
3125 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003126 */
3127 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003128 UserInfo userInfo = getUserInfo(userId);
3129 if (userInfo == null) {
3130 return;
3131 }
3132 final int userSerial = userInfo.serialNumber;
3133 // Migrate only if build fingerprints mismatch
3134 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003135 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003136 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003137
3138 if (userId != UserHandle.USER_SYSTEM) {
3139 synchronized (mRestrictionsLock) {
3140 applyUserRestrictionsLR(userId);
3141 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003142 }
3143 }
3144
3145 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003146 * Called right before a user is unlocked. This gives us a chance to prepare
3147 * app storage.
3148 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003149 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003150 UserInfo userInfo = getUserInfo(userId);
3151 if (userInfo == null) {
3152 return;
3153 }
3154 final int userSerial = userInfo.serialNumber;
3155 // Migrate only if build fingerprints mismatch
3156 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003157 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003158 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003159 }
3160
3161 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003162 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003163 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003164 * @param userId the user that was just foregrounded
3165 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003166 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003167 UserData userData = getUserDataNoChecks(userId);
3168 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003169 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3170 return;
3171 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003172
3173 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003174 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003175 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003176 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003177 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3178 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003179 }
3180
3181 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003182 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003183 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003184 @VisibleForTesting
3185 int getNextAvailableId() {
3186 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003187 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003188 nextId = scanNextAvailableIdLocked();
3189 if (nextId >= 0) {
3190 return nextId;
3191 }
3192 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3193 // except most recently removed
3194 if (mRemovingUserIds.size() > 0) {
3195 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3196 mRemovingUserIds.clear();
3197 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3198 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003199 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003200 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003201 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003202 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003203 if (nextId < 0) {
3204 throw new IllegalStateException("No user id available!");
3205 }
3206 return nextId;
3207 }
3208
3209 private int scanNextAvailableIdLocked() {
3210 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3211 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3212 return i;
3213 }
3214 }
3215 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003216 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003217
Amith Yamasanifc95e702013-09-26 13:20:17 -07003218 private String packageToRestrictionsFileName(String packageName) {
3219 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3220 }
3221
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003222 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003223 * Enforce that serial number stored in user directory inode matches the
3224 * given expected value. Gracefully sets the serial number if currently
3225 * undefined.
3226 *
3227 * @throws IOException when problem extracting serial number, or serial
3228 * number is mismatched.
3229 */
3230 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003231 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3232 // When we're emulating FBE, the directory may have been chmod
3233 // 000'ed, meaning we can't read the serial number to enforce it;
3234 // instead of destroying the user, just log a warning.
3235 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3236 return;
3237 }
3238
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003239 final int foundSerial = getSerialNumber(file);
3240 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3241
3242 if (foundSerial == -1) {
3243 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3244 try {
3245 setSerialNumber(file, serialNumber);
3246 } catch (IOException e) {
3247 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3248 }
3249
3250 } else if (foundSerial != serialNumber) {
3251 throw new IOException("Found serial number " + foundSerial
3252 + " doesn't match expected " + serialNumber);
3253 }
3254 }
3255
3256 /**
3257 * Set serial number stored in user directory inode.
3258 *
3259 * @throws IOException if serial number was already set
3260 */
3261 private static void setSerialNumber(File file, int serialNumber)
3262 throws IOException {
3263 try {
3264 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3265 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3266 } catch (ErrnoException e) {
3267 throw e.rethrowAsIOException();
3268 }
3269 }
3270
3271 /**
3272 * Return serial number stored in user directory inode.
3273 *
3274 * @return parsed serial number, or -1 if not set
3275 */
3276 private static int getSerialNumber(File file) throws IOException {
3277 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003278 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3279 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003280 try {
3281 return Integer.parseInt(serial);
3282 } catch (NumberFormatException e) {
3283 throw new IOException("Bad serial number: " + serial);
3284 }
3285 } catch (ErrnoException e) {
3286 if (e.errno == OsConstants.ENODATA) {
3287 return -1;
3288 } else {
3289 throw e.rethrowAsIOException();
3290 }
3291 }
3292 }
3293
Amith Yamasani920ace02012-09-20 22:15:37 -07003294 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003295 public void setSeedAccountData(int userId, String accountName, String accountType,
3296 PersistableBundle accountOptions, boolean persist) {
3297 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3298 synchronized (mPackagesLock) {
3299 final UserData userData;
3300 synchronized (mUsersLock) {
3301 userData = getUserDataLU(userId);
3302 if (userData == null) {
3303 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3304 return;
3305 }
3306 userData.seedAccountName = accountName;
3307 userData.seedAccountType = accountType;
3308 userData.seedAccountOptions = accountOptions;
3309 userData.persistSeedData = persist;
3310 }
3311 if (persist) {
3312 writeUserLP(userData);
3313 }
3314 }
3315 }
3316
3317 @Override
3318 public String getSeedAccountName() throws RemoteException {
3319 checkManageUsersPermission("Cannot get seed account information");
3320 synchronized (mUsersLock) {
3321 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3322 return userData.seedAccountName;
3323 }
3324 }
3325
3326 @Override
3327 public String getSeedAccountType() throws RemoteException {
3328 checkManageUsersPermission("Cannot get seed account information");
3329 synchronized (mUsersLock) {
3330 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3331 return userData.seedAccountType;
3332 }
3333 }
3334
3335 @Override
3336 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3337 checkManageUsersPermission("Cannot get seed account information");
3338 synchronized (mUsersLock) {
3339 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3340 return userData.seedAccountOptions;
3341 }
3342 }
3343
3344 @Override
3345 public void clearSeedAccountData() throws RemoteException {
3346 checkManageUsersPermission("Cannot clear seed account information");
3347 synchronized (mPackagesLock) {
3348 UserData userData;
3349 synchronized (mUsersLock) {
3350 userData = getUserDataLU(UserHandle.getCallingUserId());
3351 if (userData == null) return;
3352 userData.clearSeedAccountData();
3353 }
3354 writeUserLP(userData);
3355 }
3356 }
3357
3358 @Override
3359 public boolean someUserHasSeedAccount(String accountName, String accountType)
3360 throws RemoteException {
3361 checkManageUsersPermission("Cannot check seed account information");
3362 synchronized (mUsersLock) {
3363 final int userSize = mUsers.size();
3364 for (int i = 0; i < userSize; i++) {
3365 final UserData data = mUsers.valueAt(i);
3366 if (data.info.isInitialized()) continue;
3367 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3368 continue;
3369 }
3370 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3371 continue;
3372 }
3373 return true;
3374 }
3375 }
3376 return false;
3377 }
3378
3379 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003380 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003381 FileDescriptor err, String[] args, ShellCallback callback,
3382 ResultReceiver resultReceiver) {
3383 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003384 }
3385
3386 int onShellCommand(Shell shell, String cmd) {
3387 if (cmd == null) {
3388 return shell.handleDefaultCommands(cmd);
3389 }
3390
3391 final PrintWriter pw = shell.getOutPrintWriter();
3392 try {
3393 switch(cmd) {
3394 case "list":
3395 return runList(pw);
3396 }
3397 } catch (RemoteException e) {
3398 pw.println("Remote exception: " + e);
3399 }
3400 return -1;
3401 }
3402
3403 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003404 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003405 final List<UserInfo> users = getUsers(false);
3406 if (users == null) {
3407 pw.println("Error: couldn't get users");
3408 return 1;
3409 } else {
3410 pw.println("Users:");
3411 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003412 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003413 pw.println("\t" + users.get(i).toString() + running);
3414 }
3415 return 0;
3416 }
3417 }
3418
3419 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003420 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3421 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3422 != PackageManager.PERMISSION_GRANTED) {
3423 pw.println("Permission Denial: can't dump UserManager from from pid="
3424 + Binder.getCallingPid()
3425 + ", uid=" + Binder.getCallingUid()
3426 + " without permission "
3427 + android.Manifest.permission.DUMP);
3428 return;
3429 }
3430
3431 long now = System.currentTimeMillis();
3432 StringBuilder sb = new StringBuilder();
3433 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003434 synchronized (mUsersLock) {
3435 pw.println("Users:");
3436 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003437 UserData userData = mUsers.valueAt(i);
3438 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003439 continue;
3440 }
Amith Yamasani12747872015-12-07 14:19:49 -08003441 UserInfo userInfo = userData.info;
3442 final int userId = userInfo.id;
3443 pw.print(" "); pw.print(userInfo);
3444 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003445 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003446 pw.print(" <removing> ");
3447 }
Amith Yamasani12747872015-12-07 14:19:49 -08003448 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003449 pw.print(" <partial>");
3450 }
3451 pw.println();
3452 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003453 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003454 pw.println("<unknown>");
3455 } else {
3456 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003457 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003458 sb.append(" ago");
3459 pw.println(sb);
3460 }
3461 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003462 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003463 pw.println("<unknown>");
3464 } else {
3465 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003466 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003467 sb.append(" ago");
3468 pw.println(sb);
3469 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003470 pw.print(" Last logged in fingerprint: ");
3471 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003472 pw.print(" Has profile owner: ");
3473 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003474 pw.println(" Restrictions:");
3475 synchronized (mRestrictionsLock) {
3476 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003477 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003478 pw.println(" Device policy global restrictions:");
3479 UserRestrictionsUtils.dumpRestrictions(
3480 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003481 pw.println(" Device policy local restrictions:");
3482 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003483 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003484 pw.println(" Effective restrictions:");
3485 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003486 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003487 }
Amith Yamasani12747872015-12-07 14:19:49 -08003488
3489 if (userData.account != null) {
3490 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003491 pw.println();
3492 }
Amith Yamasani12747872015-12-07 14:19:49 -08003493
3494 if (userData.seedAccountName != null) {
3495 pw.print(" Seed account name: " + userData.seedAccountName);
3496 pw.println();
3497 if (userData.seedAccountType != null) {
3498 pw.print(" account type: " + userData.seedAccountType);
3499 pw.println();
3500 }
3501 if (userData.seedAccountOptions != null) {
3502 pw.print(" account options exist");
3503 pw.println();
3504 }
3505 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003506 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003507 }
Amith Yamasani12747872015-12-07 14:19:49 -08003508 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003509 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003510 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003511 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003512 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003513 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003514 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003515 synchronized (mUsersLock) {
3516 pw.println();
3517 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003518 if (mRemovingUserIds.size() > 0) {
3519 pw.println();
3520 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3521 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003522 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003523 synchronized (mUserStates) {
3524 pw.println(" Started users state: " + mUserStates);
3525 }
Amith Yamasani12747872015-12-07 14:19:49 -08003526 // Dump some capabilities
3527 pw.println();
3528 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3529 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003530 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3531 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003532 }
3533 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003534
3535 final class MainHandler extends Handler {
3536
3537 @Override
3538 public void handleMessage(Message msg) {
3539 switch (msg.what) {
3540 case WRITE_USER_MSG:
3541 removeMessages(WRITE_USER_MSG, msg.obj);
3542 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003543 int userId = ((UserData) msg.obj).info.id;
3544 UserData userData = getUserDataNoChecks(userId);
3545 if (userData != null) {
3546 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003547 }
3548 }
3549 }
3550 }
3551 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003552
3553 /**
3554 * @param userId
3555 * @return whether the user has been initialized yet
3556 */
3557 boolean isInitialized(int userId) {
3558 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3559 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003560
3561 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003562 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003563 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3564 boolean isDeviceOwner, int cameraRestrictionScope) {
3565 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3566 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003567 }
3568
3569 @Override
3570 public Bundle getBaseUserRestrictions(int userId) {
3571 synchronized (mRestrictionsLock) {
3572 return mBaseUserRestrictions.get(userId);
3573 }
3574 }
3575
3576 @Override
3577 public void setBaseUserRestrictionsByDpmsForMigration(
3578 int userId, Bundle baseRestrictions) {
3579 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003580 if (updateRestrictionsIfNeededLR(
3581 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3582 invalidateEffectiveUserRestrictionsLR(userId);
3583 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003584 }
3585
Amith Yamasani12747872015-12-07 14:19:49 -08003586 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003587 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003588 if (userData != null) {
3589 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003590 } else {
3591 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3592 }
3593 }
3594 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003595
3596 @Override
3597 public boolean getUserRestriction(int userId, String key) {
3598 return getUserRestrictions(userId).getBoolean(key);
3599 }
3600
3601 @Override
3602 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3603 synchronized (mUserRestrictionsListeners) {
3604 mUserRestrictionsListeners.add(listener);
3605 }
3606 }
3607
3608 @Override
3609 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3610 synchronized (mUserRestrictionsListeners) {
3611 mUserRestrictionsListeners.remove(listener);
3612 }
3613 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003614
3615 @Override
3616 public void setDeviceManaged(boolean isManaged) {
3617 synchronized (mUsersLock) {
3618 mIsDeviceManaged = isManaged;
3619 }
3620 }
3621
3622 @Override
3623 public void setUserManaged(int userId, boolean isManaged) {
3624 synchronized (mUsersLock) {
3625 mIsUserManaged.put(userId, isManaged);
3626 }
3627 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003628
3629 @Override
3630 public void setUserIcon(int userId, Bitmap bitmap) {
3631 long ident = Binder.clearCallingIdentity();
3632 try {
3633 synchronized (mPackagesLock) {
3634 UserData userData = getUserDataNoChecks(userId);
3635 if (userData == null || userData.info.partial) {
3636 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3637 return;
3638 }
3639 writeBitmapLP(userData.info, bitmap);
3640 writeUserLP(userData);
3641 }
3642 sendUserInfoChangedBroadcast(userId);
3643 } finally {
3644 Binder.restoreCallingIdentity(ident);
3645 }
3646 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003647
3648 @Override
3649 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3650 synchronized (mUsersLock) {
3651 mForceEphemeralUsers = forceEphemeralUsers;
3652 }
3653 }
3654
3655 @Override
3656 public void removeAllUsers() {
3657 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3658 // Remove the non-system users straight away.
3659 removeNonSystemUsers();
3660 } else {
3661 // Switch to the system user first and then remove the other users.
3662 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3663 @Override
3664 public void onReceive(Context context, Intent intent) {
3665 int userId =
3666 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3667 if (userId != UserHandle.USER_SYSTEM) {
3668 return;
3669 }
3670 mContext.unregisterReceiver(this);
3671 removeNonSystemUsers();
3672 }
3673 };
3674 IntentFilter userSwitchedFilter = new IntentFilter();
3675 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3676 mContext.registerReceiver(
3677 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3678
3679 // Switch to the system user.
3680 ActivityManager am =
3681 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3682 am.switchUser(UserHandle.USER_SYSTEM);
3683 }
3684 }
phweisse9c44062016-02-10 12:57:38 +01003685
3686 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003687 public void onEphemeralUserStop(int userId) {
3688 synchronized (mUsersLock) {
3689 UserInfo userInfo = getUserInfoLU(userId);
3690 if (userInfo != null && userInfo.isEphemeral()) {
3691 // Do not allow switching back to the ephemeral user again as the user is going
3692 // to be deleted.
3693 userInfo.flags |= UserInfo.FLAG_DISABLED;
3694 if (userInfo.isGuest()) {
3695 // Indicate that the guest will be deleted after it stops.
3696 userInfo.guestToRemove = true;
3697 }
3698 }
3699 }
3700 }
3701
3702 @Override
phweisse9c44062016-02-10 12:57:38 +01003703 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003704 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003705 // Keep this in sync with UserManager.createUser
3706 if (user != null && !user.isAdmin()) {
3707 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3708 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3709 }
3710 return user;
3711 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003712
3713 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003714 public boolean removeUserEvenWhenDisallowed(int userId) {
3715 return removeUserUnchecked(userId);
3716 }
3717
3718 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003719 public boolean isUserRunning(int userId) {
3720 synchronized (mUserStates) {
3721 return mUserStates.get(userId, -1) >= 0;
3722 }
3723 }
3724
3725 @Override
3726 public void setUserState(int userId, int userState) {
3727 synchronized (mUserStates) {
3728 mUserStates.put(userId, userState);
3729 }
3730 }
3731
3732 @Override
3733 public void removeUserState(int userId) {
3734 synchronized (mUserStates) {
3735 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003736 }
3737 }
3738
3739 @Override
3740 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003741 synchronized (mUserStates) {
3742 int state = mUserStates.get(userId, -1);
3743 return (state == UserState.STATE_RUNNING_UNLOCKING)
3744 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003745 }
3746 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003747
3748 @Override
3749 public boolean isUserUnlocked(int userId) {
3750 synchronized (mUserStates) {
3751 int state = mUserStates.get(userId, -1);
3752 return state == UserState.STATE_RUNNING_UNLOCKED;
3753 }
3754 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003755 }
3756
3757 /* Remove all the users except of the system one. */
3758 private void removeNonSystemUsers() {
3759 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3760 synchronized (mUsersLock) {
3761 final int userSize = mUsers.size();
3762 for (int i = 0; i < userSize; i++) {
3763 UserInfo ui = mUsers.valueAt(i).info;
3764 if (ui.id != UserHandle.USER_SYSTEM) {
3765 usersToRemove.add(ui);
3766 }
3767 }
3768 }
3769 for (UserInfo ui: usersToRemove) {
3770 removeUser(ui.id);
3771 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003772 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003773
3774 private class Shell extends ShellCommand {
3775 @Override
3776 public int onCommand(String cmd) {
3777 return onShellCommand(this, cmd);
3778 }
3779
3780 @Override
3781 public void onHelp() {
3782 final PrintWriter pw = getOutPrintWriter();
3783 pw.println("User manager (user) commands:");
3784 pw.println(" help");
3785 pw.println(" Print this help text.");
3786 pw.println("");
3787 pw.println(" list");
3788 pw.println(" Prints all users on the system.");
3789 }
3790 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003791
3792 private static void debug(String message) {
3793 Log.d(LOG_TAG, message +
3794 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3795 }
Kenny Guy02c89902016-11-15 19:36:38 +00003796
3797 @VisibleForTesting
3798 static int getMaxManagedProfiles() {
3799 // Allow overriding max managed profiles on debuggable builds for testing
3800 // of multiple profiles.
3801 if (!Build.IS_DEBUGGABLE) {
3802 return MAX_MANAGED_PROFILES;
3803 } else {
3804 return SystemProperties.getInt("persist.sys.max_profiles",
3805 MAX_MANAGED_PROFILES);
3806 }
3807 }
3808
3809 @VisibleForTesting
3810 int getFreeProfileBadgeLU(int parentUserId) {
3811 int maxManagedProfiles = getMaxManagedProfiles();
3812 boolean[] usedBadges = new boolean[maxManagedProfiles];
3813 final int userSize = mUsers.size();
3814 for (int i = 0; i < userSize; i++) {
3815 UserInfo ui = mUsers.valueAt(i).info;
3816 // Check which badge indexes are already used by this profile group.
3817 if (ui.isManagedProfile()
3818 && ui.profileGroupId == parentUserId
3819 && !mRemovingUserIds.get(ui.id)
3820 && ui.profileBadge < maxManagedProfiles) {
3821 usedBadges[ui.profileBadge] = true;
3822 }
3823 }
3824 for (int i = 0; i < maxManagedProfiles; i++) {
3825 if (!usedBadges[i]) {
3826 return i;
3827 }
3828 }
3829 return 0;
3830 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003831
3832 /**
3833 * Checks if the given user has a managed profile associated with it.
3834 * @param userId The parent user
3835 * @return
3836 */
3837 boolean hasManagedProfile(int userId) {
3838 synchronized (mUsersLock) {
3839 UserInfo userInfo = getUserInfoLU(userId);
3840 final int userSize = mUsers.size();
3841 for (int i = 0; i < userSize; i++) {
3842 UserInfo profile = mUsers.valueAt(i).info;
3843 if (userId != profile.id && isProfileOf(userInfo, profile)) {
3844 return true;
3845 }
3846 }
3847 return false;
3848 }
3849 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003850}