blob: 5b47b6f1da0103a59759e85c425c29aaf1b8285f [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000029import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000035import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Sudheer Shanka38c67d32016-08-02 22:13:17 +000040import android.content.pm.IPackageManager;
Amith Yamasani0b285492011-04-14 17:35:23 -070041import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080042import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010044import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070045import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060047import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080048import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080049import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.os.Environment;
51import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080053import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080055import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010056import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070057import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080058import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070059import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070060import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070061import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010062import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Todd Kennedy60459ab2015-10-30 11:32:16 -070065import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070067import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080069import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010070import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070071import android.security.GateKeeper;
72import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070073import android.system.ErrnoException;
74import android.system.Os;
75import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070076import android.text.TextUtils;
Amith Yamasani2a003292012-08-14 18:25:45 -070077import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070078import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070079import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import android.util.Slog;
81import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080082import android.util.SparseBooleanArray;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000083import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070084import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import android.util.Xml;
86
Makoto Onuki068c54a2015-10-13 14:34:03 -070087import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070088import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040089import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080090import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080091import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070092import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070093import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000094import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070095import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070096import com.android.server.SystemService;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000097import com.android.server.am.UserState;
Suprabh Shuklac5e057c2016-08-08 16:22:44 -070098import com.android.server.storage.DeviceStorageMonitorInternal;
Tony Mak6dc428f2016-10-10 15:48:27 +010099
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()) {
bohu12d23a12016-09-26 16:20:07 -0700594 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700595 }
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");
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700675 return isSameProfileGroupNoChecks(userId, otherUserId);
676 }
677
678 private boolean isSameProfileGroupNoChecks(int userId, int otherUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700679 synchronized (mUsersLock) {
680 UserInfo userInfo = getUserInfoLU(userId);
681 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
682 return false;
683 }
684 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
685 if (otherUserInfo == null
686 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
687 return false;
688 }
689 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700690 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700691 }
692
693 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100694 public UserInfo getProfileParent(int userHandle) {
695 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700696 synchronized (mUsersLock) {
697 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700698 }
699 }
700
Fyodor Kupolov82402752015-10-28 14:54:51 -0700701 private UserInfo getProfileParentLU(int userHandle) {
702 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700703 if (profile == null) {
704 return null;
705 }
706 int parentUserId = profile.profileGroupId;
707 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
708 return null;
709 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700710 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100711 }
712 }
713
Fyodor Kupolov82402752015-10-28 14:54:51 -0700714 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100715 return user.id == profile.id ||
716 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
717 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000718 }
719
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000720 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000721 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100722 Intent intent = new Intent();
723 if (inQuietMode) {
724 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
725 } else {
726 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
727 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000728 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
729 intent.putExtra(Intent.EXTRA_USER, profileHandle);
730 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000731 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000732 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000733 }
734
735 @Override
736 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
737 checkManageUsersPermission("silence profile");
738 boolean changed = false;
739 UserInfo profile, parent;
740 synchronized (mPackagesLock) {
741 synchronized (mUsersLock) {
742 profile = getUserInfoLU(userHandle);
743 parent = getProfileParentLU(userHandle);
744
745 }
746 if (profile == null || !profile.isManagedProfile()) {
747 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
748 }
749 if (profile.isQuietModeEnabled() != enableQuietMode) {
750 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800751 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000752 changed = true;
753 }
754 }
755 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000756 long identity = Binder.clearCallingIdentity();
757 try {
758 if (enableQuietMode) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800759 ActivityManager.getService().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100760 LocalServices.getService(ActivityManagerInternal.class)
761 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000762 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800763 ActivityManager.getService().startUserInBackground(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000764 }
765 } catch (RemoteException e) {
766 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
767 } finally {
768 Binder.restoreCallingIdentity(identity);
769 }
770
771 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
772 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000773 }
774 }
775
776 @Override
777 public boolean isQuietModeEnabled(int userHandle) {
778 synchronized (mPackagesLock) {
779 UserInfo info;
780 synchronized (mUsersLock) {
781 info = getUserInfoLU(userHandle);
782 }
783 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000784 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000785 }
786 return info.isQuietModeEnabled();
787 }
788 }
789
Kenny Guya52dc3e2014-02-11 15:33:14 +0000790 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100791 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100792 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600793 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100794 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100795 // if the user is already unlocked, no need to show a profile challenge
796 setQuietModeEnabled(userHandle, false);
797 return true;
798 }
799
800 long identity = Binder.clearCallingIdentity();
801 try {
802 // otherwise, we show a profile challenge to trigger decryption of the user
803 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
804 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100805 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
806 // lock, confirm screenlock page will know and show personal challenge, and unlock
807 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100808 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
809 userHandle);
810 if (unlockIntent == null) {
811 return false;
812 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100813 final Intent callBackIntent = new Intent(
814 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100815 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100816 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100817 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100818 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
819 callBackIntent.setPackage(mContext.getPackageName());
820 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
821 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
822 mContext,
823 0,
824 callBackIntent,
825 PendingIntent.FLAG_CANCEL_CURRENT |
826 PendingIntent.FLAG_ONE_SHOT |
827 PendingIntent.FLAG_IMMUTABLE);
828 // After unlocking the challenge, it will disable quiet mode and run the original
829 // intentSender
830 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100831 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
832 mContext.startActivity(unlockIntent);
833 } finally {
834 Binder.restoreCallingIdentity(identity);
835 }
836 return false;
837 }
838
839 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100840 public void setUserEnabled(int userId) {
841 checkManageUsersPermission("enable user");
842 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700843 UserInfo info;
844 synchronized (mUsersLock) {
845 info = getUserInfoLU(userId);
846 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100847 if (info != null && !info.isEnabled()) {
848 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800849 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100850 }
851 }
852 }
853
854 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700855 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700856 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000857 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700858 return userWithName(getUserInfoLU(userId));
859 }
860 }
861
862 /**
863 * Returns a UserInfo object with the name filled in, for Owner, or the original
864 * if the name is already set.
865 */
866 private UserInfo userWithName(UserInfo orig) {
867 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
868 UserInfo withName = new UserInfo(orig);
869 withName.name = getOwnerName();
870 return withName;
871 } else {
872 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000873 }
874 }
875
876 @Override
877 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000878 int callingUserId = UserHandle.getCallingUserId();
879 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700880 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700881 throw new SecurityException(
882 "You need MANAGE_USERS permission to: check if specified user a " +
883 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000884 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000885 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700886 synchronized (mUsersLock) {
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700887 UserInfo userInfo = getUserInfoLU(userId);
Tony Mak8673b282016-03-21 21:10:59 +0000888 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700889 }
890 }
891
Amith Yamasani71e6c692013-03-24 17:39:28 -0700892 @Override
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700893 public boolean isUserUnlockingOrUnlocked(int userId) {
894 int callingUserId = UserHandle.getCallingUserId();
895 if (callingUserId != userId && !hasManageUsersPermission()) {
Fyodor Kupolov0fb772e2016-10-13 16:27:34 -0700896 if (!isSameProfileGroupNoChecks(callingUserId, userId)) {
Fyodor Kupolovc413f702016-10-06 17:11:14 -0700897 throw new SecurityException(
898 "You need MANAGE_USERS permission to: check isUserUnlockingOrUnlocked");
899 }
900 }
901 return mLocalService.isUserUnlockingOrUnlocked(userId);
902 }
903
904 @Override
Amith Yamasani1c41dc82016-06-28 16:13:15 -0700905 public boolean isDemoUser(int userId) {
906 int callingUserId = UserHandle.getCallingUserId();
907 if (callingUserId != userId && !hasManageUsersPermission()) {
908 throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
909 + " is a demo user");
910 }
911 synchronized (mUsersLock) {
912 UserInfo userInfo = getUserInfoLU(userId);
913 return userInfo != null && userInfo.isDemo();
914 }
915 }
916
917 @Override
Amith Yamasani71e6c692013-03-24 17:39:28 -0700918 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700919 synchronized (mUsersLock) {
920 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700921 }
922 }
923
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700924 @Override
925 public boolean canHaveRestrictedProfile(int userId) {
926 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700927 synchronized (mUsersLock) {
928 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700929 if (userInfo == null || !userInfo.canHaveProfile()) {
930 return false;
931 }
932 if (!userInfo.isAdmin()) {
933 return false;
934 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800935 // restricted profile can be created if there is no DO set and the admin user has no PO;
936 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700937 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700938 }
939
Amith Yamasani195263742012-08-21 15:40:12 -0700940 /*
941 * Should be locked on mUsers before calling this.
942 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700943 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800944 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700945 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800946 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700947 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
948 return null;
949 }
Amith Yamasani12747872015-12-07 14:19:49 -0800950 return userData != null ? userData.info : null;
951 }
952
953 private UserData getUserDataLU(int userId) {
954 final UserData userData = mUsers.get(userId);
955 // If it is partial and not in the process of being removed, return as unknown user.
956 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
957 return null;
958 }
959 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700960 }
961
Fyodor Kupolov82402752015-10-28 14:54:51 -0700962 /**
963 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
964 * <p>No permissions checking or any addition checks are made</p>
965 */
966 private UserInfo getUserInfoNoChecks(int userId) {
967 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800968 final UserData userData = mUsers.get(userId);
969 return userData != null ? userData.info : null;
970 }
971 }
972
973 /**
974 * Obtains {@link #mUsersLock} and return UserData from mUsers.
975 * <p>No permissions checking or any addition checks are made</p>
976 */
977 private UserData getUserDataNoChecks(int userId) {
978 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700979 return mUsers.get(userId);
980 }
981 }
982
Amith Yamasani236b2b52015-08-18 14:32:14 -0700983 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700984 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700985 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700986 }
987
Amith Yamasani258848d2012-08-10 17:06:33 -0700988 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700989 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700990 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700991 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700992 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800993 UserData userData = getUserDataNoChecks(userId);
994 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700995 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
996 return;
997 }
Amith Yamasani12747872015-12-07 14:19:49 -0800998 if (name != null && !name.equals(userData.info.name)) {
999 userData.info.name = name;
1000 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001001 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -07001002 }
1003 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001004 if (changed) {
1005 sendUserInfoChangedBroadcast(userId);
1006 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001007 }
1008
Amith Yamasani258848d2012-08-10 17:06:33 -07001009 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001010 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001011 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001012 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
1013 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
1014 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001015 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001016 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001017 }
1018
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01001019
1020
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001021 private void sendUserInfoChangedBroadcast(int userId) {
1022 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
1023 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1024 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -07001025 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001026 }
1027
Amith Yamasani258848d2012-08-10 17:06:33 -07001028 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001029 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +01001030 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001031 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001032 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
1033 if (targetUserInfo == null || targetUserInfo.partial) {
1034 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001035 return null;
1036 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001037
1038 final int callingUserId = UserHandle.getCallingUserId();
1039 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
1040 final int targetGroupId = targetUserInfo.profileGroupId;
1041 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
1042 && callingGroupId == targetGroupId);
1043 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +01001044 checkManageUsersPermission("get the icon of a user who is not related");
1045 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001046
1047 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001048 return null;
1049 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001050 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001051 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001052
1053 try {
1054 return ParcelFileDescriptor.open(
1055 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1056 } catch (FileNotFoundException e) {
1057 Log.e(LOG_TAG, "Couldn't find icon file", e);
1058 }
1059 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001060 }
1061
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001062 public void makeInitialized(int userId) {
1063 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001064 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001065 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001066 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001067 userData = mUsers.get(userId);
1068 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001069 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001070 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001071 }
Amith Yamasani12747872015-12-07 14:19:49 -08001072 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1073 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001074 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001075 }
1076 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001077 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001078 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001079 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001080 }
1081
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001082 /**
1083 * If default guest restrictions haven't been initialized yet, add the basic
1084 * restrictions.
1085 */
1086 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001087 synchronized (mGuestRestrictions) {
1088 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001089 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001090 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001091 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1092 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1093 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001094 }
1095 }
1096
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001097 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301098 public Bundle getDefaultGuestRestrictions() {
1099 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001100 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301101 return new Bundle(mGuestRestrictions);
1102 }
1103 }
1104
1105 @Override
1106 public void setDefaultGuestRestrictions(Bundle restrictions) {
1107 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001108 synchronized (mGuestRestrictions) {
1109 mGuestRestrictions.clear();
1110 mGuestRestrictions.putAll(restrictions);
1111 }
1112 synchronized (mPackagesLock) {
1113 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301114 }
1115 }
1116
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001117 /**
1118 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1119 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001120 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001121 @Nullable Bundle global) {
1122 Preconditions.checkNotNull(local);
1123 boolean globalChanged = false;
1124 boolean localChanged;
1125 synchronized (mRestrictionsLock) {
1126 if (global != null) {
1127 // Update global.
1128 globalChanged = !UserRestrictionsUtils.areEqual(
1129 mDevicePolicyGlobalUserRestrictions, global);
1130 if (globalChanged) {
1131 mDevicePolicyGlobalUserRestrictions = global;
1132 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001133 // Remember the global restriction owner userId to be able to make a distinction
1134 // in getUserRestrictionSource on who set local policies.
1135 mGlobalRestrictionOwnerUserId = userId;
1136 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001137 if (mGlobalRestrictionOwnerUserId == userId) {
1138 // When profile owner sets restrictions it passes null global bundle and we
1139 // reset global restriction owner userId.
1140 // This means this user used to have DO, but now the DO is gone and the user
1141 // instead has PO.
1142 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1143 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001144 }
1145 {
1146 // Update local.
1147 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1148 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1149 if (localChanged) {
1150 mDevicePolicyLocalUserRestrictions.put(userId, local);
1151 }
1152 }
1153 }
1154 if (DBG) {
1155 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1156 + " global=" + global + (globalChanged ? " (changed)" : "")
1157 + " local=" + local + (localChanged ? " (changed)" : "")
1158 );
1159 }
1160 // Don't call them within the mRestrictionsLock.
1161 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001162 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001163 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001164 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001165 if (globalChanged) {
1166 writeUserListLP();
1167 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001168 }
1169
1170 synchronized (mRestrictionsLock) {
1171 if (globalChanged) {
1172 applyUserRestrictionsForAllUsersLR();
1173 } else if (localChanged) {
1174 applyUserRestrictionsLR(userId);
1175 }
1176 }
1177 }
1178
Makoto Onuki068c54a2015-10-13 14:34:03 -07001179 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001180 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001181 final Bundle baseRestrictions =
1182 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1183 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1184 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001185
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001186 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1187 // Common case first.
1188 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001189 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001190 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1191 UserRestrictionsUtils.merge(effective, global);
1192 UserRestrictionsUtils.merge(effective, local);
1193
Makoto Onuki068c54a2015-10-13 14:34:03 -07001194 return effective;
1195 }
1196
1197 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001198 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001199 if (DBG) {
1200 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1201 }
1202 mCachedEffectiveUserRestrictions.remove(userId);
1203 }
1204
1205 private Bundle getEffectiveUserRestrictions(int userId) {
1206 synchronized (mRestrictionsLock) {
1207 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1208 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001209 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001210 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1211 }
1212 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001213 }
1214 }
1215
Makoto Onuki068c54a2015-10-13 14:34:03 -07001216 /** @return a specific user restriction that's in effect currently. */
1217 @Override
1218 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001219 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1220 return false;
1221 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001222 Bundle restrictions = getEffectiveUserRestrictions(userId);
1223 return restrictions != null && restrictions.getBoolean(restrictionKey);
1224 }
1225
1226 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001227 * @hide
1228 *
1229 * Returns who set a user restriction on a user.
1230 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1231 * @param restrictionKey the string key representing the restriction
1232 * @param userId the id of the user for whom to retrieve the restrictions.
1233 * @return The source of user restriction. Any combination of
1234 * {@link UserManager#RESTRICTION_NOT_SET},
1235 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1236 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1237 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1238 */
1239 @Override
1240 public int getUserRestrictionSource(String restrictionKey, int userId) {
1241 checkManageUsersPermission("getUserRestrictionSource");
1242 int result = UserManager.RESTRICTION_NOT_SET;
1243
1244 // Shortcut for the most common case
1245 if (!hasUserRestriction(restrictionKey, userId)) {
1246 return result;
1247 }
1248
1249 if (hasBaseUserRestriction(restrictionKey, userId)) {
1250 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1251 }
1252
1253 synchronized(mRestrictionsLock) {
1254 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1255 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1256 && localRestrictions.getBoolean(restrictionKey)) {
1257 // Local restrictions may have been set by device owner the userId of which is
1258 // stored in mGlobalRestrictionOwnerUserId.
1259 if (mGlobalRestrictionOwnerUserId == userId) {
1260 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1261 } else {
1262 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1263 }
1264 }
1265 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1266 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1267 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1268 }
1269 }
1270
1271 return result;
1272 }
1273
1274 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001275 * @return UserRestrictions that are in effect currently. This always returns a new
1276 * {@link Bundle}.
1277 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001278 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001279 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001280 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001281 }
1282
1283 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001284 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1285 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001286 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1287 return false;
1288 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001289 synchronized (mRestrictionsLock) {
1290 Bundle bundle = mBaseUserRestrictions.get(userId);
1291 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1292 }
1293 }
1294
1295 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001296 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001297 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001298 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1299 return;
1300 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001301 synchronized (mRestrictionsLock) {
1302 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1303 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001304 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1305 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001306 newRestrictions.putBoolean(key, value);
1307
Fyodor Kupolov82402752015-10-28 14:54:51 -07001308 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001309 }
1310 }
1311
Makoto Onuki068c54a2015-10-13 14:34:03 -07001312 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001313 * Optionally updating user restrictions, calculate the effective user restrictions and also
1314 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001315 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001316 * @param newRestrictions User restrictions to set.
1317 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001318 * @param userId target user ID.
1319 */
1320 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001321 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001322 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001323
1324 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1325 mAppliedUserRestrictions.get(userId));
1326
1327 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001328 if (newRestrictions != null) {
1329 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001330 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1331
1332 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001333 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1334 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001335
1336 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1337 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001338 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001339 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001340 }
1341
Fyodor Kupolov82402752015-10-28 14:54:51 -07001342 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001343
Makoto Onuki759a7632015-10-28 16:43:10 -07001344 mCachedEffectiveUserRestrictions.put(userId, effective);
1345
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001346 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001347 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001348 debug("Applying user restrictions: userId=" + userId
1349 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001350 }
1351
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001352 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001353 mHandler.post(new Runnable() {
1354 @Override
1355 public void run() {
1356 try {
1357 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1358 } catch (RemoteException e) {
1359 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1360 }
1361 }
1362 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001363 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001364
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001365 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001366
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001367 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001368 }
1369
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001370 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001371 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001372 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1373 // actually, but we still need some kind of synchronization otherwise we might end up
1374 // calling listeners out-of-order, thus "LR".
1375
1376 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1377 return;
1378 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001379
1380 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1381 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1382
1383 mHandler.post(new Runnable() {
1384 @Override
1385 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001386 UserRestrictionsUtils.applyUserRestrictions(
1387 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001388
Makoto Onukid45a4a22015-11-02 17:17:38 -08001389 final UserRestrictionsListener[] listeners;
1390 synchronized (mUserRestrictionsListeners) {
1391 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1392 mUserRestrictionsListeners.toArray(listeners);
1393 }
1394 for (int i = 0; i < listeners.length; i++) {
1395 listeners[i].onUserRestrictionsChanged(userId,
1396 newRestrictionsFinal, prevRestrictionsFinal);
1397 }
1398 }
1399 });
1400 }
1401
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001402 // Package private for the inner class.
1403 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001404 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001405 }
1406
1407 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001408 // Package private for the inner class.
1409 void applyUserRestrictionsForAllUsersLR() {
1410 if (DBG) {
1411 debug("applyUserRestrictionsForAllUsersLR");
1412 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001413 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001414 mCachedEffectiveUserRestrictions.clear();
1415
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001416 // We don't want to call into ActivityManagerService while taking a lock, so we'll call
Makoto Onuki068c54a2015-10-13 14:34:03 -07001417 // it on a handler.
1418 final Runnable r = new Runnable() {
1419 @Override
1420 public void run() {
1421 // Then get the list of running users.
1422 final int[] runningUsers;
1423 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001424 runningUsers = ActivityManager.getService().getRunningUserIds();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001425 } catch (RemoteException e) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001426 Log.w(LOG_TAG, "Unable to access ActivityManagerService");
Makoto Onuki068c54a2015-10-13 14:34:03 -07001427 return;
1428 }
1429 // Then re-calculate the effective restrictions and apply, only for running users.
1430 // It's okay if a new user has started after the getRunningUserIds() call,
1431 // because we'll do the same thing (re-calculate the restrictions and apply)
1432 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001433 synchronized (mRestrictionsLock) {
1434 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001435 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001436 }
1437 }
1438 }
1439 };
1440 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001441 }
1442
Amith Yamasani258848d2012-08-10 17:06:33 -07001443 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001444 * Check if we've hit the limit of how many users can be created.
1445 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001446 private boolean isUserLimitReached() {
1447 int count;
1448 synchronized (mUsersLock) {
1449 count = getAliveUsersExcludingGuestsCountLU();
1450 }
1451 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001452 }
1453
1454 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001455 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001456 checkManageUsersPermission("check if more managed profiles can be added.");
1457 if (ActivityManager.isLowRamDeviceStatic()) {
1458 return false;
1459 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001460 if (!mContext.getPackageManager().hasSystemFeature(
1461 PackageManager.FEATURE_MANAGED_USERS)) {
1462 return false;
1463 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001464 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001465 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1466 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1467 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001468 return false;
1469 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001470 synchronized(mUsersLock) {
1471 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001472 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001473 return false;
1474 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001475 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1476 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001477 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001478 return usersCountAfterRemoving == 1
1479 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001480 }
1481 }
1482
Fyodor Kupolov82402752015-10-28 14:54:51 -07001483 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001484 int aliveUserCount = 0;
1485 final int totalUserCount = mUsers.size();
1486 // Skip over users being removed
1487 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001488 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov6e99d3f2016-11-01 17:18:41 -07001489 if (!mRemovingUserIds.get(user.id) && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001490 aliveUserCount++;
1491 }
1492 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001493 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001494 }
1495
1496 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001497 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001498 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1499 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1500 * permissions can make certain calls to the UserManager.
1501 *
1502 * @param message used as message if SecurityException is thrown
1503 * @throws SecurityException if the caller does not have enough privilege.
1504 */
1505 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1506 final int uid = Binder.getCallingUid();
1507 if (uid != Process.SYSTEM_UID && uid != 0
1508 && ActivityManager.checkComponentPermission(
1509 Manifest.permission.MANAGE_USERS,
1510 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1511 && ActivityManager.checkComponentPermission(
1512 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1513 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1514 throw new SecurityException(
1515 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1516 + message);
1517 }
1518 }
1519
1520 /**
1521 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001522 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001523 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001524 *
1525 * @param message used as message if SecurityException is thrown
1526 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001527 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001528 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001529 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001530 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001531 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1532 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001533 }
1534
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001535 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001536 * Enforces that only the system UID or root's UID or apps that have the
1537 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1538 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1539 * can make certain calls to the UserManager.
1540 *
1541 * @param message used as message if SecurityException is thrown
1542 * @throws SecurityException if the caller is not system or root
1543 * @see #hasManageOrCreateUsersPermission()
1544 */
1545 private static final void checkManageOrCreateUsersPermission(String message) {
1546 if (!hasManageOrCreateUsersPermission()) {
1547 throw new SecurityException(
1548 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1549 }
1550 }
1551
1552 /**
1553 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1554 * to create user/profiles other than what is allowed for
1555 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1556 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1557 */
1558 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1559 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1560 if (!hasManageOrCreateUsersPermission()) {
1561 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1562 + "permission to create an user with flags: " + creationFlags);
1563 }
1564 } else if (!hasManageUsersPermission()) {
1565 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1566 + " with flags: " + creationFlags);
1567 }
1568 }
1569
1570 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001571 * @return whether the calling UID is system UID or root's UID or the calling app has the
1572 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1573 */
1574 private static final boolean hasManageUsersPermission() {
1575 final int callingUid = Binder.getCallingUid();
1576 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1577 || callingUid == Process.ROOT_UID
1578 || ActivityManager.checkComponentPermission(
1579 android.Manifest.permission.MANAGE_USERS,
1580 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1581 }
1582
1583 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001584 * @return whether the calling UID is system UID or root's UID or the calling app has the
1585 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1586 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1587 */
1588 private static final boolean hasManageOrCreateUsersPermission() {
1589 final int callingUid = Binder.getCallingUid();
1590 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1591 || callingUid == Process.ROOT_UID
1592 || ActivityManager.checkComponentPermission(
1593 android.Manifest.permission.MANAGE_USERS,
1594 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1595 || ActivityManager.checkComponentPermission(
1596 android.Manifest.permission.CREATE_USERS,
1597 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1598 }
1599
1600 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001601 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1602 * UserManager.
1603 *
1604 * @param message used as message if SecurityException is thrown
1605 * @throws SecurityException if the caller is not system or root
1606 */
1607 private static void checkSystemOrRoot(String message) {
1608 final int uid = Binder.getCallingUid();
1609 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1610 throw new SecurityException("Only system may: " + message);
1611 }
1612 }
1613
Fyodor Kupolov82402752015-10-28 14:54:51 -07001614 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001615 try {
1616 File dir = new File(mUsersDir, Integer.toString(info.id));
1617 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001618 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001619 if (!dir.exists()) {
1620 dir.mkdir();
1621 FileUtils.setPermissions(
1622 dir.getPath(),
1623 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1624 -1, -1);
1625 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001626 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001627 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001628 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001629 info.iconPath = file.getAbsolutePath();
1630 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001631 try {
1632 os.close();
1633 } catch (IOException ioe) {
1634 // What the ... !
1635 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001636 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001637 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001638 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001639 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001640 }
1641
Amith Yamasani0b285492011-04-14 17:35:23 -07001642 /**
1643 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1644 * cache it elsewhere.
1645 * @return the array of user ids.
1646 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001647 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001648 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001649 return mUserIds;
1650 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001651 }
1652
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001653 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001654 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001655 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656 return;
1657 }
1658 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001659 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001660 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001661 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001663 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001664 int type;
1665 while ((type = parser.next()) != XmlPullParser.START_TAG
1666 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001667 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001668 }
1669
1670 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001671 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001672 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001673 return;
1674 }
1675
Amith Yamasani2a003292012-08-14 18:25:45 -07001676 mNextSerialNumber = -1;
1677 if (parser.getName().equals(TAG_USERS)) {
1678 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1679 if (lastSerialNumber != null) {
1680 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1681 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001682 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1683 if (versionNumber != null) {
1684 mUserVersion = Integer.parseInt(versionNumber);
1685 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001686 }
1687
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001688 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1689
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001690 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301691 if (type == XmlPullParser.START_TAG) {
1692 final String name = parser.getName();
1693 if (name.equals(TAG_USER)) {
1694 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001695
Amith Yamasani12747872015-12-07 14:19:49 -08001696 UserData userData = readUserLP(Integer.parseInt(id));
1697
1698 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001699 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001700 mUsers.put(userData.info.id, userData);
1701 if (mNextSerialNumber < 0
1702 || mNextSerialNumber <= userData.info.id) {
1703 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001704 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301705 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001706 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301707 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001708 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1709 && type != XmlPullParser.END_TAG) {
1710 if (type == XmlPullParser.START_TAG) {
1711 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001712 synchronized (mGuestRestrictions) {
1713 UserRestrictionsUtils
1714 .readRestrictions(parser, mGuestRestrictions);
1715 }
Amith Yamasanida0b1682014-11-21 12:58:17 -08001716 }
1717 break;
1718 }
1719 }
Makoto Onuki82de3002016-09-30 09:58:15 -07001720 } else if (name.equals(TAG_DEVICE_POLICY_RESTRICTIONS)) {
1721 UserRestrictionsUtils.readRestrictions(parser,
1722 newDevicePolicyGlobalUserRestrictions);
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001723 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1724 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1725 if (ownerUserId != null) {
1726 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1727 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001728 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001729 }
1730 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001731 synchronized (mRestrictionsLock) {
1732 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1733 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001734 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001735 upgradeIfNecessaryLP();
1736 } catch (IOException | XmlPullParserException e) {
1737 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001738 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001739 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001740 }
1741 }
1742
Amith Yamasani6f34b412012-10-22 18:19:27 -07001743 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001744 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001745 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001746 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001747 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001748 int userVersion = mUserVersion;
1749 if (userVersion < 1) {
1750 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001751 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1752 if ("Primary".equals(userData.info.name)) {
1753 userData.info.name =
1754 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1755 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001756 }
1757 userVersion = 1;
1758 }
1759
Amith Yamasanibc9625052012-11-15 14:39:18 -08001760 if (userVersion < 2) {
1761 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001762 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1763 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1764 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1765 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001766 }
1767 userVersion = 2;
1768 }
1769
Amith Yamasani350962c2013-08-06 11:18:53 -07001770
Amith Yamasani5e486f52013-08-07 11:06:44 -07001771 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001772 userVersion = 4;
1773 }
1774
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001775 if (userVersion < 5) {
1776 initDefaultGuestRestrictions();
1777 userVersion = 5;
1778 }
1779
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001780 if (userVersion < 6) {
1781 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001782 synchronized (mUsersLock) {
1783 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001784 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001785 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001786 if (!splitSystemUser && userData.info.isRestricted()
1787 && (userData.info.restrictedProfileParentId
1788 == UserInfo.NO_PROFILE_GROUP_ID)) {
1789 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1790 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001791 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001792 }
1793 }
1794 userVersion = 6;
1795 }
1796
Amith Yamasani6f34b412012-10-22 18:19:27 -07001797 if (userVersion < USER_VERSION) {
1798 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1799 + USER_VERSION);
1800 } else {
1801 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001802
1803 if (originalVersion < mUserVersion) {
1804 writeUserListLP();
1805 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001806 }
1807 }
1808
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001809 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001810 int flags = UserInfo.FLAG_INITIALIZED;
1811 // In split system user mode, the admin and primary flags are assigned to the first human
1812 // user.
1813 if (!UserManager.isSplitSystemUser()) {
1814 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1815 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001816 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001817 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07001818 UserData userData = putUserInfo(system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001819 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001820 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001821
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001822 Bundle restrictions = new Bundle();
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01001823 try {
1824 final String[] defaultFirstUserRestrictions = mContext.getResources().getStringArray(
1825 com.android.internal.R.array.config_defaultFirstUserRestrictions);
1826 for (String userRestriction : defaultFirstUserRestrictions) {
1827 if (UserRestrictionsUtils.isValidRestriction(userRestriction)) {
1828 restrictions.putBoolean(userRestriction, true);
1829 }
1830 }
1831 } catch (Resources.NotFoundException e) {
1832 Log.e(LOG_TAG, "Couldn't find resource: config_defaultFirstUserRestrictions", e);
1833 }
1834
Makoto Onuki068c54a2015-10-13 14:34:03 -07001835 synchronized (mRestrictionsLock) {
1836 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1837 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001838
Fyodor Kupolov82402752015-10-28 14:54:51 -07001839 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001840 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001841
Amith Yamasani12747872015-12-07 14:19:49 -08001842 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001843 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001844 }
1845
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001846 private String getOwnerName() {
1847 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1848 }
1849
Amith Yamasani12747872015-12-07 14:19:49 -08001850 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001851 if (DBG) {
1852 debug("scheduleWriteUser");
1853 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001854 // No need to wrap it within a lock -- worst case, we'll just post the same message
1855 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001856 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1857 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001858 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1859 }
1860 }
1861
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001862 /*
1863 * Writes the user file in this format:
1864 *
1865 * <user flags="20039023" id="0">
1866 * <name>Primary</name>
1867 * </user>
1868 */
Amith Yamasani12747872015-12-07 14:19:49 -08001869 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001870 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001871 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001872 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001873 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001874 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001875 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001876 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001877 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1878
1879 // XmlSerializer serializer = XmlUtils.serializerInstance();
1880 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001881 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001882 serializer.startDocument(null, true);
1883 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1884
Amith Yamasani12747872015-12-07 14:19:49 -08001885 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001886 serializer.startTag(null, TAG_USER);
1887 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001888 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001889 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001890 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1891 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1892 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001893 if (userInfo.lastLoggedInFingerprint != null) {
1894 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1895 userInfo.lastLoggedInFingerprint);
1896 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001897 if (userInfo.iconPath != null) {
1898 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1899 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001900 if (userInfo.partial) {
1901 serializer.attribute(null, ATTR_PARTIAL, "true");
1902 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001903 if (userInfo.guestToRemove) {
1904 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1905 }
Kenny Guy2a764942014-04-02 13:29:20 +01001906 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1907 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1908 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001909 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001910 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1911 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1912 Integer.toString(userInfo.restrictedProfileParentId));
1913 }
Amith Yamasani12747872015-12-07 14:19:49 -08001914 // Write seed data
1915 if (userData.persistSeedData) {
1916 if (userData.seedAccountName != null) {
1917 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1918 }
1919 if (userData.seedAccountType != null) {
1920 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1921 }
1922 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001923 if (userInfo.name != null) {
1924 serializer.startTag(null, TAG_NAME);
1925 serializer.text(userInfo.name);
1926 serializer.endTag(null, TAG_NAME);
1927 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001928 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001929 UserRestrictionsUtils.writeRestrictions(serializer,
1930 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1931 UserRestrictionsUtils.writeRestrictions(serializer,
1932 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1933 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001934 }
Amith Yamasani12747872015-12-07 14:19:49 -08001935
1936 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001937 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001938 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001939 serializer.endTag(null, TAG_ACCOUNT);
1940 }
1941
Amith Yamasani12747872015-12-07 14:19:49 -08001942 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1943 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1944 userData.seedAccountOptions.saveToXml(serializer);
1945 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1946 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001947 serializer.endTag(null, TAG_USER);
1948
1949 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001950 userFile.finishWrite(fos);
1951 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001952 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001953 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001954 }
1955 }
1956
1957 /*
1958 * Writes the user list file in this format:
1959 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001960 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001961 * <user id="0"></user>
1962 * <user id="2"></user>
1963 * </users>
1964 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001965 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001966 if (DBG) {
1967 debug("writeUserList");
1968 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001969 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001970 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001971 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001972 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001973 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1974
1975 // XmlSerializer serializer = XmlUtils.serializerInstance();
1976 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001977 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001978 serializer.startDocument(null, true);
1979 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1980
1981 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001982 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001983 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001984
Adam Lesinskieddeb492014-09-08 17:50:03 -07001985 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001986 synchronized (mGuestRestrictions) {
1987 UserRestrictionsUtils
1988 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1989 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301990 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001991 synchronized (mRestrictionsLock) {
1992 UserRestrictionsUtils.writeRestrictions(serializer,
1993 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1994 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001995 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1996 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1997 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001998 int[] userIdsToWrite;
1999 synchronized (mUsersLock) {
2000 userIdsToWrite = new int[mUsers.size()];
2001 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002002 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002003 userIdsToWrite[i] = user.id;
2004 }
2005 }
2006 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002007 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002008 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002009 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002010 }
2011
2012 serializer.endTag(null, TAG_USERS);
2013
2014 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07002015 userListFile.finishWrite(fos);
2016 } catch (Exception e) {
2017 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07002018 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002019 }
2020 }
2021
Amith Yamasani12747872015-12-07 14:19:49 -08002022 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002023 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07002024 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002025 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002026 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002027 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07002028 long creationTime = 0L;
2029 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002030 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01002031 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002032 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002033 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002034 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08002035 boolean persistSeedData = false;
2036 String seedAccountName = null;
2037 String seedAccountType = null;
2038 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002039 Bundle baseRestrictions = new Bundle();
2040 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002041
2042 FileInputStream fis = null;
2043 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07002044 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07002045 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07002046 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002047 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002048 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002049 int type;
2050 while ((type = parser.next()) != XmlPullParser.START_TAG
2051 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08002052 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002053 }
2054
2055 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002056 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002057 return null;
2058 }
2059
2060 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002061 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2062 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002063 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002064 return null;
2065 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002066 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2067 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002068 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002069 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2070 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002071 lastLoggedInFingerprint = parser.getAttributeValue(null,
2072 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002073 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2074 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002075 restrictedProfileParentId = readIntAttribute(parser,
2076 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002077 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2078 if ("true".equals(valueString)) {
2079 partial = true;
2080 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002081 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2082 if ("true".equals(valueString)) {
2083 guestToRemove = true;
2084 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002085
Amith Yamasani12747872015-12-07 14:19:49 -08002086 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2087 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2088 if (seedAccountName != null || seedAccountType != null) {
2089 persistSeedData = true;
2090 }
2091
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002092 int outerDepth = parser.getDepth();
2093 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2094 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2095 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2096 continue;
2097 }
2098 String tag = parser.getName();
2099 if (TAG_NAME.equals(tag)) {
2100 type = parser.next();
2101 if (type == XmlPullParser.TEXT) {
2102 name = parser.getText();
2103 }
2104 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002105 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2106 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2107 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002108 } else if (TAG_ACCOUNT.equals(tag)) {
2109 type = parser.next();
2110 if (type == XmlPullParser.TEXT) {
2111 account = parser.getText();
2112 }
Amith Yamasani12747872015-12-07 14:19:49 -08002113 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2114 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2115 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002116 }
2117 }
2118 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002119
Amith Yamasani12747872015-12-07 14:19:49 -08002120 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002121 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002122 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002123 userInfo.creationTime = creationTime;
2124 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002125 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002126 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002127 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002128 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002129 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002130
2131 // Create the UserData object that's internal to this class
2132 UserData userData = new UserData();
2133 userData.info = userInfo;
2134 userData.account = account;
2135 userData.seedAccountName = seedAccountName;
2136 userData.seedAccountType = seedAccountType;
2137 userData.persistSeedData = persistSeedData;
2138 userData.seedAccountOptions = seedAccountOptions;
2139
Makoto Onuki068c54a2015-10-13 14:34:03 -07002140 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002141 mBaseUserRestrictions.put(id, baseRestrictions);
2142 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002143 }
Amith Yamasani12747872015-12-07 14:19:49 -08002144 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002145 } catch (IOException ioe) {
2146 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002147 } finally {
2148 if (fis != null) {
2149 try {
2150 fis.close();
2151 } catch (IOException e) {
2152 }
2153 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002154 }
2155 return null;
2156 }
2157
Amith Yamasani920ace02012-09-20 22:15:37 -07002158 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2159 String valueString = parser.getAttributeValue(null, attr);
2160 if (valueString == null) return defaultValue;
2161 try {
2162 return Integer.parseInt(valueString);
2163 } catch (NumberFormatException nfe) {
2164 return defaultValue;
2165 }
2166 }
2167
2168 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2169 String valueString = parser.getAttributeValue(null, attr);
2170 if (valueString == null) return defaultValue;
2171 try {
2172 return Long.parseLong(valueString);
2173 } catch (NumberFormatException nfe) {
2174 return defaultValue;
2175 }
2176 }
2177
Amith Yamasanib82add22013-07-09 11:24:44 -07002178 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002179 * Removes the app restrictions file for a specific package and user id, if it exists.
2180 */
2181 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2182 synchronized (mPackagesLock) {
2183 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002184 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002185 if (resFile.exists()) {
2186 resFile.delete();
2187 }
2188 }
2189 }
2190
Kenny Guya52dc3e2014-02-11 15:33:14 +00002191 @Override
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002192 public UserInfo createProfileForUser(String name, int flags, int userId,
2193 String[] disallowedPackages) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002194 checkManageOrCreateUsersPermission(flags);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002195 return createUserInternal(name, flags, userId, disallowedPackages);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002196 }
2197
Amith Yamasani258848d2012-08-10 17:06:33 -07002198 @Override
Tony Mak6dc428f2016-10-10 15:48:27 +01002199 public UserInfo createProfileForUserEvenWhenDisallowed(String name, int flags, int userId,
2200 String[] disallowedPackages) {
2201 checkManageOrCreateUsersPermission(flags);
2202 return createUserInternalUnchecked(name, flags, userId, disallowedPackages);
2203 }
2204
2205 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002206 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002207 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002208 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002209 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002210
Jessica Hummelbe81c802014-04-22 15:49:22 +01002211 private UserInfo createUserInternal(String name, int flags, int parentId) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002212 return createUserInternal(name, flags, parentId, null);
2213 }
2214
2215 private UserInfo createUserInternal(String name, int flags, int parentId,
2216 String[] disallowedPackages) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002217 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002218 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2219 return null;
2220 }
Tony Mak6dc428f2016-10-10 15:48:27 +01002221 return createUserInternalUnchecked(name, flags, parentId, disallowedPackages);
2222 }
2223
2224 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId,
2225 String[] disallowedPackages) {
Suprabh Shuklac5e057c2016-08-08 16:22:44 -07002226 DeviceStorageMonitorInternal dsm = LocalServices
2227 .getService(DeviceStorageMonitorInternal.class);
2228 if (dsm.isMemoryLow()) {
2229 Log.w(LOG_TAG, "Cannot add user. Not enough space on disk.");
2230 return null;
2231 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07002232 if (ActivityManager.isLowRamDeviceStatic()) {
2233 return null;
2234 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002235 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002236 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002237 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Amith Yamasani52c21e32016-05-31 09:12:20 -07002238 final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002239 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002240 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002241 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002242 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002243 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002244 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002245 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002246 if (parentId != UserHandle.USER_NULL) {
2247 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002248 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002249 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002250 if (parent == null) return null;
2251 }
2252 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2253 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2254 return null;
2255 }
Amith Yamasani52c21e32016-05-31 09:12:20 -07002256 if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
2257 // If we're not adding a guest/demo user or a managed profile and the limit has
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002258 // been reached, cannot add a user.
2259 return null;
2260 }
2261 // If we're adding a guest and there already exists one, bail.
2262 if (isGuest && findCurrentGuestUser() != null) {
2263 return null;
2264 }
2265 // In legacy mode, restricted profile's parent can only be the owner user
2266 if (isRestricted && !UserManager.isSplitSystemUser()
2267 && (parentId != UserHandle.USER_SYSTEM)) {
2268 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2269 return null;
2270 }
2271 if (isRestricted && UserManager.isSplitSystemUser()) {
2272 if (parent == null) {
2273 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2274 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002275 return null;
2276 }
Amith Yamasani12747872015-12-07 14:19:49 -08002277 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002278 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2279 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002280 return null;
2281 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002282 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002283 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2284 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002285 Log.e(LOG_TAG,
2286 "Ephemeral users are supported on split-system-user systems only.");
2287 return null;
2288 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002289 // In split system user mode, we assign the first human user the primary flag.
2290 // And if there is no device owner, we also assign the admin flag to primary user.
2291 if (UserManager.isSplitSystemUser()
2292 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2293 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002294 synchronized (mUsersLock) {
2295 if (!mIsDeviceManaged) {
2296 flags |= UserInfo.FLAG_ADMIN;
2297 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002298 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002299 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002300
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002301 userId = getNextAvailableId();
2302 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002303 boolean ephemeralGuests = Resources.getSystem()
2304 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002305
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002306 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002307 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2308 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2309 || (parent != null && parent.info.isEphemeral())) {
2310 flags |= UserInfo.FLAG_EPHEMERAL;
2311 }
2312
2313 userInfo = new UserInfo(userId, name, null, flags);
2314 userInfo.serialNumber = mNextSerialNumber++;
2315 long now = System.currentTimeMillis();
2316 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2317 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002318 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002319 userData = new UserData();
2320 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002321 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002322 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002323 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002324 writeUserListLP();
2325 if (parent != null) {
2326 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002327 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2328 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002329 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002330 }
Amith Yamasani12747872015-12-07 14:19:49 -08002331 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002332 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002333 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2334 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002335 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002336 }
Amith Yamasani12747872015-12-07 14:19:49 -08002337 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002338 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002339 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002340 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002341 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002342 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002343 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002344 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002345 mPm.createNewUser(userId, disallowedPackages);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002346 userInfo.partial = false;
2347 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002348 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002349 }
2350 updateUserIds();
2351 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002352 if (isGuest) {
2353 synchronized (mGuestRestrictions) {
2354 restrictions.putAll(mGuestRestrictions);
2355 }
2356 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002357 synchronized (mRestrictionsLock) {
2358 mBaseUserRestrictions.append(userId, restrictions);
2359 }
Fyodor Kupolov5fd967d2016-07-12 14:46:19 -07002360 mPm.onNewUserCreated(userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002361 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2362 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2363 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2364 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002365 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002366 } finally {
2367 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002368 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002369 return userInfo;
2370 }
2371
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002372 @VisibleForTesting
2373 UserData putUserInfo(UserInfo userInfo) {
2374 final UserData userData = new UserData();
2375 userData.info = userInfo;
2376 synchronized (mUsers) {
2377 mUsers.put(userInfo.id, userData);
2378 }
2379 return userData;
2380 }
2381
2382 @VisibleForTesting
2383 void removeUserInfo(int userId) {
2384 synchronized (mUsers) {
2385 mUsers.remove(userId);
2386 }
2387 }
2388
Amith Yamasani0b285492011-04-14 17:35:23 -07002389 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002390 * @hide
2391 */
Amith Yamasani12747872015-12-07 14:19:49 -08002392 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002393 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002394 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07002395 final UserInfo user = createProfileForUser(
2396 name, UserInfo.FLAG_RESTRICTED, parentUserId, null);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002397 if (user == null) {
2398 return null;
2399 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002400 long identity = Binder.clearCallingIdentity();
2401 try {
2402 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2403 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2404 // the putIntForUser() will fail.
2405 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2406 android.provider.Settings.Secure.LOCATION_MODE,
2407 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2408 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2409 } finally {
2410 Binder.restoreCallingIdentity(identity);
2411 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002412 return user;
2413 }
2414
2415 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002416 * Find the current guest user. If the Guest user is partial,
2417 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002418 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002419 private UserInfo findCurrentGuestUser() {
2420 synchronized (mUsersLock) {
2421 final int size = mUsers.size();
2422 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002423 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002424 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2425 return user;
2426 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002427 }
2428 }
2429 return null;
2430 }
2431
2432 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002433 * Mark this guest user for deletion to allow us to create another guest
2434 * and switch to that user before actually removing this guest.
2435 * @param userHandle the userid of the current guest
2436 * @return whether the user could be marked for deletion
2437 */
Amith Yamasani12747872015-12-07 14:19:49 -08002438 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002439 public boolean markGuestForDeletion(int userHandle) {
2440 checkManageUsersPermission("Only the system can remove users");
2441 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2442 UserManager.DISALLOW_REMOVE_USER, false)) {
2443 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2444 return false;
2445 }
2446
2447 long ident = Binder.clearCallingIdentity();
2448 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002449 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002450 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002451 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002452 userData = mUsers.get(userHandle);
2453 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002454 return false;
2455 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002456 }
Amith Yamasani12747872015-12-07 14:19:49 -08002457 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002458 return false;
2459 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002460 // We set this to a guest user that is to be removed. This is a temporary state
2461 // where we are allowed to add new Guest users, even if this one is still not
2462 // removed. This user will still show up in getUserInfo() calls.
2463 // If we don't get around to removing this Guest user, it will be purged on next
2464 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002465 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002466 // Mark it as disabled, so that it isn't returned any more when
2467 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002468 userData.info.flags |= UserInfo.FLAG_DISABLED;
2469 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002470 }
2471 } finally {
2472 Binder.restoreCallingIdentity(ident);
2473 }
2474 return true;
2475 }
2476
2477 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002478 * Removes a user and all data directories created for that user. This method should be called
2479 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002480 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002481 */
Amith Yamasani12747872015-12-07 14:19:49 -08002482 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002483 public boolean removeUser(int userHandle) {
Fyodor Kupolov4593e422016-10-27 11:00:29 -07002484 Slog.i(LOG_TAG, "removeUser u" + userHandle);
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002485 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002486 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2487 UserManager.DISALLOW_REMOVE_USER, false)) {
2488 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2489 return false;
2490 }
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002491 return removeUserUnchecked(userHandle);
2492 }
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002493
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01002494 private boolean removeUserUnchecked(int userHandle) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002495 long ident = Binder.clearCallingIdentity();
2496 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002497 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002498 int currentUser = ActivityManager.getCurrentUser();
2499 if (currentUser == userHandle) {
2500 Log.w(LOG_TAG, "Current user cannot be removed");
2501 return false;
2502 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002503 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002504 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002505 userData = mUsers.get(userHandle);
2506 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002507 return false;
2508 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002509
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002510 addRemovingUserIdLocked(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002511 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002512
Kenny Guyee58b4f2014-05-23 15:19:53 +01002513 try {
2514 mAppOpsService.removeUser(userHandle);
2515 } catch (RemoteException e) {
2516 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2517 }
2518 // Set this to a partially created user, so that the user will be purged
2519 // on next startup, in case the runtime stops now before stopping and
2520 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002521 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002522 // Mark it as disabled, so that it isn't returned any more when
2523 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002524 userData.info.flags |= UserInfo.FLAG_DISABLED;
2525 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002526 }
2527
Amith Yamasani12747872015-12-07 14:19:49 -08002528 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2529 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002530 // Send broadcast to notify system that the user removed was a
2531 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002532 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002533 }
2534
2535 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2536 int res;
2537 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002538 res = ActivityManager.getService().stopUser(userHandle, /* force= */ true,
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002539 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002540 @Override
2541 public void userStopped(int userId) {
2542 finishRemoveUser(userId);
2543 }
2544 @Override
2545 public void userStopAborted(int userId) {
2546 }
2547 });
2548 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002549 return false;
2550 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002551 return res == ActivityManager.USER_OP_SUCCESS;
2552 } finally {
2553 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002554 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002555 }
2556
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002557 @VisibleForTesting
2558 void addRemovingUserIdLocked(int userId) {
2559 // We remember deleted user IDs to prevent them from being
2560 // reused during the current boot; they can still be reused
2561 // after a reboot or recycling of userIds.
2562 mRemovingUserIds.put(userId, true);
2563 mRecentlyRemovedIds.add(userId);
2564 // Keep LRU queue of recently removed IDs for recycling
2565 if (mRecentlyRemovedIds.size() > MAX_RECENTLY_REMOVED_IDS_SIZE) {
2566 mRecentlyRemovedIds.removeFirst();
2567 }
2568 }
2569
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002570 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002571 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002572 // Let other services shutdown any activity and clean up their state before completely
2573 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002574 long ident = Binder.clearCallingIdentity();
2575 try {
2576 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2577 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002578 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2579 android.Manifest.permission.MANAGE_USERS,
2580
2581 new BroadcastReceiver() {
2582 @Override
2583 public void onReceive(Context context, Intent intent) {
2584 if (DBG) {
2585 Slog.i(LOG_TAG,
2586 "USER_REMOVED broadcast sent, cleaning up user data "
2587 + userHandle);
2588 }
2589 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002590 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002591 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002592 // Clean up any ActivityManager state
2593 LocalServices.getService(ActivityManagerInternal.class)
2594 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002595 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002596 }
2597 }.start();
2598 }
2599 },
2600
2601 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002602 } finally {
2603 Binder.restoreCallingIdentity(ident);
2604 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002605 }
2606
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002607 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002608 try {
2609 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2610 } catch (IllegalStateException e) {
2611 // This may be simply because the user was partially created.
2612 Slog.i(LOG_TAG,
2613 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2614 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002615
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002616 // Cleanup gatekeeper secure user id
2617 try {
2618 final IGateKeeperService gk = GateKeeper.getService();
2619 if (gk != null) {
2620 gk.clearSecureUserId(userHandle);
2621 }
2622 } catch (Exception ex) {
2623 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2624 }
2625
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002626 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002627 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002628
2629 // Clean up all data before removing metadata
2630 mPm.destroyUserData(userHandle,
2631 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2632
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002633 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002634 synchronized (mUsersLock) {
2635 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002636 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002637 }
2638 synchronized (mUserStates) {
2639 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002640 }
2641 synchronized (mRestrictionsLock) {
2642 mBaseUserRestrictions.remove(userHandle);
2643 mAppliedUserRestrictions.remove(userHandle);
2644 mCachedEffectiveUserRestrictions.remove(userHandle);
2645 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002646 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002647 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002648 synchronized (mPackagesLock) {
2649 writeUserListLP();
2650 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002651 // Remove user file
2652 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2653 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002654 updateUserIds();
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07002655 if (RELEASE_DELETED_USER_ID) {
2656 synchronized (mUsers) {
2657 mRemovingUserIds.delete(userHandle);
2658 }
2659 }
Amith Yamasani61f57372012-08-31 12:12:28 -07002660 }
2661
Kenny Guyf8d3a232014-05-15 16:09:52 +01002662 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002663 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002664 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2665 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002666 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002667 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002668 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002669 }
2670
Amith Yamasani2a003292012-08-14 18:25:45 -07002671 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002672 public Bundle getApplicationRestrictions(String packageName) {
2673 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2674 }
2675
2676 @Override
2677 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002678 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002679 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002680 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002681 }
2682 synchronized (mPackagesLock) {
2683 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002684 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002685 }
2686 }
2687
2688 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002689 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002690 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002691 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002692 if (restrictions != null) {
2693 restrictions.setDefusable(true);
2694 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002695 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002696 if (restrictions == null || restrictions.isEmpty()) {
2697 cleanAppRestrictionsForPackage(packageName, userId);
2698 } else {
2699 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002700 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002701 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002702 }
Robin Lee66e5d962014-04-09 16:44:21 +01002703
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002704 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2705 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2706 changeIntent.setPackage(packageName);
2707 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2708 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002709 }
2710
2711 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002712 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002713 try {
2714 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002715 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002716 } catch (NameNotFoundException nnfe) {
2717 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002718 } finally {
2719 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002720 }
2721 }
2722
Fyodor Kupolov82402752015-10-28 14:54:51 -07002723 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002724 AtomicFile restrictionsFile =
2725 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2726 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002727 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002728 }
2729
2730 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002731 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002732 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002733 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002734 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002735 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002736 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002737
2738 FileInputStream fis = null;
2739 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002740 fis = restrictionsFile.openRead();
2741 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002742 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002743 XmlUtils.nextElement(parser);
2744 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002745 Slog.e(LOG_TAG, "Unable to read restrictions file "
2746 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002747 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002748 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002749 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2750 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002751 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002752 } catch (IOException|XmlPullParserException e) {
2753 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002754 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002755 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002756 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002757 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002758 }
2759
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002760 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2761 XmlPullParser parser) throws XmlPullParserException, IOException {
2762 int type = parser.getEventType();
2763 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2764 String key = parser.getAttributeValue(null, ATTR_KEY);
2765 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2766 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2767 if (multiple != null) {
2768 values.clear();
2769 int count = Integer.parseInt(multiple);
2770 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2771 if (type == XmlPullParser.START_TAG
2772 && parser.getName().equals(TAG_VALUE)) {
2773 values.add(parser.nextText().trim());
2774 count--;
2775 }
2776 }
2777 String [] valueStrings = new String[values.size()];
2778 values.toArray(valueStrings);
2779 restrictions.putStringArray(key, valueStrings);
2780 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2781 restrictions.putBundle(key, readBundleEntry(parser, values));
2782 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2783 final int outerDepth = parser.getDepth();
2784 ArrayList<Bundle> bundleList = new ArrayList<>();
2785 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2786 Bundle childBundle = readBundleEntry(parser, values);
2787 bundleList.add(childBundle);
2788 }
2789 restrictions.putParcelableArray(key,
2790 bundleList.toArray(new Bundle[bundleList.size()]));
2791 } else {
2792 String value = parser.nextText().trim();
2793 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2794 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2795 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2796 restrictions.putInt(key, Integer.parseInt(value));
2797 } else {
2798 restrictions.putString(key, value);
2799 }
2800 }
2801 }
2802 }
2803
2804 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2805 throws IOException, XmlPullParserException {
2806 Bundle childBundle = new Bundle();
2807 final int outerDepth = parser.getDepth();
2808 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2809 readEntry(childBundle, values, parser);
2810 }
2811 return childBundle;
2812 }
2813
Fyodor Kupolov82402752015-10-28 14:54:51 -07002814 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002815 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002816 AtomicFile restrictionsFile = new AtomicFile(
2817 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002818 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002819 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002820 }
2821
2822 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002823 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002824 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002825 try {
2826 fos = restrictionsFile.startWrite();
2827 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2828
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002829 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002830 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002831 serializer.startDocument(null, true);
2832 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2833
2834 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002835 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002836 serializer.endTag(null, TAG_RESTRICTIONS);
2837
2838 serializer.endDocument();
2839 restrictionsFile.finishWrite(fos);
2840 } catch (Exception e) {
2841 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002842 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2843 }
2844 }
2845
2846 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2847 throws IOException {
2848 for (String key : restrictions.keySet()) {
2849 Object value = restrictions.get(key);
2850 serializer.startTag(null, TAG_ENTRY);
2851 serializer.attribute(null, ATTR_KEY, key);
2852
2853 if (value instanceof Boolean) {
2854 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2855 serializer.text(value.toString());
2856 } else if (value instanceof Integer) {
2857 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2858 serializer.text(value.toString());
2859 } else if (value == null || value instanceof String) {
2860 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2861 serializer.text(value != null ? (String) value : "");
2862 } else if (value instanceof Bundle) {
2863 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2864 writeBundle((Bundle) value, serializer);
2865 } else if (value instanceof Parcelable[]) {
2866 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2867 Parcelable[] array = (Parcelable[]) value;
2868 for (Parcelable parcelable : array) {
2869 if (!(parcelable instanceof Bundle)) {
2870 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2871 }
2872 serializer.startTag(null, TAG_ENTRY);
2873 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2874 writeBundle((Bundle) parcelable, serializer);
2875 serializer.endTag(null, TAG_ENTRY);
2876 }
2877 } else {
2878 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2879 String[] values = (String[]) value;
2880 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2881 for (String choice : values) {
2882 serializer.startTag(null, TAG_VALUE);
2883 serializer.text(choice != null ? choice : "");
2884 serializer.endTag(null, TAG_VALUE);
2885 }
2886 }
2887 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002888 }
2889 }
2890
2891 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002892 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002893 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002894 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002895 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002896 }
2897 }
2898
2899 @Override
2900 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002901 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002902 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002903 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002904 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002905 }
2906 // Not found
2907 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002908 }
2909 }
2910
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002911 @Override
2912 public long getUserCreationTime(int userHandle) {
2913 int callingUserId = UserHandle.getCallingUserId();
2914 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002915 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002916 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002917 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002918 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002919 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002920 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002921 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002922 }
2923 }
2924 }
2925 if (userInfo == null) {
2926 throw new SecurityException("userHandle can only be the calling user or a managed "
2927 + "profile associated with this user");
2928 }
2929 return userInfo.creationTime;
2930 }
2931
Amith Yamasani0b285492011-04-14 17:35:23 -07002932 /**
2933 * Caches the list of user ids in an array, adjusting the array size when necessary.
2934 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002935 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002936 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002937 synchronized (mUsersLock) {
2938 final int userSize = mUsers.size();
2939 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002940 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002941 num++;
2942 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002943 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002944 final int[] newUsers = new int[num];
2945 int n = 0;
2946 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002947 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002948 newUsers[n++] = mUsers.keyAt(i);
2949 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002950 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002951 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002952 }
2953 }
2954
2955 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002956 * Called right before a user is started. This gives us a chance to prepare
2957 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002958 */
2959 public void onBeforeStartUser(int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002960 UserInfo userInfo = getUserInfo(userId);
2961 if (userInfo == null) {
2962 return;
2963 }
2964 final int userSerial = userInfo.serialNumber;
2965 // Migrate only if build fingerprints mismatch
2966 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002967 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002968 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002969
2970 if (userId != UserHandle.USER_SYSTEM) {
2971 synchronized (mRestrictionsLock) {
2972 applyUserRestrictionsLR(userId);
2973 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002974 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002975
2976 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002977 }
2978
2979 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002980 * Called right before a user is unlocked. This gives us a chance to prepare
2981 * app storage.
2982 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002983 public void onBeforeUnlockUser(@UserIdInt int userId) {
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002984 UserInfo userInfo = getUserInfo(userId);
2985 if (userInfo == null) {
2986 return;
2987 }
2988 final int userSerial = userInfo.serialNumber;
2989 // Migrate only if build fingerprints mismatch
2990 boolean migrateAppsData = !Build.FINGERPRINT.equals(userInfo.lastLoggedInFingerprint);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002991 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolovd80c3622016-07-19 17:22:09 -07002992 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE, migrateAppsData);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002993 }
2994
2995 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002996 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002997 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002998 * @param userId the user that was just foregrounded
2999 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003000 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08003001 UserData userData = getUserDataNoChecks(userId);
3002 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003003 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
3004 return;
3005 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003006
3007 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003008 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08003009 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07003010 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003011 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
3012 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07003013 }
3014
Amith Yamasanieb437d42016-04-29 09:31:25 -07003015 private void maybeInitializeDemoMode(int userId) {
Suprabh Shukla0271fd62016-06-27 18:56:23 -07003016 if (UserManager.isDeviceInDemoMode(mContext) && userId != UserHandle.USER_SYSTEM) {
Amith Yamasanieb437d42016-04-29 09:31:25 -07003017 String demoLauncher =
3018 mContext.getResources().getString(
3019 com.android.internal.R.string.config_demoModeLauncherComponent);
3020 if (!TextUtils.isEmpty(demoLauncher)) {
3021 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
Sudheer Shanka194e4152016-07-06 17:49:37 -07003022 String demoLauncherPkg = componentToEnable.getPackageName();
Sudheer Shanka38c67d32016-08-02 22:13:17 +00003023 try {
3024 final IPackageManager iPm = AppGlobals.getPackageManager();
3025 iPm.setComponentEnabledSetting(componentToEnable,
3026 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3027 /* userId= */ userId);
3028 iPm.setApplicationEnabledSetting(demoLauncherPkg,
3029 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
3030 /* userId= */ userId, null);
3031 } catch (RemoteException re) {
3032 // Internal, shouldn't happen
3033 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07003034 }
3035 }
3036 }
3037
Amith Yamasani920ace02012-09-20 22:15:37 -07003038 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07003039 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani0b285492011-04-14 17:35:23 -07003040 */
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003041 @VisibleForTesting
3042 int getNextAvailableId() {
3043 int nextId;
Fyodor Kupolov82402752015-10-28 14:54:51 -07003044 synchronized (mUsersLock) {
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003045 nextId = scanNextAvailableIdLocked();
3046 if (nextId >= 0) {
3047 return nextId;
3048 }
3049 // All ids up to MAX_USER_ID were used. Remove all mRemovingUserIds,
3050 // except most recently removed
3051 if (mRemovingUserIds.size() > 0) {
3052 Slog.i(LOG_TAG, "All available IDs are used. Recycling LRU ids.");
3053 mRemovingUserIds.clear();
3054 for (Integer recentlyRemovedId : mRecentlyRemovedIds) {
3055 mRemovingUserIds.put(recentlyRemovedId, true);
Amith Yamasani195263742012-08-21 15:40:12 -07003056 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003057 nextId = scanNextAvailableIdLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003058 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003059 }
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003060 if (nextId < 0) {
3061 throw new IllegalStateException("No user id available!");
3062 }
3063 return nextId;
3064 }
3065
3066 private int scanNextAvailableIdLocked() {
3067 for (int i = MIN_USER_ID; i < MAX_USER_ID; i++) {
3068 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
3069 return i;
3070 }
3071 }
3072 return -1;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003073 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003074
Amith Yamasanifc95e702013-09-26 13:20:17 -07003075 private String packageToRestrictionsFileName(String packageName) {
3076 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
3077 }
3078
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003079 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003080 * Enforce that serial number stored in user directory inode matches the
3081 * given expected value. Gracefully sets the serial number if currently
3082 * undefined.
3083 *
3084 * @throws IOException when problem extracting serial number, or serial
3085 * number is mismatched.
3086 */
3087 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
Jeff Sharkeya52c9d92016-06-27 17:27:43 -06003088 if (StorageManager.isFileEncryptedEmulatedOnly()) {
3089 // When we're emulating FBE, the directory may have been chmod
3090 // 000'ed, meaning we can't read the serial number to enforce it;
3091 // instead of destroying the user, just log a warning.
3092 Slog.w(LOG_TAG, "Device is emulating FBE; assuming current serial number is valid");
3093 return;
3094 }
3095
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003096 final int foundSerial = getSerialNumber(file);
3097 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
3098
3099 if (foundSerial == -1) {
3100 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
3101 try {
3102 setSerialNumber(file, serialNumber);
3103 } catch (IOException e) {
3104 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
3105 }
3106
3107 } else if (foundSerial != serialNumber) {
3108 throw new IOException("Found serial number " + foundSerial
3109 + " doesn't match expected " + serialNumber);
3110 }
3111 }
3112
3113 /**
3114 * Set serial number stored in user directory inode.
3115 *
3116 * @throws IOException if serial number was already set
3117 */
3118 private static void setSerialNumber(File file, int serialNumber)
3119 throws IOException {
3120 try {
3121 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
3122 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
3123 } catch (ErrnoException e) {
3124 throw e.rethrowAsIOException();
3125 }
3126 }
3127
3128 /**
3129 * Return serial number stored in user directory inode.
3130 *
3131 * @return parsed serial number, or -1 if not set
3132 */
3133 private static int getSerialNumber(File file) throws IOException {
3134 try {
Yi Kongc44a6e02016-08-27 12:16:44 +01003135 final byte[] buf = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL);
3136 final String serial = new String(buf);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003137 try {
3138 return Integer.parseInt(serial);
3139 } catch (NumberFormatException e) {
3140 throw new IOException("Bad serial number: " + serial);
3141 }
3142 } catch (ErrnoException e) {
3143 if (e.errno == OsConstants.ENODATA) {
3144 return -1;
3145 } else {
3146 throw e.rethrowAsIOException();
3147 }
3148 }
3149 }
3150
Amith Yamasani920ace02012-09-20 22:15:37 -07003151 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003152 public void setSeedAccountData(int userId, String accountName, String accountType,
3153 PersistableBundle accountOptions, boolean persist) {
3154 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
3155 synchronized (mPackagesLock) {
3156 final UserData userData;
3157 synchronized (mUsersLock) {
3158 userData = getUserDataLU(userId);
3159 if (userData == null) {
3160 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
3161 return;
3162 }
3163 userData.seedAccountName = accountName;
3164 userData.seedAccountType = accountType;
3165 userData.seedAccountOptions = accountOptions;
3166 userData.persistSeedData = persist;
3167 }
3168 if (persist) {
3169 writeUserLP(userData);
3170 }
3171 }
3172 }
3173
3174 @Override
3175 public String getSeedAccountName() throws RemoteException {
3176 checkManageUsersPermission("Cannot get seed account information");
3177 synchronized (mUsersLock) {
3178 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3179 return userData.seedAccountName;
3180 }
3181 }
3182
3183 @Override
3184 public String getSeedAccountType() throws RemoteException {
3185 checkManageUsersPermission("Cannot get seed account information");
3186 synchronized (mUsersLock) {
3187 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3188 return userData.seedAccountType;
3189 }
3190 }
3191
3192 @Override
3193 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3194 checkManageUsersPermission("Cannot get seed account information");
3195 synchronized (mUsersLock) {
3196 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3197 return userData.seedAccountOptions;
3198 }
3199 }
3200
3201 @Override
3202 public void clearSeedAccountData() throws RemoteException {
3203 checkManageUsersPermission("Cannot clear seed account information");
3204 synchronized (mPackagesLock) {
3205 UserData userData;
3206 synchronized (mUsersLock) {
3207 userData = getUserDataLU(UserHandle.getCallingUserId());
3208 if (userData == null) return;
3209 userData.clearSeedAccountData();
3210 }
3211 writeUserLP(userData);
3212 }
3213 }
3214
3215 @Override
3216 public boolean someUserHasSeedAccount(String accountName, String accountType)
3217 throws RemoteException {
3218 checkManageUsersPermission("Cannot check seed account information");
3219 synchronized (mUsersLock) {
3220 final int userSize = mUsers.size();
3221 for (int i = 0; i < userSize; i++) {
3222 final UserData data = mUsers.valueAt(i);
3223 if (data.info.isInitialized()) continue;
3224 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3225 continue;
3226 }
3227 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3228 continue;
3229 }
3230 return true;
3231 }
3232 }
3233 return false;
3234 }
3235
3236 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003237 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003238 FileDescriptor err, String[] args, ShellCallback callback,
3239 ResultReceiver resultReceiver) {
3240 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Todd Kennedy60459ab2015-10-30 11:32:16 -07003241 }
3242
3243 int onShellCommand(Shell shell, String cmd) {
3244 if (cmd == null) {
3245 return shell.handleDefaultCommands(cmd);
3246 }
3247
3248 final PrintWriter pw = shell.getOutPrintWriter();
3249 try {
3250 switch(cmd) {
3251 case "list":
3252 return runList(pw);
3253 }
3254 } catch (RemoteException e) {
3255 pw.println("Remote exception: " + e);
3256 }
3257 return -1;
3258 }
3259
3260 private int runList(PrintWriter pw) throws RemoteException {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003261 final IActivityManager am = ActivityManager.getService();
Todd Kennedy60459ab2015-10-30 11:32:16 -07003262 final List<UserInfo> users = getUsers(false);
3263 if (users == null) {
3264 pw.println("Error: couldn't get users");
3265 return 1;
3266 } else {
3267 pw.println("Users:");
3268 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003269 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003270 pw.println("\t" + users.get(i).toString() + running);
3271 }
3272 return 0;
3273 }
3274 }
3275
3276 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003277 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3278 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3279 != PackageManager.PERMISSION_GRANTED) {
3280 pw.println("Permission Denial: can't dump UserManager from from pid="
3281 + Binder.getCallingPid()
3282 + ", uid=" + Binder.getCallingUid()
3283 + " without permission "
3284 + android.Manifest.permission.DUMP);
3285 return;
3286 }
3287
3288 long now = System.currentTimeMillis();
3289 StringBuilder sb = new StringBuilder();
3290 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003291 synchronized (mUsersLock) {
3292 pw.println("Users:");
3293 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003294 UserData userData = mUsers.valueAt(i);
3295 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003296 continue;
3297 }
Amith Yamasani12747872015-12-07 14:19:49 -08003298 UserInfo userInfo = userData.info;
3299 final int userId = userInfo.id;
3300 pw.print(" "); pw.print(userInfo);
3301 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003302 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003303 pw.print(" <removing> ");
3304 }
Amith Yamasani12747872015-12-07 14:19:49 -08003305 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003306 pw.print(" <partial>");
3307 }
3308 pw.println();
3309 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003310 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003311 pw.println("<unknown>");
3312 } else {
3313 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003314 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003315 sb.append(" ago");
3316 pw.println(sb);
3317 }
3318 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003319 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003320 pw.println("<unknown>");
3321 } else {
3322 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003323 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003324 sb.append(" ago");
3325 pw.println(sb);
3326 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003327 pw.print(" Last logged in fingerprint: ");
3328 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003329 pw.print(" Has profile owner: ");
3330 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003331 pw.println(" Restrictions:");
3332 synchronized (mRestrictionsLock) {
3333 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003334 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003335 pw.println(" Device policy local restrictions:");
3336 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003337 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003338 pw.println(" Effective restrictions:");
3339 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003340 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003341 }
Amith Yamasani12747872015-12-07 14:19:49 -08003342
3343 if (userData.account != null) {
3344 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003345 pw.println();
3346 }
Amith Yamasani12747872015-12-07 14:19:49 -08003347
3348 if (userData.seedAccountName != null) {
3349 pw.print(" Seed account name: " + userData.seedAccountName);
3350 pw.println();
3351 if (userData.seedAccountType != null) {
3352 pw.print(" account type: " + userData.seedAccountType);
3353 pw.println();
3354 }
3355 if (userData.seedAccountOptions != null) {
3356 pw.print(" account options exist");
3357 pw.println();
3358 }
3359 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003360 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003361 }
Amith Yamasani12747872015-12-07 14:19:49 -08003362 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003363 pw.println(" Device policy global restrictions:");
3364 synchronized (mRestrictionsLock) {
3365 UserRestrictionsUtils
3366 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3367 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003368 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003369 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3370 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003371 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003372 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003373 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003374 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003375 synchronized (mUsersLock) {
3376 pw.println();
3377 pw.println(" Device managed: " + mIsDeviceManaged);
Fyodor Kupolov0f4533d2016-05-18 18:43:12 -07003378 if (mRemovingUserIds.size() > 0) {
3379 pw.println();
3380 pw.println(" Recently removed userIds: " + mRecentlyRemovedIds);
3381 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003382 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003383 synchronized (mUserStates) {
3384 pw.println(" Started users state: " + mUserStates);
3385 }
Amith Yamasani12747872015-12-07 14:19:49 -08003386 // Dump some capabilities
3387 pw.println();
3388 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3389 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003390 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3391 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003392 }
3393 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003394
3395 final class MainHandler extends Handler {
3396
3397 @Override
3398 public void handleMessage(Message msg) {
3399 switch (msg.what) {
3400 case WRITE_USER_MSG:
3401 removeMessages(WRITE_USER_MSG, msg.obj);
3402 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003403 int userId = ((UserData) msg.obj).info.id;
3404 UserData userData = getUserDataNoChecks(userId);
3405 if (userData != null) {
3406 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003407 }
3408 }
3409 }
3410 }
3411 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003412
3413 /**
3414 * @param userId
3415 * @return whether the user has been initialized yet
3416 */
3417 boolean isInitialized(int userId) {
3418 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3419 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003420
3421 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003422 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003423 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3424 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003425 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003426 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003427 }
3428
3429 @Override
3430 public Bundle getBaseUserRestrictions(int userId) {
3431 synchronized (mRestrictionsLock) {
3432 return mBaseUserRestrictions.get(userId);
3433 }
3434 }
3435
3436 @Override
3437 public void setBaseUserRestrictionsByDpmsForMigration(
3438 int userId, Bundle baseRestrictions) {
3439 synchronized (mRestrictionsLock) {
3440 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003441 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003442 }
3443
Amith Yamasani12747872015-12-07 14:19:49 -08003444 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003445 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003446 if (userData != null) {
3447 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003448 } else {
3449 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3450 }
3451 }
3452 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003453
3454 @Override
3455 public boolean getUserRestriction(int userId, String key) {
3456 return getUserRestrictions(userId).getBoolean(key);
3457 }
3458
3459 @Override
3460 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3461 synchronized (mUserRestrictionsListeners) {
3462 mUserRestrictionsListeners.add(listener);
3463 }
3464 }
3465
3466 @Override
3467 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3468 synchronized (mUserRestrictionsListeners) {
3469 mUserRestrictionsListeners.remove(listener);
3470 }
3471 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003472
3473 @Override
3474 public void setDeviceManaged(boolean isManaged) {
3475 synchronized (mUsersLock) {
3476 mIsDeviceManaged = isManaged;
3477 }
3478 }
3479
3480 @Override
3481 public void setUserManaged(int userId, boolean isManaged) {
3482 synchronized (mUsersLock) {
3483 mIsUserManaged.put(userId, isManaged);
3484 }
3485 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003486
3487 @Override
3488 public void setUserIcon(int userId, Bitmap bitmap) {
3489 long ident = Binder.clearCallingIdentity();
3490 try {
3491 synchronized (mPackagesLock) {
3492 UserData userData = getUserDataNoChecks(userId);
3493 if (userData == null || userData.info.partial) {
3494 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3495 return;
3496 }
3497 writeBitmapLP(userData.info, bitmap);
3498 writeUserLP(userData);
3499 }
3500 sendUserInfoChangedBroadcast(userId);
3501 } finally {
3502 Binder.restoreCallingIdentity(ident);
3503 }
3504 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003505
3506 @Override
3507 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3508 synchronized (mUsersLock) {
3509 mForceEphemeralUsers = forceEphemeralUsers;
3510 }
3511 }
3512
3513 @Override
3514 public void removeAllUsers() {
3515 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3516 // Remove the non-system users straight away.
3517 removeNonSystemUsers();
3518 } else {
3519 // Switch to the system user first and then remove the other users.
3520 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3521 @Override
3522 public void onReceive(Context context, Intent intent) {
3523 int userId =
3524 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3525 if (userId != UserHandle.USER_SYSTEM) {
3526 return;
3527 }
3528 mContext.unregisterReceiver(this);
3529 removeNonSystemUsers();
3530 }
3531 };
3532 IntentFilter userSwitchedFilter = new IntentFilter();
3533 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3534 mContext.registerReceiver(
3535 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3536
3537 // Switch to the system user.
3538 ActivityManager am =
3539 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3540 am.switchUser(UserHandle.USER_SYSTEM);
3541 }
3542 }
phweisse9c44062016-02-10 12:57:38 +01003543
3544 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003545 public void onEphemeralUserStop(int userId) {
3546 synchronized (mUsersLock) {
3547 UserInfo userInfo = getUserInfoLU(userId);
3548 if (userInfo != null && userInfo.isEphemeral()) {
3549 // Do not allow switching back to the ephemeral user again as the user is going
3550 // to be deleted.
3551 userInfo.flags |= UserInfo.FLAG_DISABLED;
3552 if (userInfo.isGuest()) {
3553 // Indicate that the guest will be deleted after it stops.
3554 userInfo.guestToRemove = true;
3555 }
3556 }
3557 }
3558 }
3559
3560 @Override
phweisse9c44062016-02-10 12:57:38 +01003561 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
Sudheer Shanka7cb54a32016-09-16 12:59:05 -07003562 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL, null);
phweisse9c44062016-02-10 12:57:38 +01003563 // Keep this in sync with UserManager.createUser
3564 if (user != null && !user.isAdmin()) {
3565 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3566 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3567 }
3568 return user;
3569 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003570
3571 @Override
Nicolas Prevotdf1b87d2016-10-25 13:57:08 +01003572 public boolean removeUserEvenWhenDisallowed(int userId) {
3573 return removeUserUnchecked(userId);
3574 }
3575
3576 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003577 public boolean isUserRunning(int userId) {
3578 synchronized (mUserStates) {
3579 return mUserStates.get(userId, -1) >= 0;
3580 }
3581 }
3582
3583 @Override
3584 public void setUserState(int userId, int userState) {
3585 synchronized (mUserStates) {
3586 mUserStates.put(userId, userState);
3587 }
3588 }
3589
3590 @Override
3591 public void removeUserState(int userId) {
3592 synchronized (mUserStates) {
3593 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003594 }
3595 }
3596
3597 @Override
3598 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003599 synchronized (mUserStates) {
3600 int state = mUserStates.get(userId, -1);
3601 return (state == UserState.STATE_RUNNING_UNLOCKING)
3602 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003603 }
3604 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003605 }
3606
3607 /* Remove all the users except of the system one. */
3608 private void removeNonSystemUsers() {
3609 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3610 synchronized (mUsersLock) {
3611 final int userSize = mUsers.size();
3612 for (int i = 0; i < userSize; i++) {
3613 UserInfo ui = mUsers.valueAt(i).info;
3614 if (ui.id != UserHandle.USER_SYSTEM) {
3615 usersToRemove.add(ui);
3616 }
3617 }
3618 }
3619 for (UserInfo ui: usersToRemove) {
3620 removeUser(ui.id);
3621 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003622 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003623
3624 private class Shell extends ShellCommand {
3625 @Override
3626 public int onCommand(String cmd) {
3627 return onShellCommand(this, cmd);
3628 }
3629
3630 @Override
3631 public void onHelp() {
3632 final PrintWriter pw = getOutPrintWriter();
3633 pw.println("User manager (user) commands:");
3634 pw.println(" help");
3635 pw.println(" Print this help text.");
3636 pw.println("");
3637 pw.println(" list");
3638 pw.println(" Prints all users on the system.");
3639 }
3640 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003641
3642 private static void debug(String message) {
3643 Log.d(LOG_TAG, message +
3644 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3645 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003646}