blob: c18ca25d8c1f6c66d511d3db44ec4794fc49c6f4 [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;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.content.Context;
36import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010037import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010038import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070039import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080040import android.content.pm.PackageManager.NameNotFoundException;
Tony Make3d1f652017-12-12 11:00:37 +000041import android.content.pm.ShortcutServiceInternal;
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;
Tony Mak64fd8c02017-12-01 19:11:59 +000053import android.os.IProgressListener;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080055import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010056import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080058import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070060import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010062import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Makoto Onuki73dded22017-12-20 13:14:48 +090066import android.os.SystemClock;
Kenny Guy02c89902016-11-15 19:36:38 +000067import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070069import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010070import android.os.UserManager.EnforcingUser;
Makoto Onuki068c54a2015-10-13 14:34:03 -070071import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080072import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010073import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070074import android.security.GateKeeper;
75import android.service.gatekeeper.IGateKeeperService;
Amith Yamasani2a003292012-08-14 18:25:45 -070076import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070077import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070078import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import android.util.Slog;
80import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080081import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000082import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070083import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084import android.util.Xml;
85
Makoto Onuki068c54a2015-10-13 14:34:03 -070086import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070087import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040088import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080089import com.android.internal.logging.MetricsLogger;
Fyodor Kupolova68a2862018-01-30 18:22:00 -080090import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060091import com.android.internal.util.DumpUtils;
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;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060097import com.android.server.LockGuard;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070098import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000099import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -0700100import com.android.server.storage.DeviceStorageMonitorInternal;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700101import com.android.server.wm.ActivityTaskManagerInternal;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800102
103import org.xmlpull.v1.XmlPullParser;
104import org.xmlpull.v1.XmlPullParserException;
105import org.xmlpull.v1.XmlSerializer;
106
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107import java.io.BufferedOutputStream;
108import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700109import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112import java.io.FileOutputStream;
Tony Mak64fd8c02017-12-01 19:11:59 +0000113import java.io.IOException;
Kenny Guy02c89902016-11-15 19:36:38 +0000114import java.io.InputStream;
115import java.io.OutputStream;
Amith Yamasani920ace02012-09-20 22:15:37 -0700116import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100117import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118import java.util.ArrayList;
Pavel Grafov6a40f092016-10-25 15:46:51 +0100119import java.util.Collections;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700120import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000122import java.util.Objects;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700124import libcore.io.IoUtils;
125
Makoto Onuki068c54a2015-10-13 14:34:03 -0700126/**
127 * Service for {@link UserManager}.
128 *
129 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700130 * <ul>
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700131 * <li> Methods suffixed with "LAr" should be called within the {@link #mAppRestrictionsLock} lock.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800132 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700133 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
134 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
135 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700136 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700137public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700138
Amith Yamasani2a003292012-08-14 18:25:45 -0700139 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800140 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800141 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700142 // Can be used for manual testing of id recycling
143 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700144
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800146 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700148 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700150 private static final String ATTR_CREATION_TIME = "created";
151 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600152 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700153 private static final String ATTR_SERIAL_NO = "serialNumber";
154 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700155 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700156 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700157 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100158 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Kenny Guy02c89902016-11-15 19:36:38 +0000159 private static final String ATTR_PROFILE_BADGE = "profileBadge";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700160 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800161 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
162 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530163 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700165 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800166 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800167 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100168 private static final String TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS =
169 "device_policy_global_restrictions";
170 /** Legacy name for device owner id tag. */
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100171 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Pavel Grafov6a40f092016-10-25 15:46:51 +0100172 private static final String TAG_DEVICE_OWNER_USER_ID = "deviceOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800173 private static final String TAG_ENTRY = "entry";
174 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800175 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800176 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700177 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700180 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
181 private static final String ATTR_TYPE_STRING = "s";
182 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700183 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700184 private static final String ATTR_TYPE_BUNDLE = "B";
185 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700186
Amith Yamasani0b285492011-04-14 17:35:23 -0700187 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700189 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100190 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800192 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700193 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800194
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700195 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
196 UserInfo.FLAG_MANAGED_PROFILE
197 | UserInfo.FLAG_EPHEMERAL
198 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700199 | UserInfo.FLAG_GUEST
200 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700201
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700202 @VisibleForTesting
203 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700204 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700205 @VisibleForTesting
206 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
207
208 // Max size of the queue of recently removed users
209 @VisibleForTesting
210 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700211
Pavel Grafov6a40f092016-10-25 15:46:51 +0100212 private static final int USER_VERSION = 7;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700213
Amith Yamasani920ace02012-09-20 22:15:37 -0700214 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
215
Nicolas Prevotb8186812015-08-06 15:00:03 +0100216 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700217 // without first making sure that the rest of the framework is prepared for it.
Kenny Guy02c89902016-11-15 19:36:38 +0000218 @VisibleForTesting
219 static final int MAX_MANAGED_PROFILES = 1;
Amith Yamasani95ab7842014-08-11 17:09:26 -0700220
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800221 static final int WRITE_USER_MSG = 1;
222 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530223
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800224 // Tron counters
225 private static final String TRON_GUEST_CREATED = "users_guest_created";
226 private static final String TRON_USER_CREATED = "users_user_created";
Christine Franks88220562017-05-24 11:11:21 -0700227 private static final String TRON_DEMO_CREATED = "users_demo_created";
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800228
Dianne Hackborn4428e172012-08-24 17:43:05 -0700229 private final Context mContext;
230 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700231 private final Object mPackagesLock;
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800232 private final UserDataPreparer mUserDataPreparer;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700233 // Short-term lock for internal state, when interaction/sync with PM is not required
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600234 private final Object mUsersLock = LockGuard.installNewLock(LockGuard.INDEX_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700235 private final Object mRestrictionsLock = new Object();
Fyodor Kupolovd31cee92017-09-05 16:31:08 -0700236 // Used for serializing access to app restriction files
237 private final Object mAppRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700238
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800239 private final Handler mHandler;
240
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700241 private final File mUsersDir;
242 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700243
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800244 private static final IBinder mUserRestriconToken = new Binder();
245
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 /**
Makoto Onuki73dded22017-12-20 13:14:48 +0900247 * Internal non-parcelable wrapper for UserInfo that is not exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800248 */
Kenny Guy02c89902016-11-15 19:36:38 +0000249 @VisibleForTesting
250 static class UserData {
Amith Yamasani12747872015-12-07 14:19:49 -0800251 // Basic user information and properties
252 UserInfo info;
253 // Account name used when there is a strong association between a user and an account
254 String account;
255 // Account information for seeding into a newly created user. This could also be
256 // used for login validation for an existing user, for updating their credentials.
257 // In the latter case, data may not need to be persisted as it is only valid for the
258 // current login session.
259 String seedAccountName;
260 String seedAccountType;
261 PersistableBundle seedAccountOptions;
262 // Whether to perist the seed account information to be available after a boot
263 boolean persistSeedData;
264
Makoto Onuki73dded22017-12-20 13:14:48 +0900265 /** Elapsed realtime since boot when the user started. */
266 long startRealtime;
267
268 /** Elapsed realtime since boot when the user was unlocked. */
269 long unlockRealtime;
270
Amith Yamasani12747872015-12-07 14:19:49 -0800271 void clearSeedAccountData() {
272 seedAccountName = null;
273 seedAccountType = null;
274 seedAccountOptions = null;
275 persistSeedData = false;
276 }
277 }
278
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800279 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800280 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800281
282 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700283 * User restrictions set via UserManager. This doesn't include restrictions set by
Pavel Grafov6a40f092016-10-25 15:46:51 +0100284 * device owner / profile owners. Only non-empty restriction bundles are stored.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700285 *
286 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
287 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
288 * maybe shared between {@link #mBaseUserRestrictions} and
289 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
290 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700291 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700292 */
293 @GuardedBy("mRestrictionsLock")
294 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
295
296 /**
297 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
298 * with device / profile owner restrictions. We'll initialize it lazily; use
299 * {@link #getEffectiveUserRestrictions} to access it.
300 *
301 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
302 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
303 * maybe shared between {@link #mBaseUserRestrictions} and
304 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
305 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700306 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700307 */
308 @GuardedBy("mRestrictionsLock")
309 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
310
Makoto Onuki4f160732015-10-27 17:15:38 -0700311 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800312 * User restrictions that have already been applied in
313 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
314 * that have changed since the last
315 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700316 */
317 @GuardedBy("mRestrictionsLock")
318 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
319
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800320 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800321 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100322 * that should be applied to all users, including guests. Only non-empty restriction bundles are
323 * stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800324 */
325 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100326 private final SparseArray<Bundle> mDevicePolicyGlobalUserRestrictions = new SparseArray<>();
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800327
328 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100329 * Id of the user that set global restrictions.
330 */
331 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +0100332 private int mDeviceOwnerUserId = UserHandle.USER_NULL;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100333
334 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800335 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
Pavel Grafov6a40f092016-10-25 15:46:51 +0100336 * for each user. Only non-empty restriction bundles are stored.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800337 */
338 @GuardedBy("mRestrictionsLock")
339 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
340
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800341 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530342 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800343
344 /**
345 * Set of user IDs being actively removed. Removed IDs linger in this set
346 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700347 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800348 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700349 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800350 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700351
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700352 /**
353 * Queue of recently removed userIds. Used for recycling of userIds
354 */
355 @GuardedBy("mUsersLock")
356 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
357
Fyodor Kupolov82402752015-10-28 14:54:51 -0700358 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700359 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800360 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700361 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700362 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700363
Jason Monk62062992014-05-06 09:55:28 -0400364 private IAppOpsService mAppOpsService;
365
Makoto Onuki068c54a2015-10-13 14:34:03 -0700366 private final LocalService mLocalService;
367
Makoto Onukie7927da2015-11-25 10:05:17 -0800368 @GuardedBy("mUsersLock")
369 private boolean mIsDeviceManaged;
370
371 @GuardedBy("mUsersLock")
372 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
373
Makoto Onukid45a4a22015-11-02 17:17:38 -0800374 @GuardedBy("mUserRestrictionsListeners")
375 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
376 new ArrayList<>();
377
Clara Bayarria1771112015-12-18 16:29:18 +0000378 private final LockPatternUtils mLockPatternUtils;
379
Ricky Waib1dd80b2016-06-07 18:00:55 +0100380 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
381 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
382
383 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
384 @Override
385 public void onReceive(Context context, Intent intent) {
Tony Mak64fd8c02017-12-01 19:11:59 +0000386 if (!ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
387 return;
Ricky Waib1dd80b2016-06-07 18:00:55 +0100388 }
Tony Mak64fd8c02017-12-01 19:11:59 +0000389 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
390 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL);
Fyodor Kupolova68a2862018-01-30 18:22:00 -0800391 // Call setQuietModeEnabled on bg thread to avoid ANR
392 BackgroundThread.getHandler()
393 .post(() -> setQuietModeEnabled(userHandle, false, target));
Ricky Waib1dd80b2016-06-07 18:00:55 +0100394 }
395 };
396
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100397 /**
Tony Mak64fd8c02017-12-01 19:11:59 +0000398 * Start an {@link IntentSender} when user is unlocked after disabling quiet mode.
399 *
Tony Makbece85d2018-01-12 12:10:17 +0000400 * @see {@link #requestQuietModeEnabled(String, boolean, int, IntentSender)}
Tony Mak64fd8c02017-12-01 19:11:59 +0000401 */
402 private class DisableQuietModeUserUnlockedCallback extends IProgressListener.Stub {
403 private final IntentSender mTarget;
404
405 public DisableQuietModeUserUnlockedCallback(IntentSender target) {
406 Preconditions.checkNotNull(target);
407 mTarget = target;
408 }
409
410 @Override
411 public void onStarted(int id, Bundle extras) {}
412
413 @Override
414 public void onProgress(int id, int progress, Bundle extras) {}
415
416 @Override
417 public void onFinished(int id, Bundle extras) {
418 try {
419 mContext.startIntentSender(mTarget, null, 0, 0, 0);
420 } catch (IntentSender.SendIntentException e) {
421 Slog.e(LOG_TAG, "Failed to start the target in the callback", e);
422 }
423 }
424 }
425
426 /**
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100427 * Whether all users should be created ephemeral.
428 */
429 @GuardedBy("mUsersLock")
430 private boolean mForceEphemeralUsers;
431
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000432 @GuardedBy("mUserStates")
433 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700434
Amith Yamasani258848d2012-08-10 17:06:33 -0700435 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700436
Dianne Hackborn4428e172012-08-24 17:43:05 -0700437 public static UserManagerService getInstance() {
438 synchronized (UserManagerService.class) {
439 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700440 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700441 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700442
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700443 public static class LifeCycle extends SystemService {
444
445 private UserManagerService mUms;
446
447 /**
448 * @param context
449 */
450 public LifeCycle(Context context) {
451 super(context);
452 }
453
454 @Override
455 public void onStart() {
456 mUms = UserManagerService.getInstance();
457 publishBinderService(Context.USER_SERVICE, mUms);
458 }
459
460 @Override
461 public void onBootPhase(int phase) {
462 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
463 mUms.cleanupPartialUsers();
464 }
465 }
Makoto Onuki73dded22017-12-20 13:14:48 +0900466
467 @Override
468 public void onStartUser(int userHandle) {
469 synchronized (mUms.mUsersLock) {
470 final UserData user = mUms.getUserDataLU(userHandle);
471 if (user != null) {
472 user.startRealtime = SystemClock.elapsedRealtime();
473 }
474 }
475 }
476
477 @Override
478 public void onUnlockUser(int userHandle) {
479 synchronized (mUms.mUsersLock) {
480 final UserData user = mUms.getUserDataLU(userHandle);
481 if (user != null) {
482 user.unlockRealtime = SystemClock.elapsedRealtime();
483 }
484 }
485 }
486
487 @Override
488 public void onStopUser(int userHandle) {
489 synchronized (mUms.mUsersLock) {
490 final UserData user = mUms.getUserDataLU(userHandle);
491 if (user != null) {
492 user.startRealtime = 0;
493 user.unlockRealtime = 0;
494 }
495 }
496 }
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700497 }
498
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700499 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800500 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700501 UserManagerService(Context context) {
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800502 this(context, null, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700503 }
504
Dianne Hackborn4428e172012-08-24 17:43:05 -0700505 /**
506 * Called by package manager to create the service. This is closely
507 * associated with the package manager, and the given lock is the
508 * package manager's own lock.
509 */
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800510 UserManagerService(Context context, PackageManagerService pm, UserDataPreparer userDataPreparer,
511 Object packagesLock) {
512 this(context, pm, userDataPreparer, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700513 }
514
Dianne Hackborn4428e172012-08-24 17:43:05 -0700515 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800516 UserDataPreparer userDataPreparer, Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700517 mContext = context;
518 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700519 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800520 mHandler = new MainHandler();
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -0800521 mUserDataPreparer = userDataPreparer;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800522 synchronized (mPackagesLock) {
523 mUsersDir = new File(dataDir, USER_INFO_DIR);
524 mUsersDir.mkdirs();
525 // Make zeroth user directory, for services to migrate their files to that location
526 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
527 userZeroDir.mkdirs();
528 FileUtils.setPermissions(mUsersDir.toString(),
529 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
530 -1, -1);
531 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
532 initDefaultGuestRestrictions();
533 readUserListLP();
534 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700535 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700536 mLocalService = new LocalService();
537 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000538 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000539 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700540 }
541
542 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400543 mAppOpsService = IAppOpsService.Stub.asInterface(
544 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800545
546 synchronized (mRestrictionsLock) {
547 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400548 }
Samuel Tand9453b82016-03-14 15:57:02 -0700549
550 UserInfo currentGuestUser = findCurrentGuestUser();
551 if (currentGuestUser != null && !hasUserRestriction(
552 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
553 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
554 // to it, in case this guest was created in a previous version where this
555 // user restriction was not a default guest restriction.
556 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
557 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700558
Ricky Waib1dd80b2016-06-07 18:00:55 +0100559 mContext.registerReceiver(mDisableQuietModeCallback,
560 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
561 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700562 }
563
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700564 void cleanupPartialUsers() {
565 // Prune out any partially created, partially removed and ephemeral users.
566 ArrayList<UserInfo> partials = new ArrayList<>();
567 synchronized (mUsersLock) {
568 final int userSize = mUsers.size();
569 for (int i = 0; i < userSize; i++) {
570 UserInfo ui = mUsers.valueAt(i).info;
571 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
572 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700573 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700574 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700575 }
576 }
577 }
578 final int partialsSize = partials.size();
579 for (int i = 0; i < partialsSize; i++) {
580 UserInfo ui = partials.get(i);
581 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
582 + " (name=" + ui.name + ")");
583 removeUserState(ui.id);
584 }
585 }
586
Amith Yamasani258848d2012-08-10 17:06:33 -0700587 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800588 public String getUserAccount(int userId) {
589 checkManageUserAndAcrossUsersFullPermission("get user account");
590 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800591 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800592 }
593 }
594
595 @Override
596 public void setUserAccount(int userId, String accountName) {
597 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800598 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800599 synchronized (mPackagesLock) {
600 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800601 final UserData userData = mUsers.get(userId);
602 if (userData == null) {
603 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
604 return;
605 }
606 String currentAccount = userData.account;
Narayan Kamath607223f2018-02-19 14:09:02 +0000607 if (!Objects.equals(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800608 userData.account = accountName;
609 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800610 }
611 }
612
613 if (userToUpdate != null) {
614 writeUserLP(userToUpdate);
615 }
616 }
617 }
618
619 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700620 public UserInfo getPrimaryUser() {
621 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700622 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700623 final int userSize = mUsers.size();
624 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800625 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800626 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700627 return ui;
628 }
629 }
630 }
631 return null;
632 }
633
634 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700635 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700636 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700637 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700638 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700639 final int userSize = mUsers.size();
640 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800641 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700642 if (ui.partial) {
643 continue;
644 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800645 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700646 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700647 }
Amith Yamasani13593602012-03-22 16:16:17 -0700648 }
649 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700650 }
Amith Yamasani13593602012-03-22 16:16:17 -0700651 }
652
Amith Yamasani258848d2012-08-10 17:06:33 -0700653 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100654 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700655 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800656 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700657 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700658 } else {
659 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800660 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700661 final long ident = Binder.clearCallingIdentity();
662 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700663 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700664 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100665 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700666 } finally {
667 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000668 }
669 }
670
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700671 @Override
672 public int[] getProfileIds(int userId, boolean enabledOnly) {
673 if (userId != UserHandle.getCallingUserId()) {
bohu12d23a12016-09-26 16:20:07 -0700674 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700675 }
676 final long ident = Binder.clearCallingIdentity();
677 try {
678 synchronized (mUsersLock) {
679 return getProfileIdsLU(userId, enabledOnly).toArray();
680 }
681 } finally {
682 Binder.restoreCallingIdentity(ident);
683 }
684 }
685
Amith Yamasanibe465322014-04-24 13:45:17 -0700686 /** Assume permissions already checked and caller's identity cleared */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700687 @GuardedBy("mUsersLock")
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700688 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700689 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
690 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
691 for (int i = 0; i < profileIds.size(); i++) {
692 int profileId = profileIds.get(i);
693 UserInfo userInfo = mUsers.get(profileId).info;
694 // If full info is not required - clear PII data to prevent 3P apps from reading it
695 if (!fullInfo) {
696 userInfo = new UserInfo(userInfo);
697 userInfo.name = null;
698 userInfo.iconPath = null;
699 } else {
700 userInfo = userWithName(userInfo);
701 }
702 users.add(userInfo);
703 }
704 return users;
705 }
706
707 /**
708 * Assume permissions already checked and caller's identity cleared
709 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700710 @GuardedBy("mUsersLock")
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700711 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700712 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700713 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700714 if (user == null) {
715 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700716 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700717 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700718 final int userSize = mUsers.size();
719 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800720 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700721 if (!isProfileOf(user, profile)) {
722 continue;
723 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100724 if (enabledOnly && !profile.isEnabled()) {
725 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700726 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700727 if (mRemovingUserIds.get(profile.id)) {
728 continue;
729 }
Tony Mak80189cd2016-04-05 17:21:42 +0100730 if (profile.partial) {
731 continue;
732 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700733 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700734 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700735 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700736 }
737
Jessica Hummelbe81c802014-04-22 15:49:22 +0100738 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700739 public int getCredentialOwnerProfile(int userHandle) {
740 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000741 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700742 synchronized (mUsersLock) {
743 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700744 if (profileParent != null) {
745 return profileParent.id;
746 }
747 }
748 }
749
750 return userHandle;
751 }
752
753 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700754 public boolean isSameProfileGroup(int userId, int otherUserId) {
755 if (userId == otherUserId) return true;
756 checkManageUsersPermission("check if in the same profile group");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700757 return isSameProfileGroupNoChecks(userId, otherUserId);
758 }
759
760 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700761 synchronized (mUsersLock) {
762 UserInfo userInfo = getUserInfoLU(userId);
763 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
764 return false;
765 }
766 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
767 if (otherUserInfo == null
768 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
769 return false;
770 }
771 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700772 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700773 }
774
775 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100776 public UserInfo getProfileParent(int userHandle) {
777 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700778 synchronized (mUsersLock) {
779 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700780 }
781 }
782
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800783 @Override
784 public int getProfileParentId(int userHandle) {
785 checkManageUsersPermission("get the profile parent");
Sunny Goyal145c8f82018-02-15 14:27:09 -0800786 return mLocalService.getProfileParentId(userHandle);
Jakub Pawlowski0f1f5b72017-11-15 14:50:43 -0800787 }
788
Andreas Gampe2e8c7672018-07-20 13:01:08 -0700789 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700790 private UserInfo getProfileParentLU(int userHandle) {
791 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700792 if (profile == null) {
793 return null;
794 }
795 int parentUserId = profile.profileGroupId;
Amith Yamasani801e3422017-01-25 11:35:44 -0800796 if (parentUserId == userHandle || parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700797 return null;
798 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700799 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100800 }
801 }
802
Fyodor Kupolov82402752015-10-28 14:54:51 -0700803 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100804 return user.id == profile.id ||
805 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
806 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000807 }
808
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000809 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000810 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100811 Intent intent = new Intent();
812 if (inQuietMode) {
813 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
814 } else {
815 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
816 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000817 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
818 intent.putExtra(Intent.EXTRA_USER, profileHandle);
819 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000820 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000821 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000822 }
823
824 @Override
Tony Makbece85d2018-01-12 12:10:17 +0000825 public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode,
Tony Make3d1f652017-12-12 11:00:37 +0000826 int userHandle, @Nullable IntentSender target) {
827 Preconditions.checkNotNull(callingPackage);
828
Tony Makb7e6fd42017-12-05 19:40:28 +0000829 if (enableQuietMode && target != null) {
830 throw new IllegalArgumentException(
831 "target should only be specified when we are disabling quiet mode.");
832 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000833
Tony Makd390ae92017-12-28 13:23:10 +0000834 ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null);
Tony Makb7e6fd42017-12-05 19:40:28 +0000835 final long identity = Binder.clearCallingIdentity();
836 try {
837 if (enableQuietMode) {
838 setQuietModeEnabled(userHandle, true /* enableQuietMode */, target);
839 return true;
840 } else {
841 boolean needToShowConfirmCredential =
842 mLockPatternUtils.isSecure(userHandle)
843 && !StorageManager.isUserKeyUnlocked(userHandle);
844 if (needToShowConfirmCredential) {
845 showConfirmCredentialToDisableQuietMode(userHandle, target);
846 return false;
847 } else {
848 setQuietModeEnabled(userHandle, false /* enableQuietMode */, target);
849 return true;
850 }
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000851 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000852 } finally {
853 Binder.restoreCallingIdentity(identity);
854 }
855 }
856
Tony Make3d1f652017-12-12 11:00:37 +0000857 /**
Tony Makd390ae92017-12-28 13:23:10 +0000858 * The caller can modify quiet mode if it meets one of these conditions:
Tony Make3d1f652017-12-12 11:00:37 +0000859 * <ul>
860 * <li>Has system UID or root UID</li>
861 * <li>Has {@link Manifest.permission#MODIFY_QUIET_MODE}</li>
862 * <li>Has {@link Manifest.permission#MANAGE_USERS}</li>
863 * </ul>
Tony Makd390ae92017-12-28 13:23:10 +0000864 * <p>
865 * If caller wants to start an intent after disabling the quiet mode, it must has
866 * {@link Manifest.permission#MANAGE_USERS}.
Tony Make3d1f652017-12-12 11:00:37 +0000867 */
Tony Makd390ae92017-12-28 13:23:10 +0000868 private void ensureCanModifyQuietMode(String callingPackage, int callingUid,
869 boolean startIntent) {
Tony Make3d1f652017-12-12 11:00:37 +0000870 if (hasManageUsersPermission()) {
Tony Makd390ae92017-12-28 13:23:10 +0000871 return;
Tony Make3d1f652017-12-12 11:00:37 +0000872 }
Tony Makd390ae92017-12-28 13:23:10 +0000873 if (startIntent) {
874 throw new SecurityException("MANAGE_USERS permission is required to start intent "
875 + "after disabling quiet mode.");
876 }
jovanakf24ad492018-05-18 12:15:59 -0700877 final boolean hasModifyQuietModePermission = hasPermissionGranted(
878 Manifest.permission.MODIFY_QUIET_MODE, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000879 if (hasModifyQuietModePermission) {
Tony Makd390ae92017-12-28 13:23:10 +0000880 return;
Tony Make3d1f652017-12-12 11:00:37 +0000881 }
882
Tony Makd390ae92017-12-28 13:23:10 +0000883 verifyCallingPackage(callingPackage, callingUid);
Tony Make3d1f652017-12-12 11:00:37 +0000884 final ShortcutServiceInternal shortcutInternal =
885 LocalServices.getService(ShortcutServiceInternal.class);
886 if (shortcutInternal != null) {
887 boolean isForegroundLauncher =
888 shortcutInternal.isForegroundDefaultLauncher(callingPackage, callingUid);
889 if (isForegroundLauncher) {
Tony Makd390ae92017-12-28 13:23:10 +0000890 return;
Tony Make3d1f652017-12-12 11:00:37 +0000891 }
892 }
Tony Makd390ae92017-12-28 13:23:10 +0000893 throw new SecurityException("Can't modify quiet mode, caller is neither foreground "
894 + "default launcher nor has MANAGE_USERS/MODIFY_QUIET_MODE permission");
Tony Make3d1f652017-12-12 11:00:37 +0000895 }
896
Tony Makb7e6fd42017-12-05 19:40:28 +0000897 private void setQuietModeEnabled(
898 int userHandle, boolean enableQuietMode, IntentSender target) {
899 final UserInfo profile, parent;
900 final UserData profileUserData;
901 synchronized (mUsersLock) {
902 profile = getUserInfoLU(userHandle);
903 parent = getProfileParentLU(userHandle);
904
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000905 if (profile == null || !profile.isManagedProfile()) {
906 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
907 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000908 if (profile.isQuietModeEnabled() == enableQuietMode) {
909 Slog.i(LOG_TAG, "Quiet mode is already " + enableQuietMode);
910 return;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000911 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000912 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
913 profileUserData = getUserDataLU(profile.id);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000914 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000915 synchronized (mPackagesLock) {
916 writeUserLP(profileUserData);
917 }
918 try {
919 if (enableQuietMode) {
920 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
921 LocalServices.getService(ActivityManagerInternal.class)
922 .killForegroundAppsForUser(userHandle);
923 } else {
924 IProgressListener callback = target != null
925 ? new DisableQuietModeUserUnlockedCallback(target)
926 : null;
927 ActivityManager.getService().startUserInBackgroundWithListener(
928 userHandle, callback);
Rubin Xuf13c9802016-01-21 18:06:00 +0000929 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000930 } catch (RemoteException e) {
931 // Should not happen, same process.
932 e.rethrowAsRuntimeException();
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000933 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000934 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
935 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000936 }
937
938 @Override
939 public boolean isQuietModeEnabled(int userHandle) {
940 synchronized (mPackagesLock) {
941 UserInfo info;
942 synchronized (mUsersLock) {
943 info = getUserInfoLU(userHandle);
944 }
945 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000946 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000947 }
948 return info.isQuietModeEnabled();
949 }
950 }
951
Tony Makb7e6fd42017-12-05 19:40:28 +0000952 /**
953 * Show confirm credential screen to unlock user in order to turn off quiet mode.
954 */
955 private void showConfirmCredentialToDisableQuietMode(
Tony Mak64fd8c02017-12-01 19:11:59 +0000956 @UserIdInt int userHandle, @Nullable IntentSender target) {
Tony Makb7e6fd42017-12-05 19:40:28 +0000957 // otherwise, we show a profile challenge to trigger decryption of the user
958 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
959 Context.KEYGUARD_SERVICE);
960 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
961 // lock, confirm screenlock page will know and show personal challenge, and unlock
962 // work profile when personal challenge is correct
963 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
964 userHandle);
965 if (unlockIntent == null) {
966 return;
Benjamin Franzf02420c2016-04-04 18:52:21 +0100967 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000968 final Intent callBackIntent = new Intent(
969 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
970 if (target != null) {
971 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100972 }
Tony Makb7e6fd42017-12-05 19:40:28 +0000973 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
974 callBackIntent.setPackage(mContext.getPackageName());
975 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
976 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
977 mContext,
978 0,
979 callBackIntent,
980 PendingIntent.FLAG_CANCEL_CURRENT |
981 PendingIntent.FLAG_ONE_SHOT |
982 PendingIntent.FLAG_IMMUTABLE);
983 // After unlocking the challenge, it will disable quiet mode and run the original
984 // intentSender
985 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
986 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
987 mContext.startActivity(unlockIntent);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100988 }
989
990 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100991 public void setUserEnabled(int userId) {
992 checkManageUsersPermission("enable user");
993 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700994 UserInfo info;
995 synchronized (mUsersLock) {
996 info = getUserInfoLU(userId);
997 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100998 if (info != null && !info.isEnabled()) {
999 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -08001000 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001001 }
1002 }
1003 }
1004
jovanakf24ad492018-05-18 12:15:59 -07001005 @Override
1006 public void setUserAdmin(int userId) {
1007 checkManageUserAndAcrossUsersFullPermission("set user admin");
1008
1009 synchronized (mPackagesLock) {
1010 UserInfo info;
1011 synchronized (mUsersLock) {
1012 info = getUserInfoLU(userId);
1013 }
1014 if (info == null || info.isAdmin()) {
1015 // Exit if no user found with that id, or the user is already an Admin.
1016 return;
1017 }
1018
1019 info.flags ^= UserInfo.FLAG_ADMIN;
1020 writeUserLP(getUserDataLU(info.id));
1021 }
1022
1023 // Remove non-admin restrictions.
1024 // Keep synchronized with createUserEvenWhenDisallowed.
1025 setUserRestriction(UserManager.DISALLOW_SMS, false, userId);
1026 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, false, userId);
1027 }
1028
Andrew Scull85a63bc2016-10-24 13:47:47 +01001029 /**
1030 * Evicts a user's CE key by stopping and restarting the user.
1031 *
1032 * The key is evicted automatically by the user controller when the user has stopped.
1033 */
1034 @Override
1035 public void evictCredentialEncryptionKey(@UserIdInt int userId) {
1036 checkManageUsersPermission("evict CE key");
1037 final IActivityManager am = ActivityManagerNative.getDefault();
1038 final long identity = Binder.clearCallingIdentity();
1039 try {
1040 am.restartUserInBackground(userId);
1041 } catch (RemoteException re) {
1042 throw re.rethrowAsRuntimeException();
1043 } finally {
1044 Binder.restoreCallingIdentity(identity);
1045 }
1046 }
1047
Alexandra Gherghinadf35d572014-04-09 13:54:39 +01001048 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07001049 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -07001050 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +00001051 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001052 return userWithName(getUserInfoLU(userId));
1053 }
1054 }
1055
1056 /**
1057 * Returns a UserInfo object with the name filled in, for Owner, or the original
1058 * if the name is already set.
1059 */
1060 private UserInfo userWithName(UserInfo orig) {
1061 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
1062 UserInfo withName = new UserInfo(orig);
1063 withName.name = getOwnerName();
1064 return withName;
1065 } else {
1066 return orig;
Tony Mak8673b282016-03-21 21:10:59 +00001067 }
1068 }
1069
1070 @Override
Kenny Guy02c89902016-11-15 19:36:38 +00001071 public int getManagedProfileBadge(@UserIdInt int userId) {
1072 int callingUserId = UserHandle.getCallingUserId();
1073 if (callingUserId != userId && !hasManageUsersPermission()) {
1074 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
1075 throw new SecurityException(
1076 "You need MANAGE_USERS permission to: check if specified user a " +
1077 "managed profile outside your profile group");
1078 }
1079 }
1080 synchronized (mUsersLock) {
1081 UserInfo userInfo = getUserInfoLU(userId);
1082 return userInfo != null ? userInfo.profileBadge : 0;
1083 }
1084 }
1085
1086 @Override
Tony Mak8673b282016-03-21 21:10:59 +00001087 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +00001088 int callingUserId = UserHandle.getCallingUserId();
1089 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -07001090 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001091 throw new SecurityException(
1092 "You need MANAGE_USERS permission to: check if specified user a " +
1093 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +00001094 }
Tony Mak4dc008c2016-03-16 10:46:49 +00001095 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001096 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001097 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +00001098 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -07001099 }
1100 }
1101
Amith Yamasani71e6c692013-03-24 17:39:28 -07001102 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001103 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001104 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
Fyodor Kupolovc413f702016-10-06 17:11:14 -07001105 return mLocalService.isUserUnlockingOrUnlocked(userId);
1106 }
1107
1108 @Override
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001109 public boolean isUserUnlocked(int userId) {
1110 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07001111 return mLocalService.isUserUnlocked(userId);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001112 }
1113
1114 @Override
1115 public boolean isUserRunning(int userId) {
1116 checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
1117 return mLocalService.isUserRunning(userId);
1118 }
1119
Makoto Onuki73dded22017-12-20 13:14:48 +09001120 @Override
1121 public long getUserStartRealtime() {
1122 final int userId = UserHandle.getUserId(Binder.getCallingUid());
1123 synchronized (mUsersLock) {
1124 final UserData user = getUserDataLU(userId);
1125 if (user != null) {
1126 return user.startRealtime;
1127 }
1128 return 0;
1129 }
1130 }
1131
1132 @Override
1133 public long getUserUnlockRealtime() {
1134 synchronized (mUsersLock) {
1135 final UserData user = getUserDataLU(UserHandle.getUserId(Binder.getCallingUid()));
1136 if (user != null) {
1137 return user.unlockRealtime;
1138 }
1139 return 0;
1140 }
1141 }
1142
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001143 private void checkManageOrInteractPermIfCallerInOtherProfileGroup(int userId, String name) {
1144 int callingUserId = UserHandle.getCallingUserId();
1145 if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
1146 hasManageUsersPermission()) {
1147 return;
1148 }
jovanakf24ad492018-05-18 12:15:59 -07001149 if (!hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS,
1150 Binder.getCallingUid())) {
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08001151 throw new SecurityException("You need INTERACT_ACROSS_USERS or MANAGE_USERS permission "
1152 + "to: check " + name);
1153 }
1154 }
1155
1156 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -07001157 public boolean isDemoUser(int userId) {
1158 int callingUserId = UserHandle.getCallingUserId();
1159 if (callingUserId != userId && !hasManageUsersPermission()) {
1160 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
1161 + " is a demo user");
1162 }
1163 synchronized (mUsersLock) {
1164 UserInfo userInfo = getUserInfoLU(userId);
1165 return userInfo != null && userInfo.isDemo();
1166 }
1167 }
1168
1169 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -07001170 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001171 synchronized (mUsersLock) {
1172 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -07001173 }
1174 }
1175
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001176 @Override
1177 public boolean canHaveRestrictedProfile(int userId) {
1178 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -07001179 synchronized (mUsersLock) {
1180 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001181 if (userInfo == null || !userInfo.canHaveProfile()) {
1182 return false;
1183 }
1184 if (!userInfo.isAdmin()) {
1185 return false;
1186 }
Makoto Onukie7927da2015-11-25 10:05:17 -08001187 // restricted profile can be created if there is no DO set and the admin user has no PO;
1188 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001189 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001190 }
1191
Fyodor Kupolovca177562017-11-09 17:43:01 -08001192 @Override
1193 public boolean hasRestrictedProfiles() {
1194 checkManageUsersPermission("hasRestrictedProfiles");
1195 final int callingUserId = UserHandle.getCallingUserId();
1196 synchronized (mUsersLock) {
1197 final int userSize = mUsers.size();
1198 for (int i = 0; i < userSize; i++) {
1199 UserInfo profile = mUsers.valueAt(i).info;
1200 if (callingUserId != profile.id
1201 && profile.restrictedProfileParentId == callingUserId) {
1202 return true;
1203 }
1204 }
1205 return false;
1206 }
1207 }
1208
Amith Yamasani195263742012-08-21 15:40:12 -07001209 /*
1210 * Should be locked on mUsers before calling this.
1211 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001212 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001213 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08001214 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -07001215 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -08001216 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001217 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
1218 return null;
1219 }
Amith Yamasani12747872015-12-07 14:19:49 -08001220 return userData != null ? userData.info : null;
1221 }
1222
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001223 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -08001224 private UserData getUserDataLU(int userId) {
1225 final UserData userData = mUsers.get(userId);
1226 // If it is partial and not in the process of being removed, return as unknown user.
1227 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
1228 return null;
1229 }
1230 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -07001231 }
1232
Fyodor Kupolov82402752015-10-28 14:54:51 -07001233 /**
1234 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
1235 * <p>No permissions checking or any addition checks are made</p>
1236 */
1237 private UserInfo getUserInfoNoChecks(int userId) {
1238 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001239 final UserData userData = mUsers.get(userId);
1240 return userData != null ? userData.info : null;
1241 }
1242 }
1243
1244 /**
1245 * Obtains {@link #mUsersLock} and return UserData from mUsers.
1246 * <p>No permissions checking or any addition checks are made</p>
1247 */
1248 private UserData getUserDataNoChecks(int userId) {
1249 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001250 return mUsers.get(userId);
1251 }
1252 }
1253
Amith Yamasani236b2b52015-08-18 14:32:14 -07001254 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -07001255 public boolean exists(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001256 return mLocalService.exists(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001257 }
1258
Amith Yamasani258848d2012-08-10 17:06:33 -07001259 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001260 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001261 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001262 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -07001263 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001264 UserData userData = getUserDataNoChecks(userId);
1265 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001266 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
1267 return;
1268 }
Amith Yamasani12747872015-12-07 14:19:49 -08001269 if (name != null && !name.equals(userData.info.name)) {
1270 userData.info.name = name;
1271 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001272 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001273 }
1274 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001275 if (changed) {
1276 sendUserInfoChangedBroadcast(userId);
1277 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001278 }
1279
Amith Yamasani258848d2012-08-10 17:06:33 -07001280 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001281 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001282 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001283 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1284 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1285 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001286 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001287 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001288 }
1289
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001290
1291
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001292 private void sendUserInfoChangedBroadcast(int userId) {
1293 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1294 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1295 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001296 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001297 }
1298
Amith Yamasani258848d2012-08-10 17:06:33 -07001299 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001300 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001301 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001302 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001303 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1304 if (targetUserInfo == null || targetUserInfo.partial) {
1305 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001306 return null;
1307 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001308
1309 final int callingUserId = UserHandle.getCallingUserId();
1310 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1311 final int targetGroupId = targetUserInfo.profileGroupId;
1312 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1313 && callingGroupId == targetGroupId);
1314 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001315 checkManageUsersPermission("get the icon of a user who is not related");
1316 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001317
1318 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001319 return null;
1320 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001321 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001322 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001323
1324 try {
1325 return ParcelFileDescriptor.open(
1326 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1327 } catch (FileNotFoundException e) {
1328 Log.e(LOG_TAG, "Couldn't find icon file", e);
1329 }
1330 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001331 }
1332
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001333 public void makeInitialized(int userId) {
1334 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001335 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001336 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001337 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001338 userData = mUsers.get(userId);
1339 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001340 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001341 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001342 }
Amith Yamasani12747872015-12-07 14:19:49 -08001343 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1344 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001345 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001346 }
1347 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001348 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001349 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001350 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001351 }
1352
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001353 /**
1354 * If default guest restrictions haven't been initialized yet, add the basic
1355 * restrictions.
1356 */
1357 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001358 synchronized (mGuestRestrictions) {
1359 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001360 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001361 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001362 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1363 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1364 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001365 }
1366 }
1367
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001368 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301369 public Bundle getDefaultGuestRestrictions() {
1370 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001371 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301372 return new Bundle(mGuestRestrictions);
1373 }
1374 }
1375
1376 @Override
1377 public void setDefaultGuestRestrictions(Bundle restrictions) {
1378 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001379 synchronized (mGuestRestrictions) {
1380 mGuestRestrictions.clear();
1381 mGuestRestrictions.putAll(restrictions);
1382 }
1383 synchronized (mPackagesLock) {
1384 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301385 }
1386 }
1387
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001388 /**
Pavel Grafov6a40f092016-10-25 15:46:51 +01001389 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions}
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001390 */
Pavel Grafov6a40f092016-10-25 15:46:51 +01001391 private void setDevicePolicyUserRestrictionsInner(int userId, @Nullable Bundle restrictions,
1392 boolean isDeviceOwner, int cameraRestrictionScope) {
1393 final Bundle global = new Bundle();
1394 final Bundle local = new Bundle();
1395
1396 // Sort restrictions into local and global ensuring they don't overlap.
1397 UserRestrictionsUtils.sortToGlobalAndLocal(restrictions, isDeviceOwner,
1398 cameraRestrictionScope, global, local);
1399
1400 boolean globalChanged, localChanged;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001401 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001402 // Update global and local restrictions if they were changed.
1403 globalChanged = updateRestrictionsIfNeededLR(
1404 userId, global, mDevicePolicyGlobalUserRestrictions);
1405 localChanged = updateRestrictionsIfNeededLR(
1406 userId, local, mDevicePolicyLocalUserRestrictions);
1407
1408 if (isDeviceOwner) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001409 // Remember the global restriction owner userId to be able to make a distinction
1410 // in getUserRestrictionSource on who set local policies.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001411 mDeviceOwnerUserId = userId;
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001412 } else {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001413 if (mDeviceOwnerUserId == userId) {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001414 // When profile owner sets restrictions it passes null global bundle and we
1415 // reset global restriction owner userId.
1416 // This means this user used to have DO, but now the DO is gone and the user
1417 // instead has PO.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001418 mDeviceOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001419 }
1420 }
1421 }
1422 if (DBG) {
1423 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1424 + " global=" + global + (globalChanged ? " (changed)" : "")
1425 + " local=" + local + (localChanged ? " (changed)" : "")
1426 );
1427 }
1428 // Don't call them within the mRestrictionsLock.
1429 synchronized (mPackagesLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001430 if (localChanged || globalChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001431 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001432 }
1433 }
1434
1435 synchronized (mRestrictionsLock) {
1436 if (globalChanged) {
1437 applyUserRestrictionsForAllUsersLR();
1438 } else if (localChanged) {
1439 applyUserRestrictionsLR(userId);
1440 }
1441 }
1442 }
1443
Pavel Grafov6a40f092016-10-25 15:46:51 +01001444 /**
1445 * Updates restriction bundle for a given user in a given restriction array. If new bundle is
1446 * empty, record is removed from the array.
1447 * @return whether restrictions bundle is different from the old one.
1448 */
1449 private boolean updateRestrictionsIfNeededLR(int userId, @Nullable Bundle restrictions,
1450 SparseArray<Bundle> restrictionsArray) {
1451 final boolean changed =
1452 !UserRestrictionsUtils.areEqual(restrictionsArray.get(userId), restrictions);
1453 if (changed) {
1454 if (!UserRestrictionsUtils.isEmpty(restrictions)) {
1455 restrictionsArray.put(userId, restrictions);
1456 } else {
1457 restrictionsArray.delete(userId);
1458 }
1459 }
1460 return changed;
1461 }
1462
Makoto Onuki068c54a2015-10-13 14:34:03 -07001463 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001464 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001465 final Bundle baseRestrictions =
1466 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
Pavel Grafov6a40f092016-10-25 15:46:51 +01001467 final Bundle global = UserRestrictionsUtils.mergeAll(mDevicePolicyGlobalUserRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001468 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001469
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001470 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1471 // Common case first.
1472 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001473 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001474 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1475 UserRestrictionsUtils.merge(effective, global);
1476 UserRestrictionsUtils.merge(effective, local);
1477
Makoto Onuki068c54a2015-10-13 14:34:03 -07001478 return effective;
1479 }
1480
1481 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001482 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001483 if (DBG) {
1484 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1485 }
1486 mCachedEffectiveUserRestrictions.remove(userId);
1487 }
1488
1489 private Bundle getEffectiveUserRestrictions(int userId) {
1490 synchronized (mRestrictionsLock) {
1491 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1492 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001493 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001494 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1495 }
1496 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001497 }
1498 }
1499
Makoto Onuki068c54a2015-10-13 14:34:03 -07001500 /** @return a specific user restriction that's in effect currently. */
1501 @Override
1502 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001503 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1504 return false;
1505 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001506 Bundle restrictions = getEffectiveUserRestrictions(userId);
1507 return restrictions != null && restrictions.getBoolean(restrictionKey);
1508 }
1509
Makoto Onukiacc50462018-02-14 14:13:49 -08001510 /** @return if any user has the given restriction. */
1511 @Override
1512 public boolean hasUserRestrictionOnAnyUser(String restrictionKey) {
1513 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1514 return false;
1515 }
1516 final List<UserInfo> users = getUsers(/* excludeDying= */ true);
1517 for (int i = 0; i < users.size(); i++) {
1518 final int userId = users.get(i).id;
1519 Bundle restrictions = getEffectiveUserRestrictions(userId);
1520 if (restrictions != null && restrictions.getBoolean(restrictionKey)) {
1521 return true;
1522 }
1523 }
1524 return false;
1525 }
1526
Makoto Onuki068c54a2015-10-13 14:34:03 -07001527 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001528 * @hide
1529 *
1530 * Returns who set a user restriction on a user.
1531 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1532 * @param restrictionKey the string key representing the restriction
1533 * @param userId the id of the user for whom to retrieve the restrictions.
1534 * @return The source of user restriction. Any combination of
1535 * {@link UserManager#RESTRICTION_NOT_SET},
1536 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1537 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1538 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1539 */
1540 @Override
1541 public int getUserRestrictionSource(String restrictionKey, int userId) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001542 List<EnforcingUser> enforcingUsers = getUserRestrictionSources(restrictionKey, userId);
1543 // Get "bitwise or" of restriction sources for all enforcing users.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001544 int result = UserManager.RESTRICTION_NOT_SET;
Pavel Grafov6a40f092016-10-25 15:46:51 +01001545 for (int i = enforcingUsers.size() - 1; i >= 0; i--) {
1546 result |= enforcingUsers.get(i).getUserRestrictionSource();
1547 }
1548 return result;
1549 }
1550
1551 @Override
1552 public List<EnforcingUser> getUserRestrictionSources(
1553 String restrictionKey, @UserIdInt int userId) {
1554 checkManageUsersPermission("getUserRestrictionSource");
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001555
1556 // Shortcut for the most common case
1557 if (!hasUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001558 return Collections.emptyList();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001559 }
1560
Pavel Grafov6a40f092016-10-25 15:46:51 +01001561 final List<EnforcingUser> result = new ArrayList<>();
1562
1563 // Check if it is base restriction.
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001564 if (hasBaseUserRestriction(restrictionKey, userId)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01001565 result.add(new EnforcingUser(
1566 UserHandle.USER_NULL, UserManager.RESTRICTION_SOURCE_SYSTEM));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001567 }
1568
Pavel Grafov6a40f092016-10-25 15:46:51 +01001569 synchronized (mRestrictionsLock) {
1570 // Check if it is set by profile owner.
1571 Bundle profileOwnerRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1572 if (UserRestrictionsUtils.contains(profileOwnerRestrictions, restrictionKey)) {
1573 result.add(getEnforcingUserLocked(userId));
1574 }
1575
1576 // Iterate over all users who enforce global restrictions.
1577 for (int i = mDevicePolicyGlobalUserRestrictions.size() - 1; i >= 0; i--) {
1578 Bundle globalRestrictions = mDevicePolicyGlobalUserRestrictions.valueAt(i);
1579 int profileUserId = mDevicePolicyGlobalUserRestrictions.keyAt(i);
1580 if (UserRestrictionsUtils.contains(globalRestrictions, restrictionKey)) {
1581 result.add(getEnforcingUserLocked(profileUserId));
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001582 }
1583 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001584 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001585 return result;
1586 }
1587
Andreas Gampea36dc622018-02-05 17:19:22 -08001588 @GuardedBy("mRestrictionsLock")
Pavel Grafov6a40f092016-10-25 15:46:51 +01001589 private EnforcingUser getEnforcingUserLocked(@UserIdInt int userId) {
1590 int source = mDeviceOwnerUserId == userId ? UserManager.RESTRICTION_SOURCE_DEVICE_OWNER
1591 : UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1592 return new EnforcingUser(userId, source);
1593 }
1594
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001595 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001596 * @return UserRestrictions that are in effect currently. This always returns a new
1597 * {@link Bundle}.
1598 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001599 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001600 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001601 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001602 }
1603
1604 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001605 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1606 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001607 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1608 return false;
1609 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001610 synchronized (mRestrictionsLock) {
1611 Bundle bundle = mBaseUserRestrictions.get(userId);
1612 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1613 }
1614 }
1615
1616 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001617 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001618 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001619 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1620 return;
1621 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001622 synchronized (mRestrictionsLock) {
1623 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1624 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001625 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1626 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001627 newRestrictions.putBoolean(key, value);
1628
Fyodor Kupolov82402752015-10-28 14:54:51 -07001629 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001630 }
1631 }
1632
Makoto Onuki068c54a2015-10-13 14:34:03 -07001633 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001634 * Optionally updating user restrictions, calculate the effective user restrictions and also
1635 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001636 *
Pavel Grafov6a40f092016-10-25 15:46:51 +01001637 * @param newBaseRestrictions User restrictions to set.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001638 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001639 * @param userId target user ID.
1640 */
1641 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001642 private void updateUserRestrictionsInternalLR(
Pavel Grafov6a40f092016-10-25 15:46:51 +01001643 @Nullable Bundle newBaseRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001644 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1645 mAppliedUserRestrictions.get(userId));
1646
1647 // Update base restrictions.
Pavel Grafov6a40f092016-10-25 15:46:51 +01001648 if (newBaseRestrictions != null) {
1649 // If newBaseRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1651
Pavel Grafov6a40f092016-10-25 15:46:51 +01001652 Preconditions.checkState(prevBaseRestrictions != newBaseRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001653 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
Pavel Grafov6a40f092016-10-25 15:46:51 +01001654 != newBaseRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001655
Pavel Grafov6a40f092016-10-25 15:46:51 +01001656 if (updateRestrictionsIfNeededLR(userId, newBaseRestrictions, mBaseUserRestrictions)) {
Amith Yamasani12747872015-12-07 14:19:49 -08001657 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001659 }
1660
Fyodor Kupolov82402752015-10-28 14:54:51 -07001661 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001662
Makoto Onuki759a7632015-10-28 16:43:10 -07001663 mCachedEffectiveUserRestrictions.put(userId, effective);
1664
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001665 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001666 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001667 debug("Applying user restrictions: userId=" + userId
1668 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001669 }
1670
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001671 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001672 mHandler.post(new Runnable() {
1673 @Override
1674 public void run() {
1675 try {
1676 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1677 } catch (RemoteException e) {
1678 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1679 }
1680 }
1681 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001682 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001683
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001684 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001685
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001687 }
1688
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001690 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1692 // actually, but we still need some kind of synchronization otherwise we might end up
1693 // calling listeners out-of-order, thus "LR".
1694
1695 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1696 return;
1697 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001698
1699 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1700 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1701
1702 mHandler.post(new Runnable() {
1703 @Override
1704 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001705 UserRestrictionsUtils.applyUserRestrictions(
1706 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707
Makoto Onukid45a4a22015-11-02 17:17:38 -08001708 final UserRestrictionsListener[] listeners;
1709 synchronized (mUserRestrictionsListeners) {
1710 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1711 mUserRestrictionsListeners.toArray(listeners);
1712 }
1713 for (int i = 0; i < listeners.length; i++) {
1714 listeners[i].onUserRestrictionsChanged(userId,
1715 newRestrictionsFinal, prevRestrictionsFinal);
1716 }
Makoto Onukie72f81b2017-03-16 14:08:19 -07001717
1718 final Intent broadcast = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)
1719 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1720 mContext.sendBroadcastAsUser(broadcast, UserHandle.of(userId));
Makoto Onukid45a4a22015-11-02 17:17:38 -08001721 }
1722 });
1723 }
1724
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001725 // Package private for the inner class.
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001726 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001727 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001728 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001729 }
1730
1731 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001732 // Package private for the inner class.
1733 void applyUserRestrictionsForAllUsersLR() {
1734 if (DBG) {
1735 debug("applyUserRestrictionsForAllUsersLR");
1736 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001737 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001738 mCachedEffectiveUserRestrictions.clear();
1739
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001740 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001741 // it on a handler.
1742 final Runnable r = new Runnable() {
1743 @Override
1744 public void run() {
1745 // Then get the list of running users.
1746 final int[] runningUsers;
1747 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001748 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001749 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001750 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001751 return;
1752 }
1753 // Then re-calculate the effective restrictions and apply, only for running users.
1754 // It's okay if a new user has started after the getRunningUserIds() call,
1755 // because we'll do the same thing (re-calculate the restrictions and apply)
1756 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001757 synchronized (mRestrictionsLock) {
1758 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001759 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001760 }
1761 }
1762 }
1763 };
1764 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001765 }
1766
Amith Yamasani258848d2012-08-10 17:06:33 -07001767 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001768 * Check if we've hit the limit of how many users can be created.
1769 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001770 private boolean isUserLimitReached() {
1771 int count;
1772 synchronized (mUsersLock) {
1773 count = getAliveUsersExcludingGuestsCountLU();
1774 }
1775 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001776 }
1777
1778 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001779 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001780 checkManageUsersPermission("check if more managed profiles can be added.");
1781 if (ActivityManager.isLowRamDeviceStatic()) {
1782 return false;
1783 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001784 if (!mContext.getPackageManager().hasSystemFeature(
1785 PackageManager.FEATURE_MANAGED_USERS)) {
1786 return false;
1787 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001788 // Limit number of managed profiles that can be created
Benjamin Franzc8776152017-01-06 14:16:41 +00001789 final int managedProfilesCount = getProfiles(userId, false).size() - 1;
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001790 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
Kenny Guy02c89902016-11-15 19:36:38 +00001791 if (managedProfilesCount - profilesRemovedCount >= getMaxManagedProfiles()) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001792 return false;
1793 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001794 synchronized(mUsersLock) {
1795 UserInfo userInfo = getUserInfoLU(userId);
yuanhao47f9f7c2017-01-18 09:54:45 +08001796 if (userInfo == null || !userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001797 return false;
1798 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001799 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1800 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001801 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001802 return usersCountAfterRemoving == 1
1803 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001804 }
1805 }
1806
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001807 @GuardedBy("mUsersLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001808 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001809 int aliveUserCount = 0;
1810 final int totalUserCount = mUsers.size();
1811 // Skip over users being removed
1812 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001813 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001814 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001815 aliveUserCount++;
1816 }
1817 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001818 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001819 }
1820
1821 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001822 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001823 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1824 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1825 * permissions can make certain calls to the UserManager.
1826 *
1827 * @param message used as message if SecurityException is thrown
1828 * @throws SecurityException if the caller does not have enough privilege.
1829 */
1830 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1831 final int uid = Binder.getCallingUid();
jovanakf24ad492018-05-18 12:15:59 -07001832
1833 if (uid == Process.SYSTEM_UID || uid == 0) {
1834 // System UID or root's UID are granted privilege.
1835 return;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001836 }
jovanakf24ad492018-05-18 12:15:59 -07001837
1838 if (hasPermissionGranted(Manifest.permission.MANAGE_USERS, uid)
1839 && hasPermissionGranted(Manifest.permission.INTERACT_ACROSS_USERS_FULL, uid)) {
1840 // Apps with both permissions are granted privilege.
1841 return;
1842 }
1843
1844 throw new SecurityException(
1845 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: " + message);
1846 }
1847
1848 private static boolean hasPermissionGranted(String permission, int uid) {
1849 return ActivityManager.checkComponentPermission(
1850 permission, uid, /* owningUid = */-1, /* exported = */ true) ==
1851 PackageManager.PERMISSION_GRANTED;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001852 }
1853
1854 /**
1855 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001856 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001857 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001858 *
1859 * @param message used as message if SecurityException is thrown
1860 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001861 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001862 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001863 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001864 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001865 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1866 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001867 }
1868
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001869 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001870 * Enforces that only the system UID or root's UID or apps that have the
1871 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1872 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1873 * can make certain calls to the UserManager.
1874 *
1875 * @param message used as message if SecurityException is thrown
1876 * @throws SecurityException if the caller is not system or root
1877 * @see #hasManageOrCreateUsersPermission()
1878 */
1879 private static final void checkManageOrCreateUsersPermission(String message) {
1880 if (!hasManageOrCreateUsersPermission()) {
1881 throw new SecurityException(
1882 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1883 }
1884 }
1885
1886 /**
1887 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1888 * to create user/profiles other than what is allowed for
1889 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1890 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1891 */
1892 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1893 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1894 if (!hasManageOrCreateUsersPermission()) {
1895 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1896 + "permission to create an user with flags: " + creationFlags);
1897 }
1898 } else if (!hasManageUsersPermission()) {
1899 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1900 + " with flags: " + creationFlags);
1901 }
1902 }
1903
1904 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001905 * @return whether the calling UID is system UID or root's UID or the calling app has the
1906 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1907 */
1908 private static final boolean hasManageUsersPermission() {
1909 final int callingUid = Binder.getCallingUid();
1910 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1911 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001912 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid);
Tony Mak4dc008c2016-03-16 10:46:49 +00001913 }
1914
1915 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001916 * @return whether the calling UID is system UID or root's UID or the calling app has the
1917 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1918 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1919 */
1920 private static final boolean hasManageOrCreateUsersPermission() {
1921 final int callingUid = Binder.getCallingUid();
1922 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1923 || callingUid == Process.ROOT_UID
jovanakf24ad492018-05-18 12:15:59 -07001924 || hasPermissionGranted(android.Manifest.permission.MANAGE_USERS, callingUid)
1925 || hasPermissionGranted(android.Manifest.permission.CREATE_USERS, callingUid);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001926 }
1927
1928 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001929 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1930 * UserManager.
1931 *
1932 * @param message used as message if SecurityException is thrown
1933 * @throws SecurityException if the caller is not system or root
1934 */
1935 private static void checkSystemOrRoot(String message) {
1936 final int uid = Binder.getCallingUid();
1937 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1938 throw new SecurityException("Only system may: " + message);
1939 }
1940 }
1941
Fyodor Kupolov82402752015-10-28 14:54:51 -07001942 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001943 try {
1944 File dir = new File(mUsersDir, Integer.toString(info.id));
1945 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001946 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001947 if (!dir.exists()) {
1948 dir.mkdir();
1949 FileUtils.setPermissions(
1950 dir.getPath(),
1951 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1952 -1, -1);
1953 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001954 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001955 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001956 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001957 info.iconPath = file.getAbsolutePath();
1958 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001959 try {
1960 os.close();
1961 } catch (IOException ioe) {
1962 // What the ... !
1963 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001964 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001965 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001966 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001967 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001968 }
1969
Amith Yamasani0b285492011-04-14 17:35:23 -07001970 /**
1971 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1972 * cache it elsewhere.
1973 * @return the array of user ids.
1974 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001975 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001976 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001977 return mUserIds;
1978 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001979 }
1980
Andreas Gampe2e8c7672018-07-20 13:01:08 -07001981 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001982 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001983 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001984 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001985 return;
1986 }
1987 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001988 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001989 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001990 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001991 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001992 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001993 int type;
1994 while ((type = parser.next()) != XmlPullParser.START_TAG
1995 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001996 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001997 }
1998
1999 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002000 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002001 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002002 return;
2003 }
2004
Amith Yamasani2a003292012-08-14 18:25:45 -07002005 mNextSerialNumber = -1;
2006 if (parser.getName().equals(TAG_USERS)) {
2007 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
2008 if (lastSerialNumber != null) {
2009 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
2010 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002011 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
2012 if (versionNumber != null) {
2013 mUserVersion = Integer.parseInt(versionNumber);
2014 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002015 }
2016
Pavel Grafov6a40f092016-10-25 15:46:51 +01002017 // Pre-O global user restriction were stored as a single bundle (as opposed to per-user
2018 // currently), take care of it in case of upgrade.
2019 Bundle oldDevicePolicyGlobalUserRestrictions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002020
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002021 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302022 if (type == XmlPullParser.START_TAG) {
2023 final String name = parser.getName();
2024 if (name.equals(TAG_USER)) {
2025 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002026
Amith Yamasani12747872015-12-07 14:19:49 -08002027 UserData userData = readUserLP(Integer.parseInt(id));
2028
2029 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002030 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002031 mUsers.put(userData.info.id, userData);
2032 if (mNextSerialNumber < 0
2033 || mNextSerialNumber <= userData.info.id) {
2034 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002035 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302036 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002037 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302038 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08002039 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2040 && type != XmlPullParser.END_TAG) {
2041 if (type == XmlPullParser.START_TAG) {
2042 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002043 synchronized (mGuestRestrictions) {
Fyodor Kupoloveafee022017-03-15 17:09:04 -07002044 UserRestrictionsUtils
2045 .readRestrictions(parser, mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002046 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08002047 }
2048 break;
2049 }
2050 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002051 } else if (name.equals(TAG_DEVICE_OWNER_USER_ID)
2052 // Legacy name, should only be encountered when upgrading from pre-O.
2053 || name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002054 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
2055 if (ownerUserId != null) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002056 mDeviceOwnerUserId = Integer.parseInt(ownerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01002057 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002058 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
2059 // Should only happen when upgrading from pre-O (version < 7).
2060 oldDevicePolicyGlobalUserRestrictions =
2061 UserRestrictionsUtils.readRestrictions(parser);
Amith Yamasani258848d2012-08-10 17:06:33 -07002062 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002063 }
2064 }
Pavel Grafov6a40f092016-10-25 15:46:51 +01002065
Fyodor Kupolov82402752015-10-28 14:54:51 -07002066 updateUserIds();
Pavel Grafov6a40f092016-10-25 15:46:51 +01002067 upgradeIfNecessaryLP(oldDevicePolicyGlobalUserRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002068 } catch (IOException | XmlPullParserException e) {
2069 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002070 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002071 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002072 }
2073 }
2074
Amith Yamasani6f34b412012-10-22 18:19:27 -07002075 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08002076 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Pavel Grafov6a40f092016-10-25 15:46:51 +01002077 * @param oldGlobalUserRestrictions Pre-O global device policy restrictions.
Amith Yamasani6f34b412012-10-22 18:19:27 -07002078 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002079 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Pavel Grafov6a40f092016-10-25 15:46:51 +01002080 private void upgradeIfNecessaryLP(Bundle oldGlobalUserRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002081 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07002082 int userVersion = mUserVersion;
2083 if (userVersion < 1) {
2084 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08002085 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2086 if ("Primary".equals(userData.info.name)) {
2087 userData.info.name =
2088 mContext.getResources().getString(com.android.internal.R.string.owner_name);
2089 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07002090 }
2091 userVersion = 1;
2092 }
2093
Amith Yamasanibc9625052012-11-15 14:39:18 -08002094 if (userVersion < 2) {
2095 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08002096 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
2097 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
2098 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
2099 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08002100 }
2101 userVersion = 2;
2102 }
2103
Amith Yamasani350962c2013-08-06 11:18:53 -07002104
Amith Yamasani5e486f52013-08-07 11:06:44 -07002105 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07002106 userVersion = 4;
2107 }
2108
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002109 if (userVersion < 5) {
2110 initDefaultGuestRestrictions();
2111 userVersion = 5;
2112 }
2113
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002114 if (userVersion < 6) {
2115 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002116 synchronized (mUsersLock) {
2117 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002118 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002119 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08002120 if (!splitSystemUser && userData.info.isRestricted()
2121 && (userData.info.restrictedProfileParentId
2122 == UserInfo.NO_PROFILE_GROUP_ID)) {
2123 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
2124 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002125 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07002126 }
2127 }
2128 userVersion = 6;
2129 }
2130
Pavel Grafov6a40f092016-10-25 15:46:51 +01002131 if (userVersion < 7) {
2132 // Previously only one user could enforce global restrictions, now it is per-user.
2133 synchronized (mRestrictionsLock) {
2134 if (!UserRestrictionsUtils.isEmpty(oldGlobalUserRestrictions)
2135 && mDeviceOwnerUserId != UserHandle.USER_NULL) {
2136 mDevicePolicyGlobalUserRestrictions.put(
2137 mDeviceOwnerUserId, oldGlobalUserRestrictions);
2138 }
2139 // ENSURE_VERIFY_APPS is now enforced globally even if put by profile owner, so move
2140 // it from local to global bundle for all users who set it.
2141 UserRestrictionsUtils.moveRestriction(UserManager.ENSURE_VERIFY_APPS,
2142 mDevicePolicyLocalUserRestrictions, mDevicePolicyGlobalUserRestrictions
2143 );
2144 }
2145 userVersion = 7;
2146 }
2147
Amith Yamasani6f34b412012-10-22 18:19:27 -07002148 if (userVersion < USER_VERSION) {
2149 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
2150 + USER_VERSION);
2151 } else {
2152 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002153
2154 if (originalVersion < mUserVersion) {
2155 writeUserListLP();
2156 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07002157 }
2158 }
2159
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002160 @GuardedBy({"mPackagesLock", "mRestrictionsLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002161 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07002162 int flags = UserInfo.FLAG_INITIALIZED;
2163 // In split system user mode, the admin and primary flags are assigned to the first human
2164 // user.
2165 if (!UserManager.isSplitSystemUser()) {
2166 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
2167 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07002168 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002169 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002170 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07002171 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04002172 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08002173
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05002174 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01002175 try {
2176 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
2177 com.android.internal.R.array.config_defaultFirstUserRestrictions);
2178 for (String userRestriction : defaultFirstUserRestrictions) {
2179 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
2180 restrictions.putBoolean(userRestriction, true);
2181 }
2182 }
2183 } catch (Resources.NotFoundException e) {
2184 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
2185 }
2186
Pavel Grafov6a40f092016-10-25 15:46:51 +01002187 if (!restrictions.isEmpty()) {
2188 synchronized (mRestrictionsLock) {
2189 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
2190 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002191 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002192
Fyodor Kupolov82402752015-10-28 14:54:51 -07002193 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07002194 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002195
Amith Yamasani12747872015-12-07 14:19:49 -08002196 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06002197 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002198 }
2199
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07002200 private String getOwnerName() {
2201 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
2202 }
2203
Amith Yamasani12747872015-12-07 14:19:49 -08002204 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002205 if (DBG) {
2206 debug("scheduleWriteUser");
2207 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08002208 // No need to wrap it within a lock -- worst case, we'll just post the same message
2209 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08002210 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
2211 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002212 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
2213 }
2214 }
2215
Amith Yamasani12747872015-12-07 14:19:49 -08002216 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002217 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08002218 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002219 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002220 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08002221 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002222 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002223 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002224 final BufferedOutputStream bos = new BufferedOutputStream(fos);
Kenny Guy02c89902016-11-15 19:36:38 +00002225 writeUserLP(userData, bos);
Amith Yamasani2a003292012-08-14 18:25:45 -07002226 userFile.finishWrite(fos);
2227 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06002228 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07002229 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002230 }
2231 }
2232
2233 /*
Kenny Guy02c89902016-11-15 19:36:38 +00002234 * Writes the user file in this format:
2235 *
2236 * <user flags="20039023" id="0">
2237 * <name>Primary</name>
2238 * </user>
2239 */
2240 @VisibleForTesting
2241 void writeUserLP(UserData userData, OutputStream os)
2242 throws IOException, XmlPullParserException {
2243 // XmlSerializer serializer = XmlUtils.serializerInstance();
2244 final XmlSerializer serializer = new FastXmlSerializer();
2245 serializer.setOutput(os, StandardCharsets.UTF_8.name());
2246 serializer.startDocument(null, true);
2247 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2248
2249 final UserInfo userInfo = userData.info;
2250 serializer.startTag(null, TAG_USER);
2251 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
2252 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
2253 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
2254 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
2255 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
2256 Long.toString(userInfo.lastLoggedInTime));
2257 if (userInfo.lastLoggedInFingerprint != null) {
2258 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
2259 userInfo.lastLoggedInFingerprint);
2260 }
2261 if (userInfo.iconPath != null) {
2262 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
2263 }
2264 if (userInfo.partial) {
2265 serializer.attribute(null, ATTR_PARTIAL, "true");
2266 }
2267 if (userInfo.guestToRemove) {
2268 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
2269 }
2270 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2271 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
2272 Integer.toString(userInfo.profileGroupId));
2273 }
2274 serializer.attribute(null, ATTR_PROFILE_BADGE,
2275 Integer.toString(userInfo.profileBadge));
2276 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
2277 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
2278 Integer.toString(userInfo.restrictedProfileParentId));
2279 }
2280 // Write seed data
2281 if (userData.persistSeedData) {
2282 if (userData.seedAccountName != null) {
2283 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
2284 }
2285 if (userData.seedAccountType != null) {
2286 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
2287 }
2288 }
2289 if (userInfo.name != null) {
2290 serializer.startTag(null, TAG_NAME);
2291 serializer.text(userInfo.name);
2292 serializer.endTag(null, TAG_NAME);
2293 }
2294 synchronized (mRestrictionsLock) {
2295 UserRestrictionsUtils.writeRestrictions(serializer,
2296 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
2297 UserRestrictionsUtils.writeRestrictions(serializer,
2298 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
2299 TAG_DEVICE_POLICY_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002300 UserRestrictionsUtils.writeRestrictions(serializer,
2301 mDevicePolicyGlobalUserRestrictions.get(userInfo.id),
2302 TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS);
Kenny Guy02c89902016-11-15 19:36:38 +00002303 }
2304
2305 if (userData.account != null) {
2306 serializer.startTag(null, TAG_ACCOUNT);
2307 serializer.text(userData.account);
2308 serializer.endTag(null, TAG_ACCOUNT);
2309 }
2310
2311 if (userData.persistSeedData && userData.seedAccountOptions != null) {
2312 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2313 userData.seedAccountOptions.saveToXml(serializer);
2314 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
2315 }
2316
2317 serializer.endTag(null, TAG_USER);
2318
2319 serializer.endDocument();
2320 }
2321
2322 /*
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002323 * Writes the user list file in this format:
2324 *
Amith Yamasani2a003292012-08-14 18:25:45 -07002325 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002326 * <user id="0"></user>
2327 * <user id="2"></user>
2328 * </users>
2329 */
Andreas Gampe2e8c7672018-07-20 13:01:08 -07002330 @GuardedBy({"mRestrictionsLock", "mPackagesLock"})
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002331 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002332 if (DBG) {
2333 debug("writeUserList");
2334 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002335 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07002336 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002337 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002338 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002339 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2340
2341 // XmlSerializer serializer = XmlUtils.serializerInstance();
2342 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002343 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002344 serializer.startDocument(null, true);
2345 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2346
2347 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07002348 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07002349 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002350
Adam Lesinskieddeb492014-09-08 17:50:03 -07002351 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002352 synchronized (mGuestRestrictions) {
2353 UserRestrictionsUtils
2354 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
2355 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05302356 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Pavel Grafov6a40f092016-10-25 15:46:51 +01002357 serializer.startTag(null, TAG_DEVICE_OWNER_USER_ID);
2358 serializer.attribute(null, ATTR_ID, Integer.toString(mDeviceOwnerUserId));
2359 serializer.endTag(null, TAG_DEVICE_OWNER_USER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002360 int[] userIdsToWrite;
2361 synchronized (mUsersLock) {
2362 userIdsToWrite = new int[mUsers.size()];
2363 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002364 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002365 userIdsToWrite[i] = user.id;
2366 }
2367 }
2368 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002369 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002370 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002371 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002372 }
2373
2374 serializer.endTag(null, TAG_USERS);
2375
2376 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002377 userListFile.finishWrite(fos);
2378 } catch (Exception e) {
2379 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002380 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002381 }
2382 }
2383
Amith Yamasani12747872015-12-07 14:19:49 -08002384 private UserData readUserLP(int id) {
Kenny Guy02c89902016-11-15 19:36:38 +00002385 FileInputStream fis = null;
2386 try {
2387 AtomicFile userFile =
2388 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
2389 fis = userFile.openRead();
2390 return readUserLP(id, fis);
2391 } catch (IOException ioe) {
2392 Slog.e(LOG_TAG, "Error reading user list");
2393 } catch (XmlPullParserException pe) {
2394 Slog.e(LOG_TAG, "Error reading user list");
2395 } finally {
2396 IoUtils.closeQuietly(fis);
2397 }
2398 return null;
2399 }
2400
2401 @VisibleForTesting
2402 UserData readUserLP(int id, InputStream is) throws IOException,
2403 XmlPullParserException {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002404 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002405 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002406 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002407 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002408 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002409 long creationTime = 0L;
2410 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002411 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002412 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guy02c89902016-11-15 19:36:38 +00002413 int profileBadge = 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002414 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002415 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002416 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002417 boolean persistSeedData = false;
2418 String seedAccountName = null;
2419 String seedAccountType = null;
2420 PersistableBundle seedAccountOptions = null;
Pavel Grafov6a40f092016-10-25 15:46:51 +01002421 Bundle baseRestrictions = null;
2422 Bundle localRestrictions = null;
2423 Bundle globalRestrictions = null;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002424
Kenny Guy02c89902016-11-15 19:36:38 +00002425 XmlPullParser parser = Xml.newPullParser();
2426 parser.setInput(is, StandardCharsets.UTF_8.name());
2427 int type;
2428 while ((type = parser.next()) != XmlPullParser.START_TAG
2429 && type != XmlPullParser.END_DOCUMENT) {
2430 // Skip
2431 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002432
Kenny Guy02c89902016-11-15 19:36:38 +00002433 if (type != XmlPullParser.START_TAG) {
2434 Slog.e(LOG_TAG, "Unable to read user " + id);
2435 return null;
2436 }
2437
2438 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
2439 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2440 if (storedId != id) {
2441 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002442 return null;
2443 }
Kenny Guy02c89902016-11-15 19:36:38 +00002444 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2445 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
2446 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
2447 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2448 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
2449 lastLoggedInFingerprint = parser.getAttributeValue(null,
2450 ATTR_LAST_LOGGED_IN_FINGERPRINT);
2451 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2452 UserInfo.NO_PROFILE_GROUP_ID);
2453 profileBadge = readIntAttribute(parser, ATTR_PROFILE_BADGE, 0);
2454 restrictedProfileParentId = readIntAttribute(parser,
2455 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
2456 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2457 if ("true".equals(valueString)) {
2458 partial = true;
2459 }
2460 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2461 if ("true".equals(valueString)) {
2462 guestToRemove = true;
2463 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002464
Kenny Guy02c89902016-11-15 19:36:38 +00002465 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2466 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2467 if (seedAccountName != null || seedAccountType != null) {
2468 persistSeedData = true;
2469 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002470
Kenny Guy02c89902016-11-15 19:36:38 +00002471 int outerDepth = parser.getDepth();
2472 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2473 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2474 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2475 continue;
2476 }
2477 String tag = parser.getName();
2478 if (TAG_NAME.equals(tag)) {
2479 type = parser.next();
2480 if (type == XmlPullParser.TEXT) {
2481 name = parser.getText();
2482 }
2483 } else if (TAG_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002484 baseRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002485 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002486 localRestrictions = UserRestrictionsUtils.readRestrictions(parser);
2487 } else if (TAG_DEVICE_POLICY_GLOBAL_RESTRICTIONS.equals(tag)) {
2488 globalRestrictions = UserRestrictionsUtils.readRestrictions(parser);
Kenny Guy02c89902016-11-15 19:36:38 +00002489 } else if (TAG_ACCOUNT.equals(tag)) {
2490 type = parser.next();
2491 if (type == XmlPullParser.TEXT) {
2492 account = parser.getText();
2493 }
2494 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2495 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
Amith Yamasani12747872015-12-07 14:19:49 -08002496 persistSeedData = true;
2497 }
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002498 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002499 }
Kenny Guy02c89902016-11-15 19:36:38 +00002500
2501 // Create the UserInfo object that gets passed around
2502 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
2503 userInfo.serialNumber = serialNumber;
2504 userInfo.creationTime = creationTime;
2505 userInfo.lastLoggedInTime = lastLoggedInTime;
2506 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
2507 userInfo.partial = partial;
2508 userInfo.guestToRemove = guestToRemove;
2509 userInfo.profileGroupId = profileGroupId;
2510 userInfo.profileBadge = profileBadge;
2511 userInfo.restrictedProfileParentId = restrictedProfileParentId;
2512
2513 // Create the UserData object that's internal to this class
2514 UserData userData = new UserData();
2515 userData.info = userInfo;
2516 userData.account = account;
2517 userData.seedAccountName = seedAccountName;
2518 userData.seedAccountType = seedAccountType;
2519 userData.persistSeedData = persistSeedData;
2520 userData.seedAccountOptions = seedAccountOptions;
2521
2522 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01002523 if (baseRestrictions != null) {
2524 mBaseUserRestrictions.put(id, baseRestrictions);
2525 }
2526 if (localRestrictions != null) {
2527 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
2528 }
2529 if (globalRestrictions != null) {
2530 mDevicePolicyGlobalUserRestrictions.put(id, globalRestrictions);
2531 }
Kenny Guy02c89902016-11-15 19:36:38 +00002532 }
2533 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002534 }
2535
Amith Yamasani920ace02012-09-20 22:15:37 -07002536 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2537 String valueString = parser.getAttributeValue(null, attr);
2538 if (valueString == null) return defaultValue;
2539 try {
2540 return Integer.parseInt(valueString);
2541 } catch (NumberFormatException nfe) {
2542 return defaultValue;
2543 }
2544 }
2545
2546 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2547 String valueString = parser.getAttributeValue(null, attr);
2548 if (valueString == null) return defaultValue;
2549 try {
2550 return Long.parseLong(valueString);
2551 } catch (NumberFormatException nfe) {
2552 return defaultValue;
2553 }
2554 }
2555
Amith Yamasanib82add22013-07-09 11:24:44 -07002556 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002557 * Removes the app restrictions file for a specific package and user id, if it exists.
2558 */
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07002559 private static void cleanAppRestrictionsForPackageLAr(String pkg, int userId) {
2560 File dir = Environment.getUserSystemDirectory(userId);
2561 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
2562 if (resFile.exists()) {
2563 resFile.delete();
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002564 }
2565 }
2566
Kenny Guya52dc3e2014-02-11 15:33:14 +00002567 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002568 public UserInfo createProfileForUser(String name, int flags, int userId,
2569 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002570 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002571 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002572 }
2573
Amith Yamasani258848d2012-08-10 17:06:33 -07002574 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002575 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2576 String[] disallowedPackages) {
2577 checkManageOrCreateUsersPermission(flags);
2578 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2579 }
2580
2581 @Override
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002582 public boolean removeUserEvenWhenDisallowed(@UserIdInt int userHandle) {
2583 checkManageOrCreateUsersPermission("Only the system can remove users");
2584 return removeUserUnchecked(userHandle);
2585 }
2586
2587 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002588 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002589 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002590 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002591 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002592
Jessica Hummelbe81c802014-04-22 15:49:22 +01002593 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002594 return createUserInternal(name, flags, parentId, null);
2595 }
2596
2597 private UserInfo createUserInternal(String name, int flags, int parentId,
2598 String[] disallowedPackages) {
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002599 String restriction = ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0)
2600 ? UserManager.DISALLOW_ADD_MANAGED_PROFILE
2601 : UserManager.DISALLOW_ADD_USER;
2602 if (hasUserRestriction(restriction, UserHandle.getCallingUserId())) {
2603 Log.w(LOG_TAG, "Cannot add user. " + restriction + " is enabled.");
Julia Reynolds75175022014-06-26 16:35:00 -04002604 return null;
2605 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002606 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2607 }
2608
2609 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2610 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002611 DeviceStorageMonitorInternal dsm = LocalServices
2612 .getService(DeviceStorageMonitorInternal.class);
2613 if (dsm.isMemoryLow()) {
2614 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2615 return null;
2616 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002617 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002618 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002619 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002620 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002621 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002622 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002623 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002624 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002625 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002626 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002627 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002628 if (parentId != UserHandle.USER_NULL) {
2629 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002630 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002631 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002632 if (parent == null) return null;
2633 }
2634 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2635 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2636 return null;
2637 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002638 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2639 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002640 // been reached, cannot add a user.
2641 return null;
2642 }
2643 // If we're adding a guest and there already exists one, bail.
2644 if (isGuest && findCurrentGuestUser() != null) {
2645 return null;
2646 }
2647 // In legacy mode, restricted profile's parent can only be the owner user
2648 if (isRestricted && !UserManager.isSplitSystemUser()
2649 && (parentId != UserHandle.USER_SYSTEM)) {
2650 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2651 return null;
2652 }
2653 if (isRestricted && UserManager.isSplitSystemUser()) {
2654 if (parent == null) {
2655 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2656 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002657 return null;
2658 }
Amith Yamasani12747872015-12-07 14:19:49 -08002659 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002660 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2661 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002662 return null;
2663 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002664 }
2665 // In split system user mode, we assign the first human user the primary flag.
2666 // And if there is no device owner, we also assign the admin flag to primary user.
2667 if (UserManager.isSplitSystemUser()
2668 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2669 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002670 synchronized (mUsersLock) {
2671 if (!mIsDeviceManaged) {
2672 flags |= UserInfo.FLAG_ADMIN;
2673 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002674 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002675 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002676
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002677 userId = getNextAvailableId();
2678 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002679 boolean ephemeralGuests = Resources.getSystem()
2680 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002681
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002682 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002683 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2684 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2685 || (parent != null && parent.info.isEphemeral())) {
2686 flags |= UserInfo.FLAG_EPHEMERAL;
2687 }
2688
2689 userInfo = new UserInfo(userId, name, null, flags);
2690 userInfo.serialNumber = mNextSerialNumber++;
2691 long now = System.currentTimeMillis();
2692 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2693 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002694 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Kenny Guy02c89902016-11-15 19:36:38 +00002695 if (isManagedProfile && parentId != UserHandle.USER_NULL) {
2696 userInfo.profileBadge = getFreeProfileBadgeLU(parentId);
2697 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002698 userData = new UserData();
2699 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002700 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002701 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002702 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002703 writeUserListLP();
2704 if (parent != null) {
2705 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002706 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2707 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002708 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002709 }
Amith Yamasani12747872015-12-07 14:19:49 -08002710 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002711 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002712 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2713 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002714 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002715 }
Amith Yamasani12747872015-12-07 14:19:49 -08002716 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002717 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002718 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002719 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002720 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002721 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08002722 mUserDataPreparer.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002723 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002724 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002725 userInfo.partial = false;
2726 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002727 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002728 }
2729 updateUserIds();
2730 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002731 if (isGuest) {
2732 synchronized (mGuestRestrictions) {
2733 restrictions.putAll(mGuestRestrictions);
2734 }
2735 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002736 synchronized (mRestrictionsLock) {
2737 mBaseUserRestrictions.append(userId, restrictions);
2738 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002739 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002740 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2741 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2742 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2743 android.Manifest.permission.MANAGE_USERS);
Christine Franks88220562017-05-24 11:11:21 -07002744 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED
2745 : (isDemo ? TRON_DEMO_CREATED : TRON_USER_CREATED), 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002746 } finally {
2747 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002748 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002749 return userInfo;
2750 }
2751
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002752 @VisibleForTesting
2753 UserData putUserInfo(UserInfo userInfo) {
2754 final UserData userData = new UserData();
2755 userData.info = userInfo;
2756 synchronized (mUsers) {
2757 mUsers.put(userInfo.id, userData);
2758 }
2759 return userData;
2760 }
2761
2762 @VisibleForTesting
2763 void removeUserInfo(int userId) {
2764 synchronized (mUsers) {
2765 mUsers.remove(userId);
2766 }
2767 }
2768
Amith Yamasani0b285492011-04-14 17:35:23 -07002769 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002770 * @hide
2771 */
Amith Yamasani12747872015-12-07 14:19:49 -08002772 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002773 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002774 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002775 final UserInfo user = createProfileForUser(
2776 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002777 if (user == null) {
2778 return null;
2779 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002780 long identity = Binder.clearCallingIdentity();
2781 try {
2782 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2783 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2784 // the putIntForUser() will fail.
2785 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2786 android.provider.Settings.Secure.LOCATION_MODE,
2787 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2788 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2789 } finally {
2790 Binder.restoreCallingIdentity(identity);
2791 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002792 return user;
2793 }
2794
2795 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002796 * Find the current guest user. If the Guest user is partial,
2797 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002798 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002799 private UserInfo findCurrentGuestUser() {
2800 synchronized (mUsersLock) {
2801 final int size = mUsers.size();
2802 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002803 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002804 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2805 return user;
2806 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002807 }
2808 }
2809 return null;
2810 }
2811
2812 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002813 * Mark this guest user for deletion to allow us to create another guest
2814 * and switch to that user before actually removing this guest.
2815 * @param userHandle the userid of the current guest
2816 * @return whether the user could be marked for deletion
2817 */
Amith Yamasani12747872015-12-07 14:19:49 -08002818 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002819 public boolean markGuestForDeletion(int userHandle) {
2820 checkManageUsersPermission("Only the system can remove users");
2821 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2822 UserManager.DISALLOW_REMOVE_USER, false)) {
2823 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2824 return false;
2825 }
2826
2827 long ident = Binder.clearCallingIdentity();
2828 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002829 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002830 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002831 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002832 userData = mUsers.get(userHandle);
2833 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002834 return false;
2835 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002836 }
Amith Yamasani12747872015-12-07 14:19:49 -08002837 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002838 return false;
2839 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002840 // We set this to a guest user that is to be removed. This is a temporary state
2841 // where we are allowed to add new Guest users, even if this one is still not
2842 // removed. This user will still show up in getUserInfo() calls.
2843 // If we don't get around to removing this Guest user, it will be purged on next
2844 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002845 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002846 // Mark it as disabled, so that it isn't returned any more when
2847 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002848 userData.info.flags |= UserInfo.FLAG_DISABLED;
2849 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002850 }
2851 } finally {
2852 Binder.restoreCallingIdentity(ident);
2853 }
2854 return true;
2855 }
2856
2857 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002858 * Removes a user and all data directories created for that user. This method should be called
2859 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002860 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002861 */
Amith Yamasani12747872015-12-07 14:19:49 -08002862 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002863 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002864 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002865 checkManageOrCreateUsersPermission("Only the system can remove users");
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002866
2867 final boolean isManagedProfile;
2868 synchronized (mUsersLock) {
2869 UserInfo userInfo = getUserInfoLU(userHandle);
2870 isManagedProfile = userInfo != null && userInfo.isManagedProfile();
2871 }
2872 String restriction = isManagedProfile
2873 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
2874 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
2875 Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002876 return false;
2877 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002878 return removeUserUnchecked(userHandle);
2879 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002880
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002881 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002882 long ident = Binder.clearCallingIdentity();
2883 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002884 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002885 int currentUser = ActivityManager.getCurrentUser();
2886 if (currentUser == userHandle) {
2887 Log.w(LOG_TAG, "Current user cannot be removed");
2888 return false;
2889 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002890 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002891 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002892 userData = mUsers.get(userHandle);
2893 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002894 return false;
2895 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002896
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002897 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002898 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002899
Kenny Guyee58b4f2014-05-23 15:19:53 +01002900 // Set this to a partially created user, so that the user will be purged
2901 // on next startup, in case the runtime stops now before stopping and
2902 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002903 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002904 // Mark it as disabled, so that it isn't returned any more when
2905 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002906 userData.info.flags |= UserInfo.FLAG_DISABLED;
2907 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002908 }
Fyodor Kupolov6c96f7f2017-06-28 18:22:59 -07002909 try {
2910 mAppOpsService.removeUser(userHandle);
2911 } catch (RemoteException e) {
2912 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2913 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002914
Amith Yamasani12747872015-12-07 14:19:49 -08002915 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2916 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002917 // Send broadcast to notify system that the user removed was a
2918 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002919 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002920 }
2921
2922 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2923 int res;
2924 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002925 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002926 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002927 @Override
2928 public void userStopped(int userId) {
2929 finishRemoveUser(userId);
2930 }
2931 @Override
2932 public void userStopAborted(int userId) {
2933 }
2934 });
2935 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002936 return false;
2937 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002938 return res == ActivityManager.USER_OP_SUCCESS;
2939 } finally {
2940 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002941 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002942 }
2943
Andreas Gampea36dc622018-02-05 17:19:22 -08002944 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002945 @VisibleForTesting
2946 void addRemovingUserIdLocked(int userId) {
2947 // We remember deleted user IDs to prevent them from being
2948 // reused during the current boot; they can still be reused
2949 // after a reboot or recycling of userIds.
2950 mRemovingUserIds.put(userId, true);
2951 mRecentlyRemovedIds.add(userId);
2952 // Keep LRU queue of recently removed IDs for recycling
2953 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2954 mRecentlyRemovedIds.removeFirst();
2955 }
2956 }
2957
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002958 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002959 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002960 // Let other services shutdown any activity and clean up their state before completely
2961 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002962 long ident = Binder.clearCallingIdentity();
2963 try {
2964 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2965 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002966 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2967 android.Manifest.permission.MANAGE_USERS,
2968
2969 new BroadcastReceiver() {
2970 @Override
2971 public void onReceive(Context context, Intent intent) {
2972 if (DBG) {
2973 Slog.i(LOG_TAG,
2974 "USER_REMOVED broadcast sent, cleaning up user data "
2975 + userHandle);
2976 }
2977 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002978 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002979 public void run() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002980 // Clean up any ActivityTaskManager state
2981 LocalServices.getService(ActivityTaskManagerInternal.class)
2982 .onUserStopped(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002983 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002984 }
2985 }.start();
2986 }
2987 },
2988
2989 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002990 } finally {
2991 Binder.restoreCallingIdentity(ident);
2992 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002993 }
2994
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002995 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002996 try {
2997 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2998 } catch (IllegalStateException e) {
2999 // This may be simply because the user was partially created.
3000 Slog.i(LOG_TAG,
3001 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
3002 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06003003
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003004 // Cleanup gatekeeper secure user id
3005 try {
3006 final IGateKeeperService gk = GateKeeper.getService();
3007 if (gk != null) {
3008 gk.clearSecureUserId(userHandle);
3009 }
3010 } catch (Exception ex) {
3011 Slog.w(LOG_TAG, "unable to clear GK secure user id");
3012 }
3013
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003014 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003015 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003016
3017 // Clean up all data before removing metadata
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003018 mUserDataPreparer.destroyUserData(userHandle,
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003019 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3020
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003021 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07003022 synchronized (mUsersLock) {
3023 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003024 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003025 }
3026 synchronized (mUserStates) {
3027 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08003028 }
3029 synchronized (mRestrictionsLock) {
3030 mBaseUserRestrictions.remove(userHandle);
3031 mAppliedUserRestrictions.remove(userHandle);
3032 mCachedEffectiveUserRestrictions.remove(userHandle);
3033 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Pavel Grafov6a40f092016-10-25 15:46:51 +01003034 if (mDevicePolicyGlobalUserRestrictions.get(userHandle) != null) {
3035 mDevicePolicyGlobalUserRestrictions.remove(userHandle);
3036 applyUserRestrictionsForAllUsersLR();
3037 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003038 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003039 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003040 synchronized (mPackagesLock) {
3041 writeUserListLP();
3042 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06003043 // Remove user file
3044 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
3045 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07003046 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003047 if (RELEASE_DELETED_USER_ID) {
3048 synchronized (mUsers) {
3049 mRemovingUserIds.delete(userHandle);
3050 }
3051 }
Amith Yamasani61f57372012-08-31 12:12:28 -07003052 }
3053
Kenny Guyf8d3a232014-05-15 16:09:52 +01003054 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01003055 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01003056 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3057 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003058 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07003059 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01003060 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01003061 }
3062
Amith Yamasani2a003292012-08-14 18:25:45 -07003063 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003064 public Bundle getApplicationRestrictions(String packageName) {
3065 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
3066 }
3067
3068 @Override
3069 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003070 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07003071 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003072 checkSystemOrRoot("get application restrictions for other user/app " + packageName);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003073 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003074 synchronized (mAppRestrictionsLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003075 // Read the restrictions from XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003076 return readApplicationRestrictionsLAr(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003077 }
3078 }
3079
3080 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003081 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003082 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00003083 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07003084 if (restrictions != null) {
3085 restrictions.setDefusable(true);
3086 }
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003087 synchronized (mAppRestrictionsLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01003088 if (restrictions == null || restrictions.isEmpty()) {
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003089 cleanAppRestrictionsForPackageLAr(packageName, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003090 } else {
3091 // Write the restrictions to XML
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003092 writeApplicationRestrictionsLAr(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01003093 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003094 }
Robin Lee66e5d962014-04-09 16:44:21 +01003095
Fyodor Kupolovd2846122016-02-11 18:06:34 -08003096 // Notify package of changes via an intent - only sent to explicitly registered receivers.
3097 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
3098 changeIntent.setPackage(packageName);
3099 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3100 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003101 }
3102
3103 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07003104 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003105 try {
3106 return mContext.getPackageManager().getApplicationInfo(packageName,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07003107 PackageManager.MATCH_ANY_USER).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003108 } catch (NameNotFoundException nnfe) {
3109 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07003110 } finally {
3111 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003112 }
3113 }
3114
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003115 @GuardedBy("mAppRestrictionsLock")
3116 private static Bundle readApplicationRestrictionsLAr(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003117 AtomicFile restrictionsFile =
3118 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
3119 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003120 return readApplicationRestrictionsLAr(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003121 }
3122
3123 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003124 @GuardedBy("mAppRestrictionsLock")
3125 static Bundle readApplicationRestrictionsLAr(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003126 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003127 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003128 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07003129 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07003130 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003131
3132 FileInputStream fis = null;
3133 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003134 fis = restrictionsFile.openRead();
3135 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003136 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003137 XmlUtils.nextElement(parser);
3138 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003139 Slog.e(LOG_TAG, "Unable to read restrictions file "
3140 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003141 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003142 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003143 while (parser.next() != XmlPullParser.END_DOCUMENT) {
3144 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003145 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003146 } catch (IOException|XmlPullParserException e) {
3147 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003148 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003149 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003150 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003151 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003152 }
3153
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003154 private static void readEntry(Bundle restrictions, ArrayList<String> values,
3155 XmlPullParser parser) throws XmlPullParserException, IOException {
3156 int type = parser.getEventType();
3157 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
3158 String key = parser.getAttributeValue(null, ATTR_KEY);
3159 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
3160 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
3161 if (multiple != null) {
3162 values.clear();
3163 int count = Integer.parseInt(multiple);
3164 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
3165 if (type == XmlPullParser.START_TAG
3166 && parser.getName().equals(TAG_VALUE)) {
3167 values.add(parser.nextText().trim());
3168 count--;
3169 }
3170 }
3171 String [] valueStrings = new String[values.size()];
3172 values.toArray(valueStrings);
3173 restrictions.putStringArray(key, valueStrings);
3174 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
3175 restrictions.putBundle(key, readBundleEntry(parser, values));
3176 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
3177 final int outerDepth = parser.getDepth();
3178 ArrayList<Bundle> bundleList = new ArrayList<>();
3179 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3180 Bundle childBundle = readBundleEntry(parser, values);
3181 bundleList.add(childBundle);
3182 }
3183 restrictions.putParcelableArray(key,
3184 bundleList.toArray(new Bundle[bundleList.size()]));
3185 } else {
3186 String value = parser.nextText().trim();
3187 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
3188 restrictions.putBoolean(key, Boolean.parseBoolean(value));
3189 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
3190 restrictions.putInt(key, Integer.parseInt(value));
3191 } else {
3192 restrictions.putString(key, value);
3193 }
3194 }
3195 }
3196 }
3197
3198 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
3199 throws IOException, XmlPullParserException {
3200 Bundle childBundle = new Bundle();
3201 final int outerDepth = parser.getDepth();
3202 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
3203 readEntry(childBundle, values, parser);
3204 }
3205 return childBundle;
3206 }
3207
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003208 @GuardedBy("mAppRestrictionsLock")
3209 private static void writeApplicationRestrictionsLAr(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07003210 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003211 AtomicFile restrictionsFile = new AtomicFile(
3212 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07003213 packageToRestrictionsFileName(packageName)));
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003214 writeApplicationRestrictionsLAr(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003215 }
3216
3217 @VisibleForTesting
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003218 @GuardedBy("mAppRestrictionsLock")
3219 static void writeApplicationRestrictionsLAr(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003220 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003221 try {
3222 fos = restrictionsFile.startWrite();
3223 final BufferedOutputStream bos = new BufferedOutputStream(fos);
3224
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003225 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003226 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003227 serializer.startDocument(null, true);
3228 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3229
3230 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003231 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003232 serializer.endTag(null, TAG_RESTRICTIONS);
3233
3234 serializer.endDocument();
3235 restrictionsFile.finishWrite(fos);
3236 } catch (Exception e) {
3237 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07003238 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
3239 }
3240 }
3241
3242 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
3243 throws IOException {
3244 for (String key : restrictions.keySet()) {
3245 Object value = restrictions.get(key);
3246 serializer.startTag(null, TAG_ENTRY);
3247 serializer.attribute(null, ATTR_KEY, key);
3248
3249 if (value instanceof Boolean) {
3250 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
3251 serializer.text(value.toString());
3252 } else if (value instanceof Integer) {
3253 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
3254 serializer.text(value.toString());
3255 } else if (value == null || value instanceof String) {
3256 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
3257 serializer.text(value != null ? (String) value : "");
3258 } else if (value instanceof Bundle) {
3259 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3260 writeBundle((Bundle) value, serializer);
3261 } else if (value instanceof Parcelable[]) {
3262 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
3263 Parcelable[] array = (Parcelable[]) value;
3264 for (Parcelable parcelable : array) {
3265 if (!(parcelable instanceof Bundle)) {
3266 throw new IllegalArgumentException("bundle-array can only hold Bundles");
3267 }
3268 serializer.startTag(null, TAG_ENTRY);
3269 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
3270 writeBundle((Bundle) parcelable, serializer);
3271 serializer.endTag(null, TAG_ENTRY);
3272 }
3273 } else {
3274 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
3275 String[] values = (String[]) value;
3276 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
3277 for (String choice : values) {
3278 serializer.startTag(null, TAG_VALUE);
3279 serializer.text(choice != null ? choice : "");
3280 serializer.endTag(null, TAG_VALUE);
3281 }
3282 }
3283 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003284 }
3285 }
3286
3287 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003288 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003289 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003290 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003291 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07003292 }
3293 }
3294
3295 @Override
Fyodor Kupolov605b12a2017-05-10 15:58:09 -07003296 public boolean isUserNameSet(int userHandle) {
3297 synchronized (mUsersLock) {
3298 UserInfo userInfo = getUserInfoLU(userHandle);
3299 return userInfo != null && userInfo.name != null;
3300 }
3301 }
3302
3303 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07003304 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003305 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07003306 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003307 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00003308 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07003309 }
3310 // Not found
3311 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07003312 }
3313 }
3314
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003315 @Override
3316 public long getUserCreationTime(int userHandle) {
3317 int callingUserId = UserHandle.getCallingUserId();
3318 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003319 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003320 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003321 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003322 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003323 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003324 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003325 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07003326 }
3327 }
3328 }
3329 if (userInfo == null) {
3330 throw new SecurityException("userHandle can only be the calling user or a managed "
3331 + "profile associated with this user");
3332 }
3333 return userInfo.creationTime;
3334 }
3335
Amith Yamasani0b285492011-04-14 17:35:23 -07003336 /**
3337 * Caches the list of user ids in an array, adjusting the array size when necessary.
3338 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07003339 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003340 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003341 synchronized (mUsersLock) {
3342 final int userSize = mUsers.size();
3343 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003344 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003345 num++;
3346 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003347 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003348 final int[] newUsers = new int[num];
3349 int n = 0;
3350 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003351 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003352 newUsers[n++] = mUsers.keyAt(i);
3353 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003354 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07003355 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07003356 }
3357 }
3358
3359 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003360 * Called right before a user is started. This gives us a chance to prepare
3361 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003362 */
3363 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003364 UserInfo userInfo = getUserInfo(userId);
3365 if (userInfo == null) {
3366 return;
3367 }
3368 final int userSerial = userInfo.serialNumber;
3369 // Migrate only if build fingerprints mismatch
3370 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003371 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003372 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003373
3374 if (userId != UserHandle.USER_SYSTEM) {
3375 synchronized (mRestrictionsLock) {
3376 applyUserRestrictionsLR(userId);
3377 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003378 }
3379 }
3380
3381 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003382 * Called right before a user is unlocked. This gives us a chance to prepare
3383 * app storage.
3384 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003385 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003386 UserInfo userInfo = getUserInfo(userId);
3387 if (userInfo == null) {
3388 return;
3389 }
3390 final int userSerial = userInfo.serialNumber;
3391 // Migrate only if build fingerprints mismatch
3392 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Fyodor Kupolov5c0ecfd2017-01-27 11:11:57 -08003393 mUserDataPreparer.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07003394 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07003395 }
3396
3397 /**
Fyodor Kupolov50979d12017-01-27 17:36:32 -08003398 * Examine all users present on given mounted volume, and destroy data
3399 * belonging to users that are no longer valid, or whose user ID has been
3400 * recycled.
3401 */
3402 void reconcileUsers(String volumeUuid) {
3403 mUserDataPreparer.reconcileUsers(volumeUuid, getUsers(true /* excludeDying */));
3404 }
3405
3406 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07003407 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07003408 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07003409 * @param userId the user that was just foregrounded
3410 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003411 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003412 UserData userData = getUserDataNoChecks(userId);
3413 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003414 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3415 return;
3416 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003417
3418 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003419 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003420 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003421 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003422 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3423 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003424 }
3425
3426 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003427 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003428 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003429 @VisibleForTesting
3430 int getNextAvailableId() {
3431 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003432 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003433 nextId = scanNextAvailableIdLocked();
3434 if (nextId >= 0) {
3435 return nextId;
3436 }
3437 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3438 // except most recently removed
3439 if (mRemovingUserIds.size() > 0) {
3440 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3441 mRemovingUserIds.clear();
3442 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3443 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003444 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003445 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003446 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003447 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003448 if (nextId < 0) {
3449 throw new IllegalStateException("No user id available!");
3450 }
3451 return nextId;
3452 }
3453
Andreas Gampea36dc622018-02-05 17:19:22 -08003454 @GuardedBy("mUsersLock")
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003455 private int scanNextAvailableIdLocked() {
3456 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3457 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3458 return i;
3459 }
3460 }
3461 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003462 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003463
Fyodor Kupolovd31cee92017-09-05 16:31:08 -07003464 private static String packageToRestrictionsFileName(String packageName) {
Amith Yamasanifc95e702013-09-26 13:20:17 -07003465 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3466 }
3467
Amith Yamasani920ace02012-09-20 22:15:37 -07003468 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003469 public void setSeedAccountData(int userId, String accountName, String accountType,
3470 PersistableBundle accountOptions, boolean persist) {
3471 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3472 synchronized (mPackagesLock) {
3473 final UserData userData;
3474 synchronized (mUsersLock) {
3475 userData = getUserDataLU(userId);
3476 if (userData == null) {
3477 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3478 return;
3479 }
3480 userData.seedAccountName = accountName;
3481 userData.seedAccountType = accountType;
3482 userData.seedAccountOptions = accountOptions;
3483 userData.persistSeedData = persist;
3484 }
3485 if (persist) {
3486 writeUserLP(userData);
3487 }
3488 }
3489 }
3490
3491 @Override
3492 public String getSeedAccountName() throws RemoteException {
3493 checkManageUsersPermission("Cannot get seed account information");
3494 synchronized (mUsersLock) {
3495 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3496 return userData.seedAccountName;
3497 }
3498 }
3499
3500 @Override
3501 public String getSeedAccountType() throws RemoteException {
3502 checkManageUsersPermission("Cannot get seed account information");
3503 synchronized (mUsersLock) {
3504 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3505 return userData.seedAccountType;
3506 }
3507 }
3508
3509 @Override
3510 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3511 checkManageUsersPermission("Cannot get seed account information");
3512 synchronized (mUsersLock) {
3513 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3514 return userData.seedAccountOptions;
3515 }
3516 }
3517
3518 @Override
3519 public void clearSeedAccountData() throws RemoteException {
3520 checkManageUsersPermission("Cannot clear seed account information");
3521 synchronized (mPackagesLock) {
3522 UserData userData;
3523 synchronized (mUsersLock) {
3524 userData = getUserDataLU(UserHandle.getCallingUserId());
3525 if (userData == null) return;
3526 userData.clearSeedAccountData();
3527 }
3528 writeUserLP(userData);
3529 }
3530 }
3531
3532 @Override
3533 public boolean someUserHasSeedAccount(String accountName, String accountType)
3534 throws RemoteException {
3535 checkManageUsersPermission("Cannot check seed account information");
3536 synchronized (mUsersLock) {
3537 final int userSize = mUsers.size();
3538 for (int i = 0; i < userSize; i++) {
3539 final UserData data = mUsers.valueAt(i);
3540 if (data.info.isInitialized()) continue;
3541 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3542 continue;
3543 }
3544 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3545 continue;
3546 }
3547 return true;
3548 }
3549 }
3550 return false;
3551 }
3552
3553 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003554 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003555 FileDescriptor err, String[] args, ShellCallback callback,
3556 ResultReceiver resultReceiver) {
3557 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003558 }
3559
3560 int onShellCommand(Shell shell, String cmd) {
3561 if (cmd == null) {
3562 return shell.handleDefaultCommands(cmd);
3563 }
3564
3565 final PrintWriter pw = shell.getOutPrintWriter();
3566 try {
3567 switch(cmd) {
3568 case "list":
3569 return runList(pw);
Hui Yu8ba65972018-04-16 18:45:48 -07003570 default:
3571 return shell.handleDefaultCommands(cmd);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003572 }
3573 } catch (RemoteException e) {
3574 pw.println("Remote exception: " + e);
3575 }
3576 return -1;
3577 }
3578
3579 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003580 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003581 final List<UserInfo> users = getUsers(false);
3582 if (users == null) {
3583 pw.println("Error: couldn't get users");
3584 return 1;
3585 } else {
3586 pw.println("Users:");
3587 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003588 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003589 pw.println("\t" + users.get(i).toString() + running);
3590 }
3591 return 0;
3592 }
3593 }
3594
3595 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003596 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003597 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
Amith Yamasani920ace02012-09-20 22:15:37 -07003598
3599 long now = System.currentTimeMillis();
Makoto Onuki73dded22017-12-20 13:14:48 +09003600 final long nowRealtime = SystemClock.elapsedRealtime();
Amith Yamasani920ace02012-09-20 22:15:37 -07003601 StringBuilder sb = new StringBuilder();
3602 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003603 synchronized (mUsersLock) {
3604 pw.println("Users:");
3605 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003606 UserData userData = mUsers.valueAt(i);
3607 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003608 continue;
3609 }
Amith Yamasani12747872015-12-07 14:19:49 -08003610 UserInfo userInfo = userData.info;
3611 final int userId = userInfo.id;
3612 pw.print(" "); pw.print(userInfo);
3613 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003614 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003615 pw.print(" <removing> ");
3616 }
Amith Yamasani12747872015-12-07 14:19:49 -08003617 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003618 pw.print(" <partial>");
3619 }
3620 pw.println();
Makoto Onuki88aef752017-03-29 16:52:03 -07003621 pw.print(" State: ");
3622 final int state;
3623 synchronized (mUserStates) {
3624 state = mUserStates.get(userId, -1);
3625 }
3626 pw.println(UserState.stateToString(state));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003627 pw.print(" Created: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003628 dumpTimeAgo(pw, sb, now, userInfo.creationTime);
3629
Fyodor Kupolov82402752015-10-28 14:54:51 -07003630 pw.print(" Last logged in: ");
Makoto Onuki73dded22017-12-20 13:14:48 +09003631 dumpTimeAgo(pw, sb, now, userInfo.lastLoggedInTime);
3632
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003633 pw.print(" Last logged in fingerprint: ");
3634 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onuki73dded22017-12-20 13:14:48 +09003635
3636 pw.print(" Start time: ");
3637 dumpTimeAgo(pw, sb, nowRealtime, userData.startRealtime);
3638
3639 pw.print(" Unlock time: ");
3640 dumpTimeAgo(pw, sb, nowRealtime, userData.unlockRealtime);
3641
Makoto Onukie7927da2015-11-25 10:05:17 -08003642 pw.print(" Has profile owner: ");
3643 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003644 pw.println(" Restrictions:");
3645 synchronized (mRestrictionsLock) {
3646 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003647 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Pavel Grafov6a40f092016-10-25 15:46:51 +01003648 pw.println(" Device policy global restrictions:");
3649 UserRestrictionsUtils.dumpRestrictions(
3650 pw, " ", mDevicePolicyGlobalUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003651 pw.println(" Device policy local restrictions:");
3652 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003653 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003654 pw.println(" Effective restrictions:");
3655 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003656 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003657 }
Amith Yamasani12747872015-12-07 14:19:49 -08003658
3659 if (userData.account != null) {
3660 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003661 pw.println();
3662 }
Amith Yamasani12747872015-12-07 14:19:49 -08003663
3664 if (userData.seedAccountName != null) {
3665 pw.print(" Seed account name: " + userData.seedAccountName);
3666 pw.println();
3667 if (userData.seedAccountType != null) {
3668 pw.print(" account type: " + userData.seedAccountType);
3669 pw.println();
3670 }
3671 if (userData.seedAccountOptions != null) {
3672 pw.print(" account options exist");
3673 pw.println();
3674 }
3675 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003676 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003677 }
Amith Yamasani12747872015-12-07 14:19:49 -08003678 pw.println();
Pavel Grafov6a40f092016-10-25 15:46:51 +01003679 pw.println(" Device owner id:" + mDeviceOwnerUserId);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003680 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003681 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003682 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003683 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003684 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003685 synchronized (mUsersLock) {
3686 pw.println();
3687 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003688 if (mRemovingUserIds.size() > 0) {
3689 pw.println();
3690 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3691 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003692 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003693 synchronized (mUserStates) {
3694 pw.println(" Started users state: " + mUserStates);
3695 }
Amith Yamasani12747872015-12-07 14:19:49 -08003696 // Dump some capabilities
3697 pw.println();
3698 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3699 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003700 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3701 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003702 }
3703 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003704
Makoto Onuki73dded22017-12-20 13:14:48 +09003705 private static void dumpTimeAgo(PrintWriter pw, StringBuilder sb, long nowTime, long time) {
3706 if (time == 0) {
3707 pw.println("<unknown>");
3708 } else {
3709 sb.setLength(0);
3710 TimeUtils.formatDuration(nowTime - time, sb);
3711 sb.append(" ago");
3712 pw.println(sb);
3713 }
3714 }
3715
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003716 final class MainHandler extends Handler {
3717
3718 @Override
3719 public void handleMessage(Message msg) {
3720 switch (msg.what) {
3721 case WRITE_USER_MSG:
3722 removeMessages(WRITE_USER_MSG, msg.obj);
3723 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003724 int userId = ((UserData) msg.obj).info.id;
3725 UserData userData = getUserDataNoChecks(userId);
3726 if (userData != null) {
3727 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003728 }
3729 }
3730 }
3731 }
3732 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003733
3734 /**
3735 * @param userId
3736 * @return whether the user has been initialized yet
3737 */
Todd Kennedy0eb97382017-10-03 16:57:22 -07003738 boolean isUserInitialized(int userId) {
3739 return mLocalService.isUserInitialized(userId);
Amith Yamasanibb054c92015-07-09 14:16:27 -07003740 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003741
3742 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003743 @Override
Pavel Grafov6a40f092016-10-25 15:46:51 +01003744 public void setDevicePolicyUserRestrictions(int userId, @Nullable Bundle restrictions,
3745 boolean isDeviceOwner, int cameraRestrictionScope) {
3746 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, restrictions,
3747 isDeviceOwner, cameraRestrictionScope);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003748 }
3749
3750 @Override
3751 public Bundle getBaseUserRestrictions(int userId) {
3752 synchronized (mRestrictionsLock) {
3753 return mBaseUserRestrictions.get(userId);
3754 }
3755 }
3756
3757 @Override
3758 public void setBaseUserRestrictionsByDpmsForMigration(
3759 int userId, Bundle baseRestrictions) {
3760 synchronized (mRestrictionsLock) {
Pavel Grafov6a40f092016-10-25 15:46:51 +01003761 if (updateRestrictionsIfNeededLR(
3762 userId, new Bundle(baseRestrictions), mBaseUserRestrictions)) {
3763 invalidateEffectiveUserRestrictionsLR(userId);
3764 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003765 }
3766
Amith Yamasani12747872015-12-07 14:19:49 -08003767 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003768 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003769 if (userData != null) {
3770 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003771 } else {
3772 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3773 }
3774 }
3775 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003776
3777 @Override
3778 public boolean getUserRestriction(int userId, String key) {
3779 return getUserRestrictions(userId).getBoolean(key);
3780 }
3781
3782 @Override
3783 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3784 synchronized (mUserRestrictionsListeners) {
3785 mUserRestrictionsListeners.add(listener);
3786 }
3787 }
3788
3789 @Override
3790 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3791 synchronized (mUserRestrictionsListeners) {
3792 mUserRestrictionsListeners.remove(listener);
3793 }
3794 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003795
3796 @Override
3797 public void setDeviceManaged(boolean isManaged) {
3798 synchronized (mUsersLock) {
3799 mIsDeviceManaged = isManaged;
3800 }
3801 }
3802
3803 @Override
3804 public void setUserManaged(int userId, boolean isManaged) {
3805 synchronized (mUsersLock) {
3806 mIsUserManaged.put(userId, isManaged);
3807 }
3808 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003809
3810 @Override
3811 public void setUserIcon(int userId, Bitmap bitmap) {
3812 long ident = Binder.clearCallingIdentity();
3813 try {
3814 synchronized (mPackagesLock) {
3815 UserData userData = getUserDataNoChecks(userId);
3816 if (userData == null || userData.info.partial) {
3817 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3818 return;
3819 }
3820 writeBitmapLP(userData.info, bitmap);
3821 writeUserLP(userData);
3822 }
3823 sendUserInfoChangedBroadcast(userId);
3824 } finally {
3825 Binder.restoreCallingIdentity(ident);
3826 }
3827 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003828
3829 @Override
3830 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3831 synchronized (mUsersLock) {
3832 mForceEphemeralUsers = forceEphemeralUsers;
3833 }
3834 }
3835
3836 @Override
3837 public void removeAllUsers() {
3838 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3839 // Remove the non-system users straight away.
3840 removeNonSystemUsers();
3841 } else {
3842 // Switch to the system user first and then remove the other users.
3843 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3844 @Override
3845 public void onReceive(Context context, Intent intent) {
3846 int userId =
3847 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3848 if (userId != UserHandle.USER_SYSTEM) {
3849 return;
3850 }
3851 mContext.unregisterReceiver(this);
3852 removeNonSystemUsers();
3853 }
3854 };
3855 IntentFilter userSwitchedFilter = new IntentFilter();
3856 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3857 mContext.registerReceiver(
3858 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3859
3860 // Switch to the system user.
3861 ActivityManager am =
3862 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3863 am.switchUser(UserHandle.USER_SYSTEM);
3864 }
3865 }
phweisse9c44062016-02-10 12:57:38 +01003866
3867 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003868 public void onEphemeralUserStop(int userId) {
3869 synchronized (mUsersLock) {
3870 UserInfo userInfo = getUserInfoLU(userId);
3871 if (userInfo != null && userInfo.isEphemeral()) {
3872 // Do not allow switching back to the ephemeral user again as the user is going
3873 // to be deleted.
3874 userInfo.flags |= UserInfo.FLAG_DISABLED;
3875 if (userInfo.isGuest()) {
3876 // Indicate that the guest will be deleted after it stops.
3877 userInfo.guestToRemove = true;
3878 }
3879 }
3880 }
3881 }
3882
3883 @Override
Alex Chaub6a9f942017-11-07 11:28:56 +08003884 public UserInfo createUserEvenWhenDisallowed(String name, int flags,
3885 String[] disallowedPackages) {
3886 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL,
3887 disallowedPackages);
phweisse9c44062016-02-10 12:57:38 +01003888 // Keep this in sync with UserManager.createUser
Christine Franks97a54802017-08-09 10:06:43 -07003889 if (user != null && !user.isAdmin() && !user.isDemo()) {
phweisse9c44062016-02-10 12:57:38 +01003890 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3891 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3892 }
3893 return user;
3894 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003895
3896 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003897 public boolean removeUserEvenWhenDisallowed(int userId) {
3898 return removeUserUnchecked(userId);
3899 }
3900
3901 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003902 public boolean isUserRunning(int userId) {
3903 synchronized (mUserStates) {
3904 return mUserStates.get(userId, -1) >= 0;
3905 }
3906 }
3907
3908 @Override
3909 public void setUserState(int userId, int userState) {
3910 synchronized (mUserStates) {
3911 mUserStates.put(userId, userState);
3912 }
3913 }
3914
3915 @Override
3916 public void removeUserState(int userId) {
3917 synchronized (mUserStates) {
3918 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003919 }
3920 }
3921
3922 @Override
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07003923 public int[] getUserIds() {
3924 return UserManagerService.this.getUserIds();
3925 }
3926
3927 @Override
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003928 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003929 int state;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003930 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003931 state = mUserStates.get(userId, -1);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003932 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003933 // Special case, in the stopping/shutdown state user key can still be unlocked
3934 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3935 return StorageManager.isUserKeyUnlocked(userId);
3936 }
3937 return (state == UserState.STATE_RUNNING_UNLOCKING)
3938 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003939 }
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003940
3941 @Override
3942 public boolean isUserUnlocked(int userId) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003943 int state;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003944 synchronized (mUserStates) {
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003945 state = mUserStates.get(userId, -1);
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003946 }
Fyodor Kupolov0468ee92017-05-25 17:06:17 -07003947 // Special case, in the stopping/shutdown state user key can still be unlocked
3948 if (state == UserState.STATE_STOPPING || state == UserState.STATE_SHUTDOWN) {
3949 return StorageManager.isUserKeyUnlocked(userId);
3950 }
3951 return state == UserState.STATE_RUNNING_UNLOCKED;
Fyodor Kupolov2e7e0962016-12-01 18:09:17 -08003952 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07003953
3954 @Override
3955 public boolean isUserInitialized(int userId) {
3956 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3957 }
3958
3959 @Override
3960 public boolean exists(int userId) {
3961 return getUserInfoNoChecks(userId) != null;
3962 }
Sunny Goyal145c8f82018-02-15 14:27:09 -08003963
3964 @Override
3965 public boolean isProfileAccessible(int callingUserId, int targetUserId, String debugMsg,
3966 boolean throwSecurityException) {
3967 if (targetUserId == callingUserId) {
3968 return true;
3969 }
3970 synchronized (mUsersLock) {
3971 UserInfo callingUserInfo = getUserInfoLU(callingUserId);
3972 if (callingUserInfo == null || callingUserInfo.isManagedProfile()) {
3973 if (throwSecurityException) {
3974 throw new SecurityException(
3975 debugMsg + " for another profile "
3976 + targetUserId + " from " + callingUserId);
3977 }
3978 }
3979
3980 UserInfo targetUserInfo = getUserInfoLU(targetUserId);
3981 if (targetUserInfo == null || !targetUserInfo.isEnabled()) {
3982 // Do not throw any exception here as this could happen due to race conditions
3983 // between the system updating its state and the client getting notified.
3984 if (throwSecurityException) {
3985 Slog.w(LOG_TAG, debugMsg + " for disabled profile "
3986 + targetUserId + " from " + callingUserId);
3987 }
3988 return false;
3989 }
3990
3991 if (targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID ||
3992 targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
3993 if (throwSecurityException) {
3994 throw new SecurityException(
3995 debugMsg + " for unrelated profile " + targetUserId);
3996 }
3997 return false;
3998 }
3999 }
4000 return true;
4001 }
4002
4003 @Override
4004 public int getProfileParentId(int userId) {
4005 synchronized (mUsersLock) {
4006 UserInfo profileParent = getProfileParentLU(userId);
4007 if (profileParent == null) {
4008 return userId;
4009 }
4010 return profileParent.id;
4011 }
4012 }
yuemingw1d13eae2018-01-30 17:27:54 +00004013
4014 @Override
4015 public boolean isSettingRestrictedForUser(String setting, @UserIdInt int userId,
4016 String value, int callingUid) {
4017 return UserRestrictionsUtils.isSettingRestrictedForUser(mContext, setting, userId,
4018 value, callingUid);
4019 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01004020 }
4021
4022 /* Remove all the users except of the system one. */
4023 private void removeNonSystemUsers() {
4024 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
4025 synchronized (mUsersLock) {
4026 final int userSize = mUsers.size();
4027 for (int i = 0; i < userSize; i++) {
4028 UserInfo ui = mUsers.valueAt(i).info;
4029 if (ui.id != UserHandle.USER_SYSTEM) {
4030 usersToRemove.add(ui);
4031 }
4032 }
4033 }
4034 for (UserInfo ui: usersToRemove) {
4035 removeUser(ui.id);
4036 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07004037 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07004038
4039 private class Shell extends ShellCommand {
4040 @Override
4041 public int onCommand(String cmd) {
4042 return onShellCommand(this, cmd);
4043 }
4044
4045 @Override
4046 public void onHelp() {
4047 final PrintWriter pw = getOutPrintWriter();
4048 pw.println("User manager (user) commands:");
4049 pw.println(" help");
4050 pw.println(" Print this help text.");
4051 pw.println("");
4052 pw.println(" list");
4053 pw.println(" Prints all users on the system.");
4054 }
4055 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08004056
4057 private static void debug(String message) {
4058 Log.d(LOG_TAG, message +
4059 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
4060 }
Kenny Guy02c89902016-11-15 19:36:38 +00004061
4062 @VisibleForTesting
4063 static int getMaxManagedProfiles() {
4064 // Allow overriding max managed profiles on debuggable builds for testing
4065 // of multiple profiles.
4066 if (!Build.IS_DEBUGGABLE) {
4067 return MAX_MANAGED_PROFILES;
4068 } else {
4069 return SystemProperties.getInt("persist.sys.max_profiles",
4070 MAX_MANAGED_PROFILES);
4071 }
4072 }
4073
Andreas Gampe2e8c7672018-07-20 13:01:08 -07004074 @GuardedBy("mUsersLock")
Kenny Guy02c89902016-11-15 19:36:38 +00004075 @VisibleForTesting
4076 int getFreeProfileBadgeLU(int parentUserId) {
4077 int maxManagedProfiles = getMaxManagedProfiles();
4078 boolean[] usedBadges = new boolean[maxManagedProfiles];
4079 final int userSize = mUsers.size();
4080 for (int i = 0; i < userSize; i++) {
4081 UserInfo ui = mUsers.valueAt(i).info;
4082 // Check which badge indexes are already used by this profile group.
4083 if (ui.isManagedProfile()
4084 && ui.profileGroupId == parentUserId
4085 && !mRemovingUserIds.get(ui.id)
4086 && ui.profileBadge < maxManagedProfiles) {
4087 usedBadges[ui.profileBadge] = true;
4088 }
4089 }
4090 for (int i = 0; i < maxManagedProfiles; i++) {
4091 if (!usedBadges[i]) {
4092 return i;
4093 }
4094 }
4095 return 0;
4096 }
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07004097
4098 /**
4099 * Checks if the given user has a managed profile associated with it.
4100 * @param userId The parent user
4101 * @return
4102 */
4103 boolean hasManagedProfile(int userId) {
4104 synchronized (mUsersLock) {
4105 UserInfo userInfo = getUserInfoLU(userId);
4106 final int userSize = mUsers.size();
4107 for (int i = 0; i < userSize; i++) {
4108 UserInfo profile = mUsers.valueAt(i).info;
4109 if (userId != profile.id && isProfileOf(userInfo, profile)) {
4110 return true;
4111 }
4112 }
4113 return false;
4114 }
4115 }
Tony Makd390ae92017-12-28 13:23:10 +00004116
4117 /**
4118 * Check if the calling package name matches with the calling UID, throw
4119 * {@link SecurityException} if not.
4120 */
4121 private void verifyCallingPackage(String callingPackage, int callingUid) {
4122 int packageUid = mPm.getPackageUid(callingPackage, 0, UserHandle.getUserId(callingUid));
4123 if (packageUid != callingUid) {
4124 throw new SecurityException("Specified package " + callingPackage
4125 + " does not match the calling uid " + callingUid);
4126 }
4127 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07004128}