blob: c6b09d190bff0c12eae7f74a49180694474d16db [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010034import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070035import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000036import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.content.Context;
38import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010039import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010040import android.content.IntentSender;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000041import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070042import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080043import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010045import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070046import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060048import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080049import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080050import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.os.Environment;
52import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080054import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070055import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080056import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010057import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070058import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080059import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070060import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070061import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010063import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070066import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070068import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080070import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010071import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070072import android.security.GateKeeper;
73import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070074import android.system.ErrnoException;
75import android.system.Os;
76import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070077import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070078import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070079import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070080import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Slog;
82import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080083import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000084import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070085import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import android.util.Xml;
87
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040090import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080091import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080092import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070093import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070094import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000095import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070096import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070097import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000098import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070099import com.android.server.storage.DeviceStorageMonitorInternal;
Jeff Sharkey47f71082016-02-01 17:03:54 -0700100import libcore.io.IoUtils;
101import libcore.util.Objects;
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;
113import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700114import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100115import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116import java.util.ArrayList;
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700117import java.util.LinkedList;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118import java.util.List;
119
Makoto Onuki068c54a2015-10-13 14:34:03 -0700120/**
121 * Service for {@link UserManager}.
122 *
123 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700124 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800125 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700126 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
127 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
128 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700129 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700130public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700131
Amith Yamasani2a003292012-08-14 18:25:45 -0700132 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800133 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800134 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700135 // Can be used for manual testing of id recycling
136 private static final boolean RELEASE_DELETED_USER_ID = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700137
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800139 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700140 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700141 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700143 private static final String ATTR_CREATION_TIME = "created";
144 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600145 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700146 private static final String ATTR_SERIAL_NO = "serialNumber";
147 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700148 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700149 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700150 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100151 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700152 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800153 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
154 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530155 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800158 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800159 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100160 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800161 private static final String TAG_ENTRY = "entry";
162 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800163 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800164 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700165 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800166 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700168 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
169 private static final String ATTR_TYPE_STRING = "s";
170 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700171 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700172 private static final String ATTR_TYPE_BUNDLE = "B";
173 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700174
Amith Yamasani0b285492011-04-14 17:35:23 -0700175 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700176 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700177 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100178 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800180 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700181 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800182
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700183 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
184 UserInfo.FLAG_MANAGED_PROFILE
185 | UserInfo.FLAG_EPHEMERAL
186 | UserInfo.FLAG_RESTRICTED
Sudheer Shanka234d1af2016-08-26 15:42:53 -0700187 | UserInfo.FLAG_GUEST
188 | UserInfo.FLAG_DEMO;
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700189
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700190 @VisibleForTesting
191 static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700192 // We need to keep process uid within Integer.MAX_VALUE.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700193 @VisibleForTesting
194 static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
195
196 // Max size of the queue of recently removed users
197 @VisibleForTesting
198 static final int MAX_RECENTLY_REMOVED_IDS_SIZE = 100;
Amith Yamasani634cf312012-10-04 17:34:21 -0700199
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700200 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700201
Amith Yamasani920ace02012-09-20 22:15:37 -0700202 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
203
Nicolas Prevotb8186812015-08-06 15:00:03 +0100204 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700205 // without first making sure that the rest of the framework is prepared for it.
206 private static final int MAX_MANAGED_PROFILES = 1;
207
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800208 static final int WRITE_USER_MSG = 1;
209 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530210
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700211 private static final String XATTR_SERIAL = "user.serial";
212
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800213 // Tron counters
214 private static final String TRON_GUEST_CREATED = "users_guest_created";
215 private static final String TRON_USER_CREATED = "users_user_created";
216
Dianne Hackborn4428e172012-08-24 17:43:05 -0700217 private final Context mContext;
218 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700219 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700220 // Short-term lock for internal state, when interaction/sync with PM is not required
221 private final Object mUsersLock = new Object();
222 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700223
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800224 private final Handler mHandler;
225
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700226 private final File mUsersDir;
227 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700228
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800229 private static final IBinder mUserRestriconToken = new Binder();
230
Makoto Onuki068c54a2015-10-13 14:34:03 -0700231 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800232 * User-related information that is used for persisting to flash. Only UserInfo is
233 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800234 */
Amith Yamasani12747872015-12-07 14:19:49 -0800235 private static class UserData {
236 // Basic user information and properties
237 UserInfo info;
238 // Account name used when there is a strong association between a user and an account
239 String account;
240 // Account information for seeding into a newly created user. This could also be
241 // used for login validation for an existing user, for updating their credentials.
242 // In the latter case, data may not need to be persisted as it is only valid for the
243 // current login session.
244 String seedAccountName;
245 String seedAccountType;
246 PersistableBundle seedAccountOptions;
247 // Whether to perist the seed account information to be available after a boot
248 boolean persistSeedData;
249
250 void clearSeedAccountData() {
251 seedAccountName = null;
252 seedAccountType = null;
253 seedAccountOptions = null;
254 persistSeedData = false;
255 }
256 }
257
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800258 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800259 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800260
261 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700262 * User restrictions set via UserManager. This doesn't include restrictions set by
263 * device owner / profile owners.
264 *
265 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
266 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
267 * maybe shared between {@link #mBaseUserRestrictions} and
268 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
269 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700270 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700271 */
272 @GuardedBy("mRestrictionsLock")
273 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
274
275 /**
276 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
277 * with device / profile owner restrictions. We'll initialize it lazily; use
278 * {@link #getEffectiveUserRestrictions} to access it.
279 *
280 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
281 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
282 * maybe shared between {@link #mBaseUserRestrictions} and
283 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
284 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700285 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700286 */
287 @GuardedBy("mRestrictionsLock")
288 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
289
Makoto Onuki4f160732015-10-27 17:15:38 -0700290 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800291 * User restrictions that have already been applied in
292 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
293 * that have changed since the last
294 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700295 */
296 @GuardedBy("mRestrictionsLock")
297 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
298
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800299 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800300 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
301 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800302 */
303 @GuardedBy("mRestrictionsLock")
304 private Bundle mDevicePolicyGlobalUserRestrictions;
305
306 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100307 * Id of the user that set global restrictions.
308 */
309 @GuardedBy("mRestrictionsLock")
310 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
311
312 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800313 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
314 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800315 */
316 @GuardedBy("mRestrictionsLock")
317 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
318
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800319 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530320 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800321
322 /**
323 * Set of user IDs being actively removed. Removed IDs linger in this set
324 * for several seconds to work around a VFS caching issue.
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700325 * Use {@link #addRemovingUserIdLocked(int)} to add elements to this array
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800326 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700327 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800328 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700329
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700330 /**
331 * Queue of recently removed userIds. Used for recycling of userIds
332 */
333 @GuardedBy("mUsersLock")
334 private final LinkedList<Integer> mRecentlyRemovedIds = new LinkedList<>();
335
Fyodor Kupolov82402752015-10-28 14:54:51 -0700336 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700337 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800338 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700339 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700340 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700341
Jason Monk62062992014-05-06 09:55:28 -0400342 private IAppOpsService mAppOpsService;
343
Makoto Onuki068c54a2015-10-13 14:34:03 -0700344 private final LocalService mLocalService;
345
Makoto Onukie7927da2015-11-25 10:05:17 -0800346 @GuardedBy("mUsersLock")
347 private boolean mIsDeviceManaged;
348
349 @GuardedBy("mUsersLock")
350 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
351
Makoto Onukid45a4a22015-11-02 17:17:38 -0800352 @GuardedBy("mUserRestrictionsListeners")
353 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
354 new ArrayList<>();
355
Clara Bayarria1771112015-12-18 16:29:18 +0000356 private final LockPatternUtils mLockPatternUtils;
357
Ricky Waib1dd80b2016-06-07 18:00:55 +0100358 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
359 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
360
361 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
362 @Override
363 public void onReceive(Context context, Intent intent) {
364 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
365 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
366 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
367 setQuietModeEnabled(userHandle, false);
368 if (target != null) {
369 try {
370 mContext.startIntentSender(target, null, 0, 0, 0);
371 } catch (IntentSender.SendIntentException e) {
372 /* ignore */
373 }
374 }
375 }
376 }
377 };
378
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100379 /**
380 * Whether all users should be created ephemeral.
381 */
382 @GuardedBy("mUsersLock")
383 private boolean mForceEphemeralUsers;
384
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000385 @GuardedBy("mUserStates")
386 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700387
Amith Yamasani258848d2012-08-10 17:06:33 -0700388 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700389
Dianne Hackborn4428e172012-08-24 17:43:05 -0700390 public static UserManagerService getInstance() {
391 synchronized (UserManagerService.class) {
392 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700393 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700394 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700395
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700396 public static class LifeCycle extends SystemService {
397
398 private UserManagerService mUms;
399
400 /**
401 * @param context
402 */
403 public LifeCycle(Context context) {
404 super(context);
405 }
406
407 @Override
408 public void onStart() {
409 mUms = UserManagerService.getInstance();
410 publishBinderService(Context.USER_SERVICE, mUms);
411 }
412
413 @Override
414 public void onBootPhase(int phase) {
415 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
416 mUms.cleanupPartialUsers();
417 }
418 }
419 }
420
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700421 // TODO b/28848102 Add support for test dependencies injection
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800422 @VisibleForTesting
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700423 UserManagerService(Context context) {
424 this(context, null, new Object(), context.getCacheDir());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700425 }
426
Dianne Hackborn4428e172012-08-24 17:43:05 -0700427 /**
428 * Called by package manager to create the service. This is closely
429 * associated with the package manager, and the given lock is the
430 * package manager's own lock.
431 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800432 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
433 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700434 }
435
Dianne Hackborn4428e172012-08-24 17:43:05 -0700436 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800437 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700438 mContext = context;
439 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700440 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800441 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800442 synchronized (mPackagesLock) {
443 mUsersDir = new File(dataDir, USER_INFO_DIR);
444 mUsersDir.mkdirs();
445 // Make zeroth user directory, for services to migrate their files to that location
446 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
447 userZeroDir.mkdirs();
448 FileUtils.setPermissions(mUsersDir.toString(),
449 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
450 -1, -1);
451 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
452 initDefaultGuestRestrictions();
453 readUserListLP();
454 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700455 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700456 mLocalService = new LocalService();
457 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000458 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000459 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700460 }
461
462 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400463 mAppOpsService = IAppOpsService.Stub.asInterface(
464 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800465
466 synchronized (mRestrictionsLock) {
467 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400468 }
Samuel Tand9453b82016-03-14 15:57:02 -0700469
470 UserInfo currentGuestUser = findCurrentGuestUser();
471 if (currentGuestUser != null && !hasUserRestriction(
472 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
473 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
474 // to it, in case this guest was created in a previous version where this
475 // user restriction was not a default guest restriction.
476 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
477 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700478
Ricky Waib1dd80b2016-06-07 18:00:55 +0100479 mContext.registerReceiver(mDisableQuietModeCallback,
480 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
481 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700482 }
483
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700484 void cleanupPartialUsers() {
485 // Prune out any partially created, partially removed and ephemeral users.
486 ArrayList<UserInfo> partials = new ArrayList<>();
487 synchronized (mUsersLock) {
488 final int userSize = mUsers.size();
489 for (int i = 0; i < userSize; i++) {
490 UserInfo ui = mUsers.valueAt(i).info;
491 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
492 partials.add(ui);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -0700493 addRemovingUserIdLocked(ui.id);
Amith Yamasaniae261892016-06-27 10:40:09 -0700494 ui.partial = true;
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700495 }
496 }
497 }
498 final int partialsSize = partials.size();
499 for (int i = 0; i < partialsSize; i++) {
500 UserInfo ui = partials.get(i);
501 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
502 + " (name=" + ui.name + ")");
503 removeUserState(ui.id);
504 }
505 }
506
Amith Yamasani258848d2012-08-10 17:06:33 -0700507 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800508 public String getUserAccount(int userId) {
509 checkManageUserAndAcrossUsersFullPermission("get user account");
510 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800511 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800512 }
513 }
514
515 @Override
516 public void setUserAccount(int userId, String accountName) {
517 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800518 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800519 synchronized (mPackagesLock) {
520 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800521 final UserData userData = mUsers.get(userId);
522 if (userData == null) {
523 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
524 return;
525 }
526 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800527 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800528 userData.account = accountName;
529 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800530 }
531 }
532
533 if (userToUpdate != null) {
534 writeUserLP(userToUpdate);
535 }
536 }
537 }
538
539 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700540 public UserInfo getPrimaryUser() {
541 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700542 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700543 final int userSize = mUsers.size();
544 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800545 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800546 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700547 return ui;
548 }
549 }
550 }
551 return null;
552 }
553
554 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700555 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700556 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700557 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700558 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700559 final int userSize = mUsers.size();
560 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800561 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700562 if (ui.partial) {
563 continue;
564 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800565 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700566 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700567 }
Amith Yamasani13593602012-03-22 16:16:17 -0700568 }
569 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700570 }
Amith Yamasani13593602012-03-22 16:16:17 -0700571 }
572
Amith Yamasani258848d2012-08-10 17:06:33 -0700573 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100574 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700575 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800576 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700577 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700578 } else {
579 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800580 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700581 final long ident = Binder.clearCallingIdentity();
582 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700583 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700584 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100585 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700586 } finally {
587 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000588 }
589 }
590
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700591 @Override
592 public int[] getProfileIds(int userId, boolean enabledOnly) {
593 if (userId != UserHandle.getCallingUserId()) {
594 checkManageUsersPermission("getting profiles related to user " + userId);
595 }
596 final long ident = Binder.clearCallingIdentity();
597 try {
598 synchronized (mUsersLock) {
599 return getProfileIdsLU(userId, enabledOnly).toArray();
600 }
601 } finally {
602 Binder.restoreCallingIdentity(ident);
603 }
604 }
605
Amith Yamasanibe465322014-04-24 13:45:17 -0700606 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700607 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700608 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
609 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
610 for (int i = 0; i < profileIds.size(); i++) {
611 int profileId = profileIds.get(i);
612 UserInfo userInfo = mUsers.get(profileId).info;
613 // If full info is not required - clear PII data to prevent 3P apps from reading it
614 if (!fullInfo) {
615 userInfo = new UserInfo(userInfo);
616 userInfo.name = null;
617 userInfo.iconPath = null;
618 } else {
619 userInfo = userWithName(userInfo);
620 }
621 users.add(userInfo);
622 }
623 return users;
624 }
625
626 /**
627 * Assume permissions already checked and caller's identity cleared
628 */
629 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700630 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700631 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700632 if (user == null) {
633 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700634 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700635 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700636 final int userSize = mUsers.size();
637 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800638 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700639 if (!isProfileOf(user, profile)) {
640 continue;
641 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100642 if (enabledOnly && !profile.isEnabled()) {
643 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700644 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700645 if (mRemovingUserIds.get(profile.id)) {
646 continue;
647 }
Tony Mak80189cd2016-04-05 17:21:42 +0100648 if (profile.partial) {
649 continue;
650 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700651 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700652 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700653 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700654 }
655
Jessica Hummelbe81c802014-04-22 15:49:22 +0100656 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700657 public int getCredentialOwnerProfile(int userHandle) {
658 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000659 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700660 synchronized (mUsersLock) {
661 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700662 if (profileParent != null) {
663 return profileParent.id;
664 }
665 }
666 }
667
668 return userHandle;
669 }
670
671 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700672 public boolean isSameProfileGroup(int userId, int otherUserId) {
673 if (userId == otherUserId) return true;
674 checkManageUsersPermission("check if in the same profile group");
675 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700676 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700677 }
678 }
679
Fyodor Kupolov82402752015-10-28 14:54:51 -0700680 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
681 synchronized (mUsersLock) {
682 UserInfo userInfo = getUserInfoLU(userId);
683 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
684 return false;
685 }
686 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
687 if (otherUserInfo == null
688 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
689 return false;
690 }
691 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700692 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700693 }
694
695 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100696 public UserInfo getProfileParent(int userHandle) {
697 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700698 synchronized (mUsersLock) {
699 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700700 }
701 }
702
Fyodor Kupolov82402752015-10-28 14:54:51 -0700703 private UserInfo getProfileParentLU(int userHandle) {
704 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700705 if (profile == null) {
706 return null;
707 }
708 int parentUserId = profile.profileGroupId;
709 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
710 return null;
711 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700712 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100713 }
714 }
715
Fyodor Kupolov82402752015-10-28 14:54:51 -0700716 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100717 return user.id == profile.id ||
718 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
719 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000720 }
721
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000722 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000723 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100724 Intent intent = new Intent();
725 if (inQuietMode) {
726 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
727 } else {
728 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
729 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000730 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
731 intent.putExtra(Intent.EXTRA_USER, profileHandle);
732 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000733 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000734 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000735 }
736
737 @Override
738 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
739 checkManageUsersPermission("silence profile");
740 boolean changed = false;
741 UserInfo profile, parent;
742 synchronized (mPackagesLock) {
743 synchronized (mUsersLock) {
744 profile = getUserInfoLU(userHandle);
745 parent = getProfileParentLU(userHandle);
746
747 }
748 if (profile == null || !profile.isManagedProfile()) {
749 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
750 }
751 if (profile.isQuietModeEnabled() != enableQuietMode) {
752 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800753 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000754 changed = true;
755 }
756 }
757 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000758 long identity = Binder.clearCallingIdentity();
759 try {
760 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100761 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100762 LocalServices.getService(ActivityManagerInternal.class)
763 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000764 } else {
765 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
766 }
767 } catch (RemoteException e) {
768 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
769 } finally {
770 Binder.restoreCallingIdentity(identity);
771 }
772
773 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
774 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000775 }
776 }
777
778 @Override
779 public boolean isQuietModeEnabled(int userHandle) {
780 synchronized (mPackagesLock) {
781 UserInfo info;
782 synchronized (mUsersLock) {
783 info = getUserInfoLU(userHandle);
784 }
785 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000786 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000787 }
788 return info.isQuietModeEnabled();
789 }
790 }
791
Kenny Guya52dc3e2014-02-11 15:33:14 +0000792 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100793 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100794 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600795 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100796 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100797 // if the user is already unlocked, no need to show a profile challenge
798 setQuietModeEnabled(userHandle, false);
799 return true;
800 }
801
802 long identity = Binder.clearCallingIdentity();
803 try {
804 // otherwise, we show a profile challenge to trigger decryption of the user
805 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
806 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100807 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
808 // lock, confirm screenlock page will know and show personal challenge, and unlock
809 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100810 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
811 userHandle);
812 if (unlockIntent == null) {
813 return false;
814 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100815 final Intent callBackIntent = new Intent(
816 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100817 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100818 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100819 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100820 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
821 callBackIntent.setPackage(mContext.getPackageName());
822 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
823 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
824 mContext,
825 0,
826 callBackIntent,
827 PendingIntent.FLAG_CANCEL_CURRENT |
828 PendingIntent.FLAG_ONE_SHOT |
829 PendingIntent.FLAG_IMMUTABLE);
830 // After unlocking the challenge, it will disable quiet mode and run the original
831 // intentSender
832 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100833 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
834 mContext.startActivity(unlockIntent);
835 } finally {
836 Binder.restoreCallingIdentity(identity);
837 }
838 return false;
839 }
840
841 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100842 public void setUserEnabled(int userId) {
843 checkManageUsersPermission("enable user");
844 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700845 UserInfo info;
846 synchronized (mUsersLock) {
847 info = getUserInfoLU(userId);
848 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100849 if (info != null && !info.isEnabled()) {
850 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800851 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100852 }
853 }
854 }
855
856 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700857 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700858 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000859 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700860 return userWithName(getUserInfoLU(userId));
861 }
862 }
863
864 /**
865 * Returns a UserInfo object with the name filled in, for Owner, or the original
866 * if the name is already set.
867 */
868 private UserInfo userWithName(UserInfo orig) {
869 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
870 UserInfo withName = new UserInfo(orig);
871 withName.name = getOwnerName();
872 return withName;
873 } else {
874 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000875 }
876 }
877
878 @Override
879 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000880 int callingUserId = UserHandle.getCallingUserId();
881 if (callingUserId != userId && !hasManageUsersPermission()) {
882 synchronized (mPackagesLock) {
883 if (!isSameProfileGroupLP(callingUserId, userId)) {
884 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000885 "You need MANAGE_USERS permission to: check if specified user a " +
886 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000887 }
888 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000889 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700890 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700891 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000892 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700893 }
894 }
895
Amith Yamasani71e6c692013-03-24 17:39:28 -0700896 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700897 public boolean isDemoUser(int userId) {
898 int callingUserId = UserHandle.getCallingUserId();
899 if (callingUserId != userId && !hasManageUsersPermission()) {
900 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
901 + " is a demo user");
902 }
903 synchronized (mUsersLock) {
904 UserInfo userInfo = getUserInfoLU(userId);
905 return userInfo != null && userInfo.isDemo();
906 }
907 }
908
909 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700910 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700911 synchronized (mUsersLock) {
912 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700913 }
914 }
915
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700916 @Override
917 public boolean canHaveRestrictedProfile(int userId) {
918 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700919 synchronized (mUsersLock) {
920 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700921 if (userInfo == null || !userInfo.canHaveProfile()) {
922 return false;
923 }
924 if (!userInfo.isAdmin()) {
925 return false;
926 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800927 // restricted profile can be created if there is no DO set and the admin user has no PO;
928 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700929 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700930 }
931
Amith Yamasani195263742012-08-21 15:40:12 -0700932 /*
933 * Should be locked on mUsers before calling this.
934 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700935 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800936 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700937 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800938 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700939 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
940 return null;
941 }
Amith Yamasani12747872015-12-07 14:19:49 -0800942 return userData != null ? userData.info : null;
943 }
944
945 private UserData getUserDataLU(int userId) {
946 final UserData userData = mUsers.get(userId);
947 // If it is partial and not in the process of being removed, return as unknown user.
948 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
949 return null;
950 }
951 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700952 }
953
Fyodor Kupolov82402752015-10-28 14:54:51 -0700954 /**
955 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
956 * <p>No permissions checking or any addition checks are made</p>
957 */
958 private UserInfo getUserInfoNoChecks(int userId) {
959 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800960 final UserData userData = mUsers.get(userId);
961 return userData != null ? userData.info : null;
962 }
963 }
964
965 /**
966 * Obtains {@link #mUsersLock} and return UserData from mUsers.
967 * <p>No permissions checking or any addition checks are made</p>
968 */
969 private UserData getUserDataNoChecks(int userId) {
970 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700971 return mUsers.get(userId);
972 }
973 }
974
Amith Yamasani236b2b52015-08-18 14:32:14 -0700975 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700976 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700977 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700978 }
979
Amith Yamasani258848d2012-08-10 17:06:33 -0700980 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700981 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700982 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700983 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700984 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800985 UserData userData = getUserDataNoChecks(userId);
986 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700987 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
988 return;
989 }
Amith Yamasani12747872015-12-07 14:19:49 -0800990 if (name != null && !name.equals(userData.info.name)) {
991 userData.info.name = name;
992 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700993 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700994 }
995 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700996 if (changed) {
997 sendUserInfoChangedBroadcast(userId);
998 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700999 }
1000
Amith Yamasani258848d2012-08-10 17:06:33 -07001001 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001002 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001003 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001004 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1005 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1006 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001007 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001008 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001009 }
1010
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001011
1012
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001013 private void sendUserInfoChangedBroadcast(int userId) {
1014 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1015 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1016 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001017 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001018 }
1019
Amith Yamasani258848d2012-08-10 17:06:33 -07001020 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001021 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001022 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001023 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001024 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1025 if (targetUserInfo == null || targetUserInfo.partial) {
1026 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001027 return null;
1028 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001029
1030 final int callingUserId = UserHandle.getCallingUserId();
1031 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1032 final int targetGroupId = targetUserInfo.profileGroupId;
1033 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1034 && callingGroupId == targetGroupId);
1035 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001036 checkManageUsersPermission("get the icon of a user who is not related");
1037 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001038
1039 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001040 return null;
1041 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001042 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001043 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001044
1045 try {
1046 return ParcelFileDescriptor.open(
1047 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1048 } catch (FileNotFoundException e) {
1049 Log.e(LOG_TAG, "Couldn't find icon file", e);
1050 }
1051 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001052 }
1053
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001054 public void makeInitialized(int userId) {
1055 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001056 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001057 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001058 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001059 userData = mUsers.get(userId);
1060 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001061 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001062 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001063 }
Amith Yamasani12747872015-12-07 14:19:49 -08001064 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1065 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001066 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001067 }
1068 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001069 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001070 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001071 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001072 }
1073
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001074 /**
1075 * If default guest restrictions haven't been initialized yet, add the basic
1076 * restrictions.
1077 */
1078 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001079 synchronized (mGuestRestrictions) {
1080 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001081 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001082 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001083 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1084 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1085 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001086 }
1087 }
1088
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001089 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301090 public Bundle getDefaultGuestRestrictions() {
1091 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001092 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301093 return new Bundle(mGuestRestrictions);
1094 }
1095 }
1096
1097 @Override
1098 public void setDefaultGuestRestrictions(Bundle restrictions) {
1099 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001100 synchronized (mGuestRestrictions) {
1101 mGuestRestrictions.clear();
1102 mGuestRestrictions.putAll(restrictions);
1103 }
1104 synchronized (mPackagesLock) {
1105 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301106 }
1107 }
1108
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001109 /**
1110 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1111 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001112 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001113 @Nullable Bundle global) {
1114 Preconditions.checkNotNull(local);
1115 boolean globalChanged = false;
1116 boolean localChanged;
1117 synchronized (mRestrictionsLock) {
1118 if (global != null) {
1119 // Update global.
1120 globalChanged = !UserRestrictionsUtils.areEqual(
1121 mDevicePolicyGlobalUserRestrictions, global);
1122 if (globalChanged) {
1123 mDevicePolicyGlobalUserRestrictions = global;
1124 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001125 // Remember the global restriction owner userId to be able to make a distinction
1126 // in getUserRestrictionSource on who set local policies.
1127 mGlobalRestrictionOwnerUserId = userId;
1128 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001129 if (mGlobalRestrictionOwnerUserId == userId) {
1130 // When profile owner sets restrictions it passes null global bundle and we
1131 // reset global restriction owner userId.
1132 // This means this user used to have DO, but now the DO is gone and the user
1133 // instead has PO.
1134 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1135 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001136 }
1137 {
1138 // Update local.
1139 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1140 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1141 if (localChanged) {
1142 mDevicePolicyLocalUserRestrictions.put(userId, local);
1143 }
1144 }
1145 }
1146 if (DBG) {
1147 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1148 + " global=" + global + (globalChanged ? " (changed)" : "")
1149 + " local=" + local + (localChanged ? " (changed)" : "")
1150 );
1151 }
1152 // Don't call them within the mRestrictionsLock.
1153 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001154 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001155 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001156 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001157 if (globalChanged) {
1158 writeUserListLP();
1159 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001160 }
1161
1162 synchronized (mRestrictionsLock) {
1163 if (globalChanged) {
1164 applyUserRestrictionsForAllUsersLR();
1165 } else if (localChanged) {
1166 applyUserRestrictionsLR(userId);
1167 }
1168 }
1169 }
1170
Makoto Onuki068c54a2015-10-13 14:34:03 -07001171 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001172 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001173 final Bundle baseRestrictions =
1174 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1175 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1176 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001177
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001178 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1179 // Common case first.
1180 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001181 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001182 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1183 UserRestrictionsUtils.merge(effective, global);
1184 UserRestrictionsUtils.merge(effective, local);
1185
Makoto Onuki068c54a2015-10-13 14:34:03 -07001186 return effective;
1187 }
1188
1189 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001190 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001191 if (DBG) {
1192 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1193 }
1194 mCachedEffectiveUserRestrictions.remove(userId);
1195 }
1196
1197 private Bundle getEffectiveUserRestrictions(int userId) {
1198 synchronized (mRestrictionsLock) {
1199 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1200 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001201 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001202 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1203 }
1204 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001205 }
1206 }
1207
Makoto Onuki068c54a2015-10-13 14:34:03 -07001208 /** @return a specific user restriction that's in effect currently. */
1209 @Override
1210 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001211 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1212 return false;
1213 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001214 Bundle restrictions = getEffectiveUserRestrictions(userId);
1215 return restrictions != null && restrictions.getBoolean(restrictionKey);
1216 }
1217
1218 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001219 * @hide
1220 *
1221 * Returns who set a user restriction on a user.
1222 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1223 * @param restrictionKey the string key representing the restriction
1224 * @param userId the id of the user for whom to retrieve the restrictions.
1225 * @return The source of user restriction. Any combination of
1226 * {@link UserManager#RESTRICTION_NOT_SET},
1227 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1228 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1229 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1230 */
1231 @Override
1232 public int getUserRestrictionSource(String restrictionKey, int userId) {
1233 checkManageUsersPermission("getUserRestrictionSource");
1234 int result = UserManager.RESTRICTION_NOT_SET;
1235
1236 // Shortcut for the most common case
1237 if (!hasUserRestriction(restrictionKey, userId)) {
1238 return result;
1239 }
1240
1241 if (hasBaseUserRestriction(restrictionKey, userId)) {
1242 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1243 }
1244
1245 synchronized(mRestrictionsLock) {
1246 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1247 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1248 && localRestrictions.getBoolean(restrictionKey)) {
1249 // Local restrictions may have been set by device owner the userId of which is
1250 // stored in mGlobalRestrictionOwnerUserId.
1251 if (mGlobalRestrictionOwnerUserId == userId) {
1252 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1253 } else {
1254 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1255 }
1256 }
1257 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1258 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1259 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1260 }
1261 }
1262
1263 return result;
1264 }
1265
1266 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001267 * @return UserRestrictions that are in effect currently. This always returns a new
1268 * {@link Bundle}.
1269 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001270 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001271 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001272 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001273 }
1274
1275 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001276 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1277 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001278 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1279 return false;
1280 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001281 synchronized (mRestrictionsLock) {
1282 Bundle bundle = mBaseUserRestrictions.get(userId);
1283 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1284 }
1285 }
1286
1287 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001288 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001289 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001290 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1291 return;
1292 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001293 synchronized (mRestrictionsLock) {
1294 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1295 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001296 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1297 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001298 newRestrictions.putBoolean(key, value);
1299
Fyodor Kupolov82402752015-10-28 14:54:51 -07001300 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001301 }
1302 }
1303
Makoto Onuki068c54a2015-10-13 14:34:03 -07001304 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001305 * Optionally updating user restrictions, calculate the effective user restrictions and also
1306 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001307 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001308 * @param newRestrictions User restrictions to set.
1309 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001310 * @param userId target user ID.
1311 */
1312 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001313 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001314 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001315
1316 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1317 mAppliedUserRestrictions.get(userId));
1318
1319 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001320 if (newRestrictions != null) {
1321 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001322 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1323
1324 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001325 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1326 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001327
1328 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1329 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001330 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001331 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001332 }
1333
Fyodor Kupolov82402752015-10-28 14:54:51 -07001334 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001335
Makoto Onuki759a7632015-10-28 16:43:10 -07001336 mCachedEffectiveUserRestrictions.put(userId, effective);
1337
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001338 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001339 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001340 debug("Applying user restrictions: userId=" + userId
1341 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001342 }
1343
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001344 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001345 mHandler.post(new Runnable() {
1346 @Override
1347 public void run() {
1348 try {
1349 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1350 } catch (RemoteException e) {
1351 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1352 }
1353 }
1354 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001355 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001356
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001357 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001358
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001359 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001360 }
1361
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001362 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001363 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001364 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1365 // actually, but we still need some kind of synchronization otherwise we might end up
1366 // calling listeners out-of-order, thus "LR".
1367
1368 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1369 return;
1370 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001371
1372 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1373 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1374
1375 mHandler.post(new Runnable() {
1376 @Override
1377 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001378 UserRestrictionsUtils.applyUserRestrictions(
1379 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001380
Makoto Onukid45a4a22015-11-02 17:17:38 -08001381 final UserRestrictionsListener[] listeners;
1382 synchronized (mUserRestrictionsListeners) {
1383 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1384 mUserRestrictionsListeners.toArray(listeners);
1385 }
1386 for (int i = 0; i < listeners.length; i++) {
1387 listeners[i].onUserRestrictionsChanged(userId,
1388 newRestrictionsFinal, prevRestrictionsFinal);
1389 }
1390 }
1391 });
1392 }
1393
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001394 // Package private for the inner class.
1395 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001396 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001397 }
1398
1399 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001400 // Package private for the inner class.
1401 void applyUserRestrictionsForAllUsersLR() {
1402 if (DBG) {
1403 debug("applyUserRestrictionsForAllUsersLR");
1404 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001405 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001406 mCachedEffectiveUserRestrictions.clear();
1407
Makoto Onuki068c54a2015-10-13 14:34:03 -07001408 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1409 // it on a handler.
1410 final Runnable r = new Runnable() {
1411 @Override
1412 public void run() {
1413 // Then get the list of running users.
1414 final int[] runningUsers;
1415 try {
1416 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1417 } catch (RemoteException e) {
1418 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1419 return;
1420 }
1421 // Then re-calculate the effective restrictions and apply, only for running users.
1422 // It's okay if a new user has started after the getRunningUserIds() call,
1423 // because we'll do the same thing (re-calculate the restrictions and apply)
1424 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001425 synchronized (mRestrictionsLock) {
1426 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001427 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001428 }
1429 }
1430 }
1431 };
1432 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001433 }
1434
Amith Yamasani258848d2012-08-10 17:06:33 -07001435 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001436 * Check if we've hit the limit of how many users can be created.
1437 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001438 private boolean isUserLimitReached() {
1439 int count;
1440 synchronized (mUsersLock) {
1441 count = getAliveUsersExcludingGuestsCountLU();
1442 }
1443 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001444 }
1445
1446 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001447 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001448 checkManageUsersPermission("check if more managed profiles can be added.");
1449 if (ActivityManager.isLowRamDeviceStatic()) {
1450 return false;
1451 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001452 if (!mContext.getPackageManager().hasSystemFeature(
1453 PackageManager.FEATURE_MANAGED_USERS)) {
1454 return false;
1455 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001456 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001457 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1458 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1459 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001460 return false;
1461 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001462 synchronized(mUsersLock) {
1463 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001464 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001465 return false;
1466 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001467 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1468 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001469 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001470 return usersCountAfterRemoving == 1
1471 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001472 }
1473 }
1474
Fyodor Kupolov82402752015-10-28 14:54:51 -07001475 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001476 int aliveUserCount = 0;
1477 final int totalUserCount = mUsers.size();
1478 // Skip over users being removed
1479 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001480 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001481 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001482 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001483 aliveUserCount++;
1484 }
1485 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001486 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001487 }
1488
1489 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001490 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001491 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1492 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1493 * permissions can make certain calls to the UserManager.
1494 *
1495 * @param message used as message if SecurityException is thrown
1496 * @throws SecurityException if the caller does not have enough privilege.
1497 */
1498 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1499 final int uid = Binder.getCallingUid();
1500 if (uid != Process.SYSTEM_UID && uid != 0
1501 && ActivityManager.checkComponentPermission(
1502 Manifest.permission.MANAGE_USERS,
1503 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1504 && ActivityManager.checkComponentPermission(
1505 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1506 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1507 throw new SecurityException(
1508 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1509 + message);
1510 }
1511 }
1512
1513 /**
1514 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001515 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001516 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001517 *
1518 * @param message used as message if SecurityException is thrown
1519 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001520 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001521 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001522 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001523 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001524 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1525 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001526 }
1527
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001528 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001529 * Enforces that only the system UID or root's UID or apps that have the
1530 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1531 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1532 * can make certain calls to the UserManager.
1533 *
1534 * @param message used as message if SecurityException is thrown
1535 * @throws SecurityException if the caller is not system or root
1536 * @see #hasManageOrCreateUsersPermission()
1537 */
1538 private static final void checkManageOrCreateUsersPermission(String message) {
1539 if (!hasManageOrCreateUsersPermission()) {
1540 throw new SecurityException(
1541 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1542 }
1543 }
1544
1545 /**
1546 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1547 * to create user/profiles other than what is allowed for
1548 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1549 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1550 */
1551 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1552 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1553 if (!hasManageOrCreateUsersPermission()) {
1554 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1555 + "permission to create an user with flags: " + creationFlags);
1556 }
1557 } else if (!hasManageUsersPermission()) {
1558 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1559 + " with flags: " + creationFlags);
1560 }
1561 }
1562
1563 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001564 * @return whether the calling UID is system UID or root's UID or the calling app has the
1565 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1566 */
1567 private static final boolean hasManageUsersPermission() {
1568 final int callingUid = Binder.getCallingUid();
1569 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1570 || callingUid == Process.ROOT_UID
1571 || ActivityManager.checkComponentPermission(
1572 android.Manifest.permission.MANAGE_USERS,
1573 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1574 }
1575
1576 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001577 * @return whether the calling UID is system UID or root's UID or the calling app has the
1578 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1579 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1580 */
1581 private static final boolean hasManageOrCreateUsersPermission() {
1582 final int callingUid = Binder.getCallingUid();
1583 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1584 || callingUid == Process.ROOT_UID
1585 || ActivityManager.checkComponentPermission(
1586 android.Manifest.permission.MANAGE_USERS,
1587 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1588 || ActivityManager.checkComponentPermission(
1589 android.Manifest.permission.CREATE_USERS,
1590 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1591 }
1592
1593 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001594 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1595 * UserManager.
1596 *
1597 * @param message used as message if SecurityException is thrown
1598 * @throws SecurityException if the caller is not system or root
1599 */
1600 private static void checkSystemOrRoot(String message) {
1601 final int uid = Binder.getCallingUid();
1602 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1603 throw new SecurityException("Only system may: " + message);
1604 }
1605 }
1606
Fyodor Kupolov82402752015-10-28 14:54:51 -07001607 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001608 try {
1609 File dir = new File(mUsersDir, Integer.toString(info.id));
1610 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001611 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001612 if (!dir.exists()) {
1613 dir.mkdir();
1614 FileUtils.setPermissions(
1615 dir.getPath(),
1616 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1617 -1, -1);
1618 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001619 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001620 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001621 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001622 info.iconPath = file.getAbsolutePath();
1623 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001624 try {
1625 os.close();
1626 } catch (IOException ioe) {
1627 // What the ... !
1628 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001629 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001630 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001631 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001632 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001633 }
1634
Amith Yamasani0b285492011-04-14 17:35:23 -07001635 /**
1636 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1637 * cache it elsewhere.
1638 * @return the array of user ids.
1639 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001640 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001641 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001642 return mUserIds;
1643 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001644 }
1645
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001646 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001647 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001648 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001649 return;
1650 }
1651 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001652 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001653 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001654 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001655 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001656 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001657 int type;
1658 while ((type = parser.next()) != XmlPullParser.START_TAG
1659 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001660 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001661 }
1662
1663 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001664 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001665 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001666 return;
1667 }
1668
Amith Yamasani2a003292012-08-14 18:25:45 -07001669 mNextSerialNumber = -1;
1670 if (parser.getName().equals(TAG_USERS)) {
1671 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1672 if (lastSerialNumber != null) {
1673 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1674 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001675 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1676 if (versionNumber != null) {
1677 mUserVersion = Integer.parseInt(versionNumber);
1678 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001679 }
1680
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1682
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001683 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301684 if (type == XmlPullParser.START_TAG) {
1685 final String name = parser.getName();
1686 if (name.equals(TAG_USER)) {
1687 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001688
Amith Yamasani12747872015-12-07 14:19:49 -08001689 UserData userData = readUserLP(Integer.parseInt(id));
1690
1691 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001692 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001693 mUsers.put(userData.info.id, userData);
1694 if (mNextSerialNumber < 0
1695 || mNextSerialNumber <= userData.info.id) {
1696 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001697 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301698 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001699 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301700 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001701 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1702 && type != XmlPullParser.END_TAG) {
1703 if (type == XmlPullParser.START_TAG) {
1704 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001705 synchronized (mGuestRestrictions) {
1706 UserRestrictionsUtils
1707 .readRestrictions(parser, mGuestRestrictions);
1708 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001709 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1710 ) {
1711 UserRestrictionsUtils.readRestrictions(parser,
1712 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001713 }
1714 break;
1715 }
1716 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001717 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1718 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1719 if (ownerUserId != null) {
1720 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1721 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001722 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001723 }
1724 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001725 synchronized (mRestrictionsLock) {
1726 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1727 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001728 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001729 upgradeIfNecessaryLP();
1730 } catch (IOException | XmlPullParserException e) {
1731 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001732 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001733 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001734 }
1735 }
1736
Amith Yamasani6f34b412012-10-22 18:19:27 -07001737 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001738 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001739 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001740 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001741 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001742 int userVersion = mUserVersion;
1743 if (userVersion < 1) {
1744 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001745 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1746 if ("Primary".equals(userData.info.name)) {
1747 userData.info.name =
1748 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1749 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001750 }
1751 userVersion = 1;
1752 }
1753
Amith Yamasanibc9625052012-11-15 14:39:18 -08001754 if (userVersion < 2) {
1755 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001756 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1757 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1758 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1759 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001760 }
1761 userVersion = 2;
1762 }
1763
Amith Yamasani350962c2013-08-06 11:18:53 -07001764
Amith Yamasani5e486f52013-08-07 11:06:44 -07001765 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001766 userVersion = 4;
1767 }
1768
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001769 if (userVersion < 5) {
1770 initDefaultGuestRestrictions();
1771 userVersion = 5;
1772 }
1773
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001774 if (userVersion < 6) {
1775 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001776 synchronized (mUsersLock) {
1777 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001778 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001779 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001780 if (!splitSystemUser && userData.info.isRestricted()
1781 && (userData.info.restrictedProfileParentId
1782 == UserInfo.NO_PROFILE_GROUP_ID)) {
1783 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1784 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001785 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001786 }
1787 }
1788 userVersion = 6;
1789 }
1790
Amith Yamasani6f34b412012-10-22 18:19:27 -07001791 if (userVersion < USER_VERSION) {
1792 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1793 + USER_VERSION);
1794 } else {
1795 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001796
1797 if (originalVersion < mUserVersion) {
1798 writeUserListLP();
1799 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001800 }
1801 }
1802
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001803 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001804 int flags = UserInfo.FLAG_INITIALIZED;
1805 // In split system user mode, the admin and primary flags are assigned to the first human
1806 // user.
1807 if (!UserManager.isSplitSystemUser()) {
1808 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1809 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001810 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001811 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001812 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001813 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001814 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001815
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001816 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001817 try {
1818 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1819 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1820 for (String userRestriction : defaultFirstUserRestrictions) {
1821 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1822 restrictions.putBoolean(userRestriction, true);
1823 }
1824 }
1825 } catch (Resources.NotFoundException e) {
1826 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1827 }
1828
Makoto Onuki068c54a2015-10-13 14:34:03 -07001829 synchronized (mRestrictionsLock) {
1830 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1831 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001832
Fyodor Kupolov82402752015-10-28 14:54:51 -07001833 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001834 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001835
Amith Yamasani12747872015-12-07 14:19:49 -08001836 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001837 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001838 }
1839
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001840 private String getOwnerName() {
1841 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1842 }
1843
Amith Yamasani12747872015-12-07 14:19:49 -08001844 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001845 if (DBG) {
1846 debug("scheduleWriteUser");
1847 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001848 // No need to wrap it within a lock -- worst case, we'll just post the same message
1849 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001850 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1851 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001852 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1853 }
1854 }
1855
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001856 /*
1857 * Writes the user file in this format:
1858 *
1859 * <user flags="20039023" id="0">
1860 * <name>Primary</name>
1861 * </user>
1862 */
Amith Yamasani12747872015-12-07 14:19:49 -08001863 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001864 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001865 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001866 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001867 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001868 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001869 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001870 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001871 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1872
1873 // XmlSerializer serializer = XmlUtils.serializerInstance();
1874 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001875 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001876 serializer.startDocument(null, true);
1877 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1878
Amith Yamasani12747872015-12-07 14:19:49 -08001879 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001880 serializer.startTag(null, TAG_USER);
1881 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001882 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001883 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001884 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1885 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1886 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001887 if (userInfo.lastLoggedInFingerprint != null) {
1888 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1889 userInfo.lastLoggedInFingerprint);
1890 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001891 if (userInfo.iconPath != null) {
1892 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1893 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001894 if (userInfo.partial) {
1895 serializer.attribute(null, ATTR_PARTIAL, "true");
1896 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001897 if (userInfo.guestToRemove) {
1898 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1899 }
Kenny Guy2a764942014-04-02 13:29:20 +01001900 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1901 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1902 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001903 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001904 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1905 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1906 Integer.toString(userInfo.restrictedProfileParentId));
1907 }
Amith Yamasani12747872015-12-07 14:19:49 -08001908 // Write seed data
1909 if (userData.persistSeedData) {
1910 if (userData.seedAccountName != null) {
1911 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1912 }
1913 if (userData.seedAccountType != null) {
1914 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1915 }
1916 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001917 if (userInfo.name != null) {
1918 serializer.startTag(null, TAG_NAME);
1919 serializer.text(userInfo.name);
1920 serializer.endTag(null, TAG_NAME);
1921 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001922 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001923 UserRestrictionsUtils.writeRestrictions(serializer,
1924 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1925 UserRestrictionsUtils.writeRestrictions(serializer,
1926 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1927 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001928 }
Amith Yamasani12747872015-12-07 14:19:49 -08001929
1930 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001931 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001932 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001933 serializer.endTag(null, TAG_ACCOUNT);
1934 }
1935
Amith Yamasani12747872015-12-07 14:19:49 -08001936 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1937 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1938 userData.seedAccountOptions.saveToXml(serializer);
1939 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1940 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001941 serializer.endTag(null, TAG_USER);
1942
1943 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001944 userFile.finishWrite(fos);
1945 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001946 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001947 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001948 }
1949 }
1950
1951 /*
1952 * Writes the user list file in this format:
1953 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001954 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001955 * <user id="0"></user>
1956 * <user id="2"></user>
1957 * </users>
1958 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001959 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001960 if (DBG) {
1961 debug("writeUserList");
1962 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001963 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001964 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001965 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001966 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001967 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1968
1969 // XmlSerializer serializer = XmlUtils.serializerInstance();
1970 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001971 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001972 serializer.startDocument(null, true);
1973 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1974
1975 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001976 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001977 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001978
Adam Lesinskieddeb492014-09-08 17:50:03 -07001979 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001980 synchronized (mGuestRestrictions) {
1981 UserRestrictionsUtils
1982 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1983 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301984 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001985 synchronized (mRestrictionsLock) {
1986 UserRestrictionsUtils.writeRestrictions(serializer,
1987 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1988 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001989 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1990 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1991 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001992 int[] userIdsToWrite;
1993 synchronized (mUsersLock) {
1994 userIdsToWrite = new int[mUsers.size()];
1995 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001996 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001997 userIdsToWrite[i] = user.id;
1998 }
1999 }
2000 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002001 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002002 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002003 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002004 }
2005
2006 serializer.endTag(null, TAG_USERS);
2007
2008 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002009 userListFile.finishWrite(fos);
2010 } catch (Exception e) {
2011 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002012 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002013 }
2014 }
2015
Amith Yamasani12747872015-12-07 14:19:49 -08002016 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002017 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002018 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002019 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002020 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002021 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002022 long creationTime = 0L;
2023 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002024 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002025 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002026 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002027 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002028 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002029 boolean persistSeedData = false;
2030 String seedAccountName = null;
2031 String seedAccountType = null;
2032 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002033 Bundle baseRestrictions = new Bundle();
2034 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002035
2036 FileInputStream fis = null;
2037 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002038 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002039 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002040 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002041 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002042 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002043 int type;
2044 while ((type = parser.next()) != XmlPullParser.START_TAG
2045 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002046 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002047 }
2048
2049 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002050 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002051 return null;
2052 }
2053
2054 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002055 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2056 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002057 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002058 return null;
2059 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002060 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2061 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002062 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002063 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2064 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002065 lastLoggedInFingerprint = parser.getAttributeValue(null,
2066 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002067 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2068 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002069 restrictedProfileParentId = readIntAttribute(parser,
2070 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002071 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2072 if ("true".equals(valueString)) {
2073 partial = true;
2074 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002075 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2076 if ("true".equals(valueString)) {
2077 guestToRemove = true;
2078 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002079
Amith Yamasani12747872015-12-07 14:19:49 -08002080 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2081 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2082 if (seedAccountName != null || seedAccountType != null) {
2083 persistSeedData = true;
2084 }
2085
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002086 int outerDepth = parser.getDepth();
2087 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2088 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2089 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2090 continue;
2091 }
2092 String tag = parser.getName();
2093 if (TAG_NAME.equals(tag)) {
2094 type = parser.next();
2095 if (type == XmlPullParser.TEXT) {
2096 name = parser.getText();
2097 }
2098 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002099 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2100 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2101 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002102 } else if (TAG_ACCOUNT.equals(tag)) {
2103 type = parser.next();
2104 if (type == XmlPullParser.TEXT) {
2105 account = parser.getText();
2106 }
Amith Yamasani12747872015-12-07 14:19:49 -08002107 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2108 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2109 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002110 }
2111 }
2112 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002113
Amith Yamasani12747872015-12-07 14:19:49 -08002114 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002115 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002116 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002117 userInfo.creationTime = creationTime;
2118 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002119 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002120 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002121 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002122 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002123 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002124
2125 // Create the UserData object that's internal to this class
2126 UserData userData = new UserData();
2127 userData.info = userInfo;
2128 userData.account = account;
2129 userData.seedAccountName = seedAccountName;
2130 userData.seedAccountType = seedAccountType;
2131 userData.persistSeedData = persistSeedData;
2132 userData.seedAccountOptions = seedAccountOptions;
2133
Makoto Onuki068c54a2015-10-13 14:34:03 -07002134 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002135 mBaseUserRestrictions.put(id, baseRestrictions);
2136 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002137 }
Amith Yamasani12747872015-12-07 14:19:49 -08002138 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002139 } catch (IOException ioe) {
2140 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002141 } finally {
2142 if (fis != null) {
2143 try {
2144 fis.close();
2145 } catch (IOException e) {
2146 }
2147 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002148 }
2149 return null;
2150 }
2151
Amith Yamasani920ace02012-09-20 22:15:37 -07002152 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2153 String valueString = parser.getAttributeValue(null, attr);
2154 if (valueString == null) return defaultValue;
2155 try {
2156 return Integer.parseInt(valueString);
2157 } catch (NumberFormatException nfe) {
2158 return defaultValue;
2159 }
2160 }
2161
2162 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2163 String valueString = parser.getAttributeValue(null, attr);
2164 if (valueString == null) return defaultValue;
2165 try {
2166 return Long.parseLong(valueString);
2167 } catch (NumberFormatException nfe) {
2168 return defaultValue;
2169 }
2170 }
2171
Amith Yamasanib82add22013-07-09 11:24:44 -07002172 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002173 * Removes the app restrictions file for a specific package and user id, if it exists.
2174 */
2175 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2176 synchronized (mPackagesLock) {
2177 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002178 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002179 if (resFile.exists()) {
2180 resFile.delete();
2181 }
2182 }
2183 }
2184
Kenny Guya52dc3e2014-02-11 15:33:14 +00002185 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002186 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002187 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002188 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002189 }
2190
Amith Yamasani258848d2012-08-10 17:06:33 -07002191 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002192 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002193 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002194 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002195 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002196
Jessica Hummelbe81c802014-04-22 15:49:22 +01002197 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002198 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002199 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2200 return null;
2201 }
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002202 DeviceStorageMonitorInternal dsm = LocalServices
2203 .getService(DeviceStorageMonitorInternal.class);
2204 if (dsm.isMemoryLow()) {
2205 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2206 return null;
2207 }
phweisse9c44062016-02-10 12:57:38 +01002208 return createUserInternalUnchecked(name, flags, parentId);
2209 }
2210
2211 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002212 if (ActivityManager.isLowRamDeviceStatic()) {
2213 return null;
2214 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002215 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002216 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002217 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002218 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002219 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002220 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002221 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002222 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002223 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002224 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002225 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002226 if (parentId != UserHandle.USER_NULL) {
2227 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002228 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002229 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002230 if (parent == null) return null;
2231 }
2232 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2233 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2234 return null;
2235 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002236 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2237 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002238 // been reached, cannot add a user.
2239 return null;
2240 }
2241 // If we're adding a guest and there already exists one, bail.
2242 if (isGuest && findCurrentGuestUser() != null) {
2243 return null;
2244 }
2245 // In legacy mode, restricted profile's parent can only be the owner user
2246 if (isRestricted && !UserManager.isSplitSystemUser()
2247 && (parentId != UserHandle.USER_SYSTEM)) {
2248 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2249 return null;
2250 }
2251 if (isRestricted && UserManager.isSplitSystemUser()) {
2252 if (parent == null) {
2253 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2254 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002255 return null;
2256 }
Amith Yamasani12747872015-12-07 14:19:49 -08002257 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002258 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2259 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002260 return null;
2261 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002262 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002263 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2264 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002265 Log.e(LOG_TAG,
2266 "Ephemeral users are supported on split-system-user systems only.");
2267 return null;
2268 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002269 // In split system user mode, we assign the first human user the primary flag.
2270 // And if there is no device owner, we also assign the admin flag to primary user.
2271 if (UserManager.isSplitSystemUser()
2272 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2273 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002274 synchronized (mUsersLock) {
2275 if (!mIsDeviceManaged) {
2276 flags |= UserInfo.FLAG_ADMIN;
2277 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002278 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002279 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002280
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002281 userId = getNextAvailableId();
2282 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002283 boolean ephemeralGuests = Resources.getSystem()
2284 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002285
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002286 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002287 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2288 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2289 || (parent != null && parent.info.isEphemeral())) {
2290 flags |= UserInfo.FLAG_EPHEMERAL;
2291 }
2292
2293 userInfo = new UserInfo(userId, name, null, flags);
2294 userInfo.serialNumber = mNextSerialNumber++;
2295 long now = System.currentTimeMillis();
2296 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2297 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002298 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002299 userData = new UserData();
2300 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002301 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002302 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002303 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002304 writeUserListLP();
2305 if (parent != null) {
2306 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002307 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2308 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002309 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002310 }
Amith Yamasani12747872015-12-07 14:19:49 -08002311 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002312 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002313 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2314 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002315 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002316 }
Amith Yamasani12747872015-12-07 14:19:49 -08002317 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002318 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002319 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002320 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002321 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002322 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002323 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002324 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002325 mPm.createNewUser(userId);
2326 userInfo.partial = false;
2327 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002328 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002329 }
2330 updateUserIds();
2331 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002332 if (isGuest) {
2333 synchronized (mGuestRestrictions) {
2334 restrictions.putAll(mGuestRestrictions);
2335 }
2336 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002337 synchronized (mRestrictionsLock) {
2338 mBaseUserRestrictions.append(userId, restrictions);
2339 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002340 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002341 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2342 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2343 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2344 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002345 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002346 } finally {
2347 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002348 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002349 return userInfo;
2350 }
2351
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002352 @VisibleForTesting
2353 UserData putUserInfo(UserInfo userInfo) {
2354 final UserData userData = new UserData();
2355 userData.info = userInfo;
2356 synchronized (mUsers) {
2357 mUsers.put(userInfo.id, userData);
2358 }
2359 return userData;
2360 }
2361
2362 @VisibleForTesting
2363 void removeUserInfo(int userId) {
2364 synchronized (mUsers) {
2365 mUsers.remove(userId);
2366 }
2367 }
2368
Amith Yamasani0b285492011-04-14 17:35:23 -07002369 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002370 * @hide
2371 */
Amith Yamasani12747872015-12-07 14:19:49 -08002372 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002373 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002374 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002375 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2376 if (user == null) {
2377 return null;
2378 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002379 long identity = Binder.clearCallingIdentity();
2380 try {
2381 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2382 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2383 // the putIntForUser() will fail.
2384 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2385 android.provider.Settings.Secure.LOCATION_MODE,
2386 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2387 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2388 } finally {
2389 Binder.restoreCallingIdentity(identity);
2390 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002391 return user;
2392 }
2393
2394 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002395 * Find the current guest user. If the Guest user is partial,
2396 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002397 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002398 private UserInfo findCurrentGuestUser() {
2399 synchronized (mUsersLock) {
2400 final int size = mUsers.size();
2401 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002402 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002403 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2404 return user;
2405 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002406 }
2407 }
2408 return null;
2409 }
2410
2411 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002412 * Mark this guest user for deletion to allow us to create another guest
2413 * and switch to that user before actually removing this guest.
2414 * @param userHandle the userid of the current guest
2415 * @return whether the user could be marked for deletion
2416 */
Amith Yamasani12747872015-12-07 14:19:49 -08002417 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002418 public boolean markGuestForDeletion(int userHandle) {
2419 checkManageUsersPermission("Only the system can remove users");
2420 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2421 UserManager.DISALLOW_REMOVE_USER, false)) {
2422 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2423 return false;
2424 }
2425
2426 long ident = Binder.clearCallingIdentity();
2427 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002428 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002429 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002430 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002431 userData = mUsers.get(userHandle);
2432 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002433 return false;
2434 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002435 }
Amith Yamasani12747872015-12-07 14:19:49 -08002436 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002437 return false;
2438 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002439 // We set this to a guest user that is to be removed. This is a temporary state
2440 // where we are allowed to add new Guest users, even if this one is still not
2441 // removed. This user will still show up in getUserInfo() calls.
2442 // If we don't get around to removing this Guest user, it will be purged on next
2443 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002444 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002445 // Mark it as disabled, so that it isn't returned any more when
2446 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002447 userData.info.flags |= UserInfo.FLAG_DISABLED;
2448 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002449 }
2450 } finally {
2451 Binder.restoreCallingIdentity(ident);
2452 }
2453 return true;
2454 }
2455
2456 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002457 * Removes a user and all data directories created for that user. This method should be called
2458 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002459 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002460 */
Amith Yamasani12747872015-12-07 14:19:49 -08002461 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002462 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002463 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002464 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2465 UserManager.DISALLOW_REMOVE_USER, false)) {
2466 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2467 return false;
2468 }
2469
Kenny Guyee58b4f2014-05-23 15:19:53 +01002470 long ident = Binder.clearCallingIdentity();
2471 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002472 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002473 int currentUser = ActivityManager.getCurrentUser();
2474 if (currentUser == userHandle) {
2475 Log.w(LOG_TAG, "Current user cannot be removed");
2476 return false;
2477 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002478 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002479 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002480 userData = mUsers.get(userHandle);
2481 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002482 return false;
2483 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002484
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002485 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002486 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002487
Kenny Guyee58b4f2014-05-23 15:19:53 +01002488 try {
2489 mAppOpsService.removeUser(userHandle);
2490 } catch (RemoteException e) {
2491 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2492 }
2493 // Set this to a partially created user, so that the user will be purged
2494 // on next startup, in case the runtime stops now before stopping and
2495 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002496 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002497 // Mark it as disabled, so that it isn't returned any more when
2498 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002499 userData.info.flags |= UserInfo.FLAG_DISABLED;
2500 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002501 }
2502
Amith Yamasani12747872015-12-07 14:19:49 -08002503 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2504 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002505 // Send broadcast to notify system that the user removed was a
2506 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002507 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002508 }
2509
2510 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2511 int res;
2512 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002513 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2514 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002515 @Override
2516 public void userStopped(int userId) {
2517 finishRemoveUser(userId);
2518 }
2519 @Override
2520 public void userStopAborted(int userId) {
2521 }
2522 });
2523 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002524 return false;
2525 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002526 return res == ActivityManager.USER_OP_SUCCESS;
2527 } finally {
2528 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002529 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002530 }
2531
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002532 @VisibleForTesting
2533 void addRemovingUserIdLocked(int userId) {
2534 // We remember deleted user IDs to prevent them from being
2535 // reused during the current boot; they can still be reused
2536 // after a reboot or recycling of userIds.
2537 mRemovingUserIds.put(userId, true);
2538 mRecentlyRemovedIds.add(userId);
2539 // Keep LRU queue of recently removed IDs for recycling
2540 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2541 mRecentlyRemovedIds.removeFirst();
2542 }
2543 }
2544
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002545 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002546 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002547 // Let other services shutdown any activity and clean up their state before completely
2548 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002549 long ident = Binder.clearCallingIdentity();
2550 try {
2551 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2552 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002553 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2554 android.Manifest.permission.MANAGE_USERS,
2555
2556 new BroadcastReceiver() {
2557 @Override
2558 public void onReceive(Context context, Intent intent) {
2559 if (DBG) {
2560 Slog.i(LOG_TAG,
2561 "USER_REMOVED broadcast sent, cleaning up user data "
2562 + userHandle);
2563 }
2564 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002565 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002566 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002567 // Clean up any ActivityManager state
2568 LocalServices.getService(ActivityManagerInternal.class)
2569 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002570 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002571 }
2572 }.start();
2573 }
2574 },
2575
2576 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002577 } finally {
2578 Binder.restoreCallingIdentity(ident);
2579 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002580 }
2581
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002582 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002583 try {
2584 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2585 } catch (IllegalStateException e) {
2586 // This may be simply because the user was partially created.
2587 Slog.i(LOG_TAG,
2588 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2589 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002590
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002591 // Cleanup gatekeeper secure user id
2592 try {
2593 final IGateKeeperService gk = GateKeeper.getService();
2594 if (gk != null) {
2595 gk.clearSecureUserId(userHandle);
2596 }
2597 } catch (Exception ex) {
2598 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2599 }
2600
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002601 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002602 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002603
2604 // Clean up all data before removing metadata
2605 mPm.destroyUserData(userHandle,
2606 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2607
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002608 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002609 synchronized (mUsersLock) {
2610 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002611 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002612 }
2613 synchronized (mUserStates) {
2614 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002615 }
2616 synchronized (mRestrictionsLock) {
2617 mBaseUserRestrictions.remove(userHandle);
2618 mAppliedUserRestrictions.remove(userHandle);
2619 mCachedEffectiveUserRestrictions.remove(userHandle);
2620 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002621 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002622 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002623 synchronized (mPackagesLock) {
2624 writeUserListLP();
2625 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002626 // Remove user file
2627 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2628 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002629 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002630 if (RELEASE_DELETED_USER_ID) {
2631 synchronized (mUsers) {
2632 mRemovingUserIds.delete(userHandle);
2633 }
2634 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002635 }
2636
Kenny Guyf8d3a232014-05-15 16:09:52 +01002637 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002638 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002639 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2640 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002641 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002642 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002643 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002644 }
2645
Amith Yamasani2a003292012-08-14 18:25:45 -07002646 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002647 public Bundle getApplicationRestrictions(String packageName) {
2648 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2649 }
2650
2651 @Override
2652 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002653 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002654 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002655 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002656 }
2657 synchronized (mPackagesLock) {
2658 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002659 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002660 }
2661 }
2662
2663 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002664 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002665 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002666 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002667 if (restrictions != null) {
2668 restrictions.setDefusable(true);
2669 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002670 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002671 if (restrictions == null || restrictions.isEmpty()) {
2672 cleanAppRestrictionsForPackage(packageName, userId);
2673 } else {
2674 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002675 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002676 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002677 }
Robin Lee66e5d962014-04-09 16:44:21 +01002678
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002679 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2680 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2681 changeIntent.setPackage(packageName);
2682 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2683 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002684 }
2685
2686 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002687 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002688 try {
2689 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002690 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002691 } catch (NameNotFoundException nnfe) {
2692 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002693 } finally {
2694 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002695 }
2696 }
2697
Fyodor Kupolov82402752015-10-28 14:54:51 -07002698 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002699 AtomicFile restrictionsFile =
2700 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2701 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002702 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002703 }
2704
2705 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002706 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002707 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002708 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002709 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002710 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002711 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002712
2713 FileInputStream fis = null;
2714 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002715 fis = restrictionsFile.openRead();
2716 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002717 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002718 XmlUtils.nextElement(parser);
2719 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002720 Slog.e(LOG_TAG, "Unable to read restrictions file "
2721 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002722 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002723 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002724 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2725 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002726 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002727 } catch (IOException|XmlPullParserException e) {
2728 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002729 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002730 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002731 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002732 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002733 }
2734
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002735 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2736 XmlPullParser parser) throws XmlPullParserException, IOException {
2737 int type = parser.getEventType();
2738 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2739 String key = parser.getAttributeValue(null, ATTR_KEY);
2740 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2741 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2742 if (multiple != null) {
2743 values.clear();
2744 int count = Integer.parseInt(multiple);
2745 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2746 if (type == XmlPullParser.START_TAG
2747 && parser.getName().equals(TAG_VALUE)) {
2748 values.add(parser.nextText().trim());
2749 count--;
2750 }
2751 }
2752 String [] valueStrings = new String[values.size()];
2753 values.toArray(valueStrings);
2754 restrictions.putStringArray(key, valueStrings);
2755 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2756 restrictions.putBundle(key, readBundleEntry(parser, values));
2757 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2758 final int outerDepth = parser.getDepth();
2759 ArrayList<Bundle> bundleList = new ArrayList<>();
2760 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2761 Bundle childBundle = readBundleEntry(parser, values);
2762 bundleList.add(childBundle);
2763 }
2764 restrictions.putParcelableArray(key,
2765 bundleList.toArray(new Bundle[bundleList.size()]));
2766 } else {
2767 String value = parser.nextText().trim();
2768 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2769 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2770 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2771 restrictions.putInt(key, Integer.parseInt(value));
2772 } else {
2773 restrictions.putString(key, value);
2774 }
2775 }
2776 }
2777 }
2778
2779 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2780 throws IOException, XmlPullParserException {
2781 Bundle childBundle = new Bundle();
2782 final int outerDepth = parser.getDepth();
2783 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2784 readEntry(childBundle, values, parser);
2785 }
2786 return childBundle;
2787 }
2788
Fyodor Kupolov82402752015-10-28 14:54:51 -07002789 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002790 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002791 AtomicFile restrictionsFile = new AtomicFile(
2792 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002793 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002794 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002795 }
2796
2797 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002798 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002799 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002800 try {
2801 fos = restrictionsFile.startWrite();
2802 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2803
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002804 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002805 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002806 serializer.startDocument(null, true);
2807 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2808
2809 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002810 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002811 serializer.endTag(null, TAG_RESTRICTIONS);
2812
2813 serializer.endDocument();
2814 restrictionsFile.finishWrite(fos);
2815 } catch (Exception e) {
2816 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002817 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2818 }
2819 }
2820
2821 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2822 throws IOException {
2823 for (String key : restrictions.keySet()) {
2824 Object value = restrictions.get(key);
2825 serializer.startTag(null, TAG_ENTRY);
2826 serializer.attribute(null, ATTR_KEY, key);
2827
2828 if (value instanceof Boolean) {
2829 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2830 serializer.text(value.toString());
2831 } else if (value instanceof Integer) {
2832 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2833 serializer.text(value.toString());
2834 } else if (value == null || value instanceof String) {
2835 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2836 serializer.text(value != null ? (String) value : "");
2837 } else if (value instanceof Bundle) {
2838 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2839 writeBundle((Bundle) value, serializer);
2840 } else if (value instanceof Parcelable[]) {
2841 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2842 Parcelable[] array = (Parcelable[]) value;
2843 for (Parcelable parcelable : array) {
2844 if (!(parcelable instanceof Bundle)) {
2845 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2846 }
2847 serializer.startTag(null, TAG_ENTRY);
2848 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2849 writeBundle((Bundle) parcelable, serializer);
2850 serializer.endTag(null, TAG_ENTRY);
2851 }
2852 } else {
2853 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2854 String[] values = (String[]) value;
2855 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2856 for (String choice : values) {
2857 serializer.startTag(null, TAG_VALUE);
2858 serializer.text(choice != null ? choice : "");
2859 serializer.endTag(null, TAG_VALUE);
2860 }
2861 }
2862 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002863 }
2864 }
2865
2866 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002867 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002868 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002869 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002870 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002871 }
2872 }
2873
2874 @Override
2875 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002876 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002877 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002878 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002879 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002880 }
2881 // Not found
2882 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002883 }
2884 }
2885
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002886 @Override
2887 public long getUserCreationTime(int userHandle) {
2888 int callingUserId = UserHandle.getCallingUserId();
2889 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002890 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002891 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002892 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002893 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002894 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002895 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002896 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002897 }
2898 }
2899 }
2900 if (userInfo == null) {
2901 throw new SecurityException("userHandle can only be the calling user or a managed "
2902 + "profile associated with this user");
2903 }
2904 return userInfo.creationTime;
2905 }
2906
Amith Yamasani0b285492011-04-14 17:35:23 -07002907 /**
2908 * Caches the list of user ids in an array, adjusting the array size when necessary.
2909 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002910 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002911 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002912 synchronized (mUsersLock) {
2913 final int userSize = mUsers.size();
2914 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002915 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002916 num++;
2917 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002918 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002919 final int[] newUsers = new int[num];
2920 int n = 0;
2921 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002922 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002923 newUsers[n++] = mUsers.keyAt(i);
2924 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002925 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002926 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002927 }
2928 }
2929
2930 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002931 * Called right before a user is started. This gives us a chance to prepare
2932 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002933 */
2934 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002935 UserInfo userInfo = getUserInfo(userId);
2936 if (userInfo == null) {
2937 return;
2938 }
2939 final int userSerial = userInfo.serialNumber;
2940 // Migrate only if build fingerprints mismatch
2941 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002942 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002943 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002944
2945 if (userId != UserHandle.USER_SYSTEM) {
2946 synchronized (mRestrictionsLock) {
2947 applyUserRestrictionsLR(userId);
2948 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002949 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002950
2951 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002952 }
2953
2954 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002955 * Called right before a user is unlocked. This gives us a chance to prepare
2956 * app storage.
2957 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002958 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002959 UserInfo userInfo = getUserInfo(userId);
2960 if (userInfo == null) {
2961 return;
2962 }
2963 final int userSerial = userInfo.serialNumber;
2964 // Migrate only if build fingerprints mismatch
2965 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002966 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002967 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002968 }
2969
2970 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002971 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002972 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002973 * @param userId the user that was just foregrounded
2974 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002975 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002976 UserData userData = getUserDataNoChecks(userId);
2977 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002978 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2979 return;
2980 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002981
2982 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002983 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002984 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002985 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002986 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2987 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002988 }
2989
Amith Yamasanieb437d42016-04-29 09:31:25 -07002990 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07002991 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07002992 String demoLauncher =
2993 mContext.getResources().getString(
2994 com.android.internal.R.string.config_demoModeLauncherComponent);
2995 if (!TextUtils.isEmpty(demoLauncher)) {
2996 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07002997 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00002998 try {
2999 final IPackageManager iPm = AppGlobals.getPackageManager();
3000 iPm.setComponentEnabledSetting(componentToEnable,
3001 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3002 /* userId= */ userId);
3003 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3004 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3005 /* userId= */ userId, null);
3006 } catch (RemoteException re) {
3007 // Internal, shouldn't happen
3008 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003009 }
3010 }
3011 }
3012
Amith Yamasani920ace02012-09-20 22:15:37 -07003013 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003014 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003015 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003016 @VisibleForTesting
3017 int getNextAvailableId() {
3018 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003019 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003020 nextId = scanNextAvailableIdLocked();
3021 if (nextId >= 0) {
3022 return nextId;
3023 }
3024 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3025 // except most recently removed
3026 if (mRemovingUserIds.size() > 0) {
3027 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3028 mRemovingUserIds.clear();
3029 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3030 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003031 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003032 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003033 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003034 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003035 if (nextId < 0) {
3036 throw new IllegalStateException("No user id available!");
3037 }
3038 return nextId;
3039 }
3040
3041 private int scanNextAvailableIdLocked() {
3042 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3043 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3044 return i;
3045 }
3046 }
3047 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003048 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003049
Amith Yamasanifc95e702013-09-26 13:20:17 -07003050 private String packageToRestrictionsFileName(String packageName) {
3051 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3052 }
3053
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003054 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003055 * Enforce that serial number stored in user directory inode matches the
3056 * given expected value. Gracefully sets the serial number if currently
3057 * undefined.
3058 *
3059 * @throws IOException when problem extracting serial number, or serial
3060 * number is mismatched.
3061 */
3062 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003063 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3064 // When we're emulating FBE, the directory may have been chmod
3065 // 000'ed, meaning we can't read the serial number to enforce it;
3066 // instead of destroying the user, just log a warning.
3067 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3068 return;
3069 }
3070
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003071 final int foundSerial = getSerialNumber(file);
3072 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3073
3074 if (foundSerial == -1) {
3075 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3076 try {
3077 setSerialNumber(file, serialNumber);
3078 } catch (IOException e) {
3079 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3080 }
3081
3082 } else if (foundSerial != serialNumber) {
3083 throw new IOException("Found serial number " + foundSerial
3084 + " doesn't match expected " + serialNumber);
3085 }
3086 }
3087
3088 /**
3089 * Set serial number stored in user directory inode.
3090 *
3091 * @throws IOException if serial number was already set
3092 */
3093 private static void setSerialNumber(File file, int serialNumber)
3094 throws IOException {
3095 try {
3096 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3097 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3098 } catch (ErrnoException e) {
3099 throw e.rethrowAsIOException();
3100 }
3101 }
3102
3103 /**
3104 * Return serial number stored in user directory inode.
3105 *
3106 * @return parsed serial number, or -1 if not set
3107 */
3108 private static int getSerialNumber(File file) throws IOException {
3109 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003110 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3111 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003112 try {
3113 return Integer.parseInt(serial);
3114 } catch (NumberFormatException e) {
3115 throw new IOException("Bad serial number: " + serial);
3116 }
3117 } catch (ErrnoException e) {
3118 if (e.errno == OsConstants.ENODATA) {
3119 return -1;
3120 } else {
3121 throw e.rethrowAsIOException();
3122 }
3123 }
3124 }
3125
Amith Yamasani920ace02012-09-20 22:15:37 -07003126 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003127 public void setSeedAccountData(int userId, String accountName, String accountType,
3128 PersistableBundle accountOptions, boolean persist) {
3129 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3130 synchronized (mPackagesLock) {
3131 final UserData userData;
3132 synchronized (mUsersLock) {
3133 userData = getUserDataLU(userId);
3134 if (userData == null) {
3135 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3136 return;
3137 }
3138 userData.seedAccountName = accountName;
3139 userData.seedAccountType = accountType;
3140 userData.seedAccountOptions = accountOptions;
3141 userData.persistSeedData = persist;
3142 }
3143 if (persist) {
3144 writeUserLP(userData);
3145 }
3146 }
3147 }
3148
3149 @Override
3150 public String getSeedAccountName() throws RemoteException {
3151 checkManageUsersPermission("Cannot get seed account information");
3152 synchronized (mUsersLock) {
3153 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3154 return userData.seedAccountName;
3155 }
3156 }
3157
3158 @Override
3159 public String getSeedAccountType() throws RemoteException {
3160 checkManageUsersPermission("Cannot get seed account information");
3161 synchronized (mUsersLock) {
3162 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3163 return userData.seedAccountType;
3164 }
3165 }
3166
3167 @Override
3168 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3169 checkManageUsersPermission("Cannot get seed account information");
3170 synchronized (mUsersLock) {
3171 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3172 return userData.seedAccountOptions;
3173 }
3174 }
3175
3176 @Override
3177 public void clearSeedAccountData() throws RemoteException {
3178 checkManageUsersPermission("Cannot clear seed account information");
3179 synchronized (mPackagesLock) {
3180 UserData userData;
3181 synchronized (mUsersLock) {
3182 userData = getUserDataLU(UserHandle.getCallingUserId());
3183 if (userData == null) return;
3184 userData.clearSeedAccountData();
3185 }
3186 writeUserLP(userData);
3187 }
3188 }
3189
3190 @Override
3191 public boolean someUserHasSeedAccount(String accountName, String accountType)
3192 throws RemoteException {
3193 checkManageUsersPermission("Cannot check seed account information");
3194 synchronized (mUsersLock) {
3195 final int userSize = mUsers.size();
3196 for (int i = 0; i < userSize; i++) {
3197 final UserData data = mUsers.valueAt(i);
3198 if (data.info.isInitialized()) continue;
3199 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3200 continue;
3201 }
3202 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3203 continue;
3204 }
3205 return true;
3206 }
3207 }
3208 return false;
3209 }
3210
3211 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003212 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003213 FileDescriptor err, String[] args, ShellCallback callback,
3214 ResultReceiver resultReceiver) {
3215 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003216 }
3217
3218 int onShellCommand(Shell shell, String cmd) {
3219 if (cmd == null) {
3220 return shell.handleDefaultCommands(cmd);
3221 }
3222
3223 final PrintWriter pw = shell.getOutPrintWriter();
3224 try {
3225 switch(cmd) {
3226 case "list":
3227 return runList(pw);
3228 }
3229 } catch (RemoteException e) {
3230 pw.println("Remote exception: " + e);
3231 }
3232 return -1;
3233 }
3234
3235 private int runList(PrintWriter pw) throws RemoteException {
3236 final IActivityManager am = ActivityManagerNative.getDefault();
3237 final List<UserInfo> users = getUsers(false);
3238 if (users == null) {
3239 pw.println("Error: couldn't get users");
3240 return 1;
3241 } else {
3242 pw.println("Users:");
3243 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003244 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003245 pw.println("\t" + users.get(i).toString() + running);
3246 }
3247 return 0;
3248 }
3249 }
3250
3251 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003252 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3253 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3254 != PackageManager.PERMISSION_GRANTED) {
3255 pw.println("Permission Denial: can't dump UserManager from from pid="
3256 + Binder.getCallingPid()
3257 + ", uid=" + Binder.getCallingUid()
3258 + " without permission "
3259 + android.Manifest.permission.DUMP);
3260 return;
3261 }
3262
3263 long now = System.currentTimeMillis();
3264 StringBuilder sb = new StringBuilder();
3265 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003266 synchronized (mUsersLock) {
3267 pw.println("Users:");
3268 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003269 UserData userData = mUsers.valueAt(i);
3270 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003271 continue;
3272 }
Amith Yamasani12747872015-12-07 14:19:49 -08003273 UserInfo userInfo = userData.info;
3274 final int userId = userInfo.id;
3275 pw.print(" "); pw.print(userInfo);
3276 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003277 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003278 pw.print(" <removing> ");
3279 }
Amith Yamasani12747872015-12-07 14:19:49 -08003280 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003281 pw.print(" <partial>");
3282 }
3283 pw.println();
3284 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003285 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003286 pw.println("<unknown>");
3287 } else {
3288 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003289 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003290 sb.append(" ago");
3291 pw.println(sb);
3292 }
3293 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003294 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003295 pw.println("<unknown>");
3296 } else {
3297 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003298 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003299 sb.append(" ago");
3300 pw.println(sb);
3301 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003302 pw.print(" Last logged in fingerprint: ");
3303 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003304 pw.print(" Has profile owner: ");
3305 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003306 pw.println(" Restrictions:");
3307 synchronized (mRestrictionsLock) {
3308 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003309 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003310 pw.println(" Device policy local restrictions:");
3311 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003312 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003313 pw.println(" Effective restrictions:");
3314 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003315 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003316 }
Amith Yamasani12747872015-12-07 14:19:49 -08003317
3318 if (userData.account != null) {
3319 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003320 pw.println();
3321 }
Amith Yamasani12747872015-12-07 14:19:49 -08003322
3323 if (userData.seedAccountName != null) {
3324 pw.print(" Seed account name: " + userData.seedAccountName);
3325 pw.println();
3326 if (userData.seedAccountType != null) {
3327 pw.print(" account type: " + userData.seedAccountType);
3328 pw.println();
3329 }
3330 if (userData.seedAccountOptions != null) {
3331 pw.print(" account options exist");
3332 pw.println();
3333 }
3334 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003335 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003336 }
Amith Yamasani12747872015-12-07 14:19:49 -08003337 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003338 pw.println(" Device policy global restrictions:");
3339 synchronized (mRestrictionsLock) {
3340 UserRestrictionsUtils
3341 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3342 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003343 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003344 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3345 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003346 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003347 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003348 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003349 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003350 synchronized (mUsersLock) {
3351 pw.println();
3352 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003353 if (mRemovingUserIds.size() > 0) {
3354 pw.println();
3355 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3356 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003357 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003358 synchronized (mUserStates) {
3359 pw.println(" Started users state: " + mUserStates);
3360 }
Amith Yamasani12747872015-12-07 14:19:49 -08003361 // Dump some capabilities
3362 pw.println();
3363 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3364 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003365 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3366 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003367 }
3368 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003369
3370 final class MainHandler extends Handler {
3371
3372 @Override
3373 public void handleMessage(Message msg) {
3374 switch (msg.what) {
3375 case WRITE_USER_MSG:
3376 removeMessages(WRITE_USER_MSG, msg.obj);
3377 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003378 int userId = ((UserData) msg.obj).info.id;
3379 UserData userData = getUserDataNoChecks(userId);
3380 if (userData != null) {
3381 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003382 }
3383 }
3384 }
3385 }
3386 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003387
3388 /**
3389 * @param userId
3390 * @return whether the user has been initialized yet
3391 */
3392 boolean isInitialized(int userId) {
3393 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3394 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003395
3396 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003397 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003398 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3399 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003400 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003401 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003402 }
3403
3404 @Override
3405 public Bundle getBaseUserRestrictions(int userId) {
3406 synchronized (mRestrictionsLock) {
3407 return mBaseUserRestrictions.get(userId);
3408 }
3409 }
3410
3411 @Override
3412 public void setBaseUserRestrictionsByDpmsForMigration(
3413 int userId, Bundle baseRestrictions) {
3414 synchronized (mRestrictionsLock) {
3415 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003416 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003417 }
3418
Amith Yamasani12747872015-12-07 14:19:49 -08003419 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003420 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003421 if (userData != null) {
3422 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003423 } else {
3424 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3425 }
3426 }
3427 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003428
3429 @Override
3430 public boolean getUserRestriction(int userId, String key) {
3431 return getUserRestrictions(userId).getBoolean(key);
3432 }
3433
3434 @Override
3435 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3436 synchronized (mUserRestrictionsListeners) {
3437 mUserRestrictionsListeners.add(listener);
3438 }
3439 }
3440
3441 @Override
3442 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3443 synchronized (mUserRestrictionsListeners) {
3444 mUserRestrictionsListeners.remove(listener);
3445 }
3446 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003447
3448 @Override
3449 public void setDeviceManaged(boolean isManaged) {
3450 synchronized (mUsersLock) {
3451 mIsDeviceManaged = isManaged;
3452 }
3453 }
3454
3455 @Override
3456 public void setUserManaged(int userId, boolean isManaged) {
3457 synchronized (mUsersLock) {
3458 mIsUserManaged.put(userId, isManaged);
3459 }
3460 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003461
3462 @Override
3463 public void setUserIcon(int userId, Bitmap bitmap) {
3464 long ident = Binder.clearCallingIdentity();
3465 try {
3466 synchronized (mPackagesLock) {
3467 UserData userData = getUserDataNoChecks(userId);
3468 if (userData == null || userData.info.partial) {
3469 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3470 return;
3471 }
3472 writeBitmapLP(userData.info, bitmap);
3473 writeUserLP(userData);
3474 }
3475 sendUserInfoChangedBroadcast(userId);
3476 } finally {
3477 Binder.restoreCallingIdentity(ident);
3478 }
3479 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003480
3481 @Override
3482 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3483 synchronized (mUsersLock) {
3484 mForceEphemeralUsers = forceEphemeralUsers;
3485 }
3486 }
3487
3488 @Override
3489 public void removeAllUsers() {
3490 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3491 // Remove the non-system users straight away.
3492 removeNonSystemUsers();
3493 } else {
3494 // Switch to the system user first and then remove the other users.
3495 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3496 @Override
3497 public void onReceive(Context context, Intent intent) {
3498 int userId =
3499 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3500 if (userId != UserHandle.USER_SYSTEM) {
3501 return;
3502 }
3503 mContext.unregisterReceiver(this);
3504 removeNonSystemUsers();
3505 }
3506 };
3507 IntentFilter userSwitchedFilter = new IntentFilter();
3508 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3509 mContext.registerReceiver(
3510 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3511
3512 // Switch to the system user.
3513 ActivityManager am =
3514 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3515 am.switchUser(UserHandle.USER_SYSTEM);
3516 }
3517 }
phweisse9c44062016-02-10 12:57:38 +01003518
3519 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003520 public void onEphemeralUserStop(int userId) {
3521 synchronized (mUsersLock) {
3522 UserInfo userInfo = getUserInfoLU(userId);
3523 if (userInfo != null && userInfo.isEphemeral()) {
3524 // Do not allow switching back to the ephemeral user again as the user is going
3525 // to be deleted.
3526 userInfo.flags |= UserInfo.FLAG_DISABLED;
3527 if (userInfo.isGuest()) {
3528 // Indicate that the guest will be deleted after it stops.
3529 userInfo.guestToRemove = true;
3530 }
3531 }
3532 }
3533 }
3534
3535 @Override
phweisse9c44062016-02-10 12:57:38 +01003536 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3537 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3538 // Keep this in sync with UserManager.createUser
3539 if (user != null && !user.isAdmin()) {
3540 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3541 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3542 }
3543 return user;
3544 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003545
3546 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003547 public boolean isUserRunning(int userId) {
3548 synchronized (mUserStates) {
3549 return mUserStates.get(userId, -1) >= 0;
3550 }
3551 }
3552
3553 @Override
3554 public void setUserState(int userId, int userState) {
3555 synchronized (mUserStates) {
3556 mUserStates.put(userId, userState);
3557 }
3558 }
3559
3560 @Override
3561 public void removeUserState(int userId) {
3562 synchronized (mUserStates) {
3563 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003564 }
3565 }
3566
3567 @Override
3568 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003569 synchronized (mUserStates) {
3570 int state = mUserStates.get(userId, -1);
3571 return (state == UserState.STATE_RUNNING_UNLOCKING)
3572 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003573 }
3574 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003575 }
3576
3577 /* Remove all the users except of the system one. */
3578 private void removeNonSystemUsers() {
3579 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3580 synchronized (mUsersLock) {
3581 final int userSize = mUsers.size();
3582 for (int i = 0; i < userSize; i++) {
3583 UserInfo ui = mUsers.valueAt(i).info;
3584 if (ui.id != UserHandle.USER_SYSTEM) {
3585 usersToRemove.add(ui);
3586 }
3587 }
3588 }
3589 for (UserInfo ui: usersToRemove) {
3590 removeUser(ui.id);
3591 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003592 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003593
3594 private class Shell extends ShellCommand {
3595 @Override
3596 public int onCommand(String cmd) {
3597 return onShellCommand(this, cmd);
3598 }
3599
3600 @Override
3601 public void onHelp() {
3602 final PrintWriter pw = getOutPrintWriter();
3603 pw.println("User manager (user) commands:");
3604 pw.println(" help");
3605 pw.println(" Print this help text.");
3606 pw.println("");
3607 pw.println(" list");
3608 pw.println(" Prints all users on the system.");
3609 }
3610 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003611
3612 private static void debug(String message) {
3613 Log.d(LOG_TAG, message +
3614 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3615 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003616}