blob: 632a98e5300150f19bd5794369c3d9aecfed97cf [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.content.Context;
36import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010037import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010038import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070039import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080040import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010042import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070043import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060045import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080046import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080047import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.os.Environment;
49import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080051import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070052import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080053import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010054import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070055import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080056import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070057import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070058import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070059import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010060import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040061import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070063import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070064import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070065import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080066import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010067import android.os.storage.StorageManager;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070068import android.security.GateKeeper;
69import android.service.gatekeeper.IGateKeeperService;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070070import android.system.ErrnoException;
71import android.system.Os;
72import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070073import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070074import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070075import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076import android.util.Slog;
77import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080078import android.util.SparseBooleanArray;
Fyodor Kupolovac06a492016-05-25 14:45:29 -070079import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070080import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081import android.util.Xml;
82
Makoto Onuki068c54a2015-10-13 14:34:03 -070083import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070084import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040085import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080086import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080087import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070088import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000090import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070091import com.android.server.LocalServices;
Amith Yamasanid04aaa32016-06-13 12:09:36 -070092import com.android.server.SystemService;
Fyodor Kupolovac06a492016-05-25 14:45:29 -070093import com.android.server.am.UserState;
Jeff Sharkey47f71082016-02-01 17:03:54 -070094
95import libcore.io.IoUtils;
96import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080097
98import org.xmlpull.v1.XmlPullParser;
99import org.xmlpull.v1.XmlPullParserException;
100import org.xmlpull.v1.XmlSerializer;
101
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700102import java.io.BufferedOutputStream;
103import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700104import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700106import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107import java.io.FileOutputStream;
108import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700109import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100110import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111import java.util.ArrayList;
112import java.util.List;
113
Makoto Onuki068c54a2015-10-13 14:34:03 -0700114/**
115 * Service for {@link UserManager}.
116 *
117 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700118 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800119 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700120 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
121 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
122 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700123 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700124public class UserManagerService extends IUserManager.Stub {
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700125
Amith Yamasani2a003292012-08-14 18:25:45 -0700126 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800127 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800128 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700129
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800131 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700133 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700135 private static final String ATTR_CREATION_TIME = "created";
136 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600137 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700138 private static final String ATTR_SERIAL_NO = "serialNumber";
139 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700140 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700141 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700142 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100143 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700144 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800145 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
146 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530147 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700148 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700149 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800150 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800151 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100152 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800153 private static final String TAG_ENTRY = "entry";
154 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800155 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800156 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700157 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800158 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700159
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700160 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
161 private static final String ATTR_TYPE_STRING = "s";
162 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700163 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700164 private static final String ATTR_TYPE_BUNDLE = "B";
165 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700166
Amith Yamasani0b285492011-04-14 17:35:23 -0700167 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700168 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700169 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100170 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800172 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700173 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800174
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700175 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
176 UserInfo.FLAG_MANAGED_PROFILE
177 | UserInfo.FLAG_EPHEMERAL
178 | UserInfo.FLAG_RESTRICTED
179 | UserInfo.FLAG_GUEST;
180
Amith Yamasani634cf312012-10-04 17:34:21 -0700181 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700182 // We need to keep process uid within Integer.MAX_VALUE.
183 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700184
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700185 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700186
Amith Yamasani920ace02012-09-20 22:15:37 -0700187 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
188
Nicolas Prevotb8186812015-08-06 15:00:03 +0100189 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700190 // without first making sure that the rest of the framework is prepared for it.
191 private static final int MAX_MANAGED_PROFILES = 1;
192
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800193 static final int WRITE_USER_MSG = 1;
194 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530195
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700196 private static final String XATTR_SERIAL = "user.serial";
197
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800198 // Tron counters
199 private static final String TRON_GUEST_CREATED = "users_guest_created";
200 private static final String TRON_USER_CREATED = "users_user_created";
201
Dianne Hackborn4428e172012-08-24 17:43:05 -0700202 private final Context mContext;
203 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700204 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700205 // Short-term lock for internal state, when interaction/sync with PM is not required
206 private final Object mUsersLock = new Object();
207 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700208
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800209 private final Handler mHandler;
210
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700211 private final File mUsersDir;
212 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700213
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800214 private static final IBinder mUserRestriconToken = new Binder();
215
Makoto Onuki068c54a2015-10-13 14:34:03 -0700216 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800217 * User-related information that is used for persisting to flash. Only UserInfo is
218 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800219 */
Amith Yamasani12747872015-12-07 14:19:49 -0800220 private static class UserData {
221 // Basic user information and properties
222 UserInfo info;
223 // Account name used when there is a strong association between a user and an account
224 String account;
225 // Account information for seeding into a newly created user. This could also be
226 // used for login validation for an existing user, for updating their credentials.
227 // In the latter case, data may not need to be persisted as it is only valid for the
228 // current login session.
229 String seedAccountName;
230 String seedAccountType;
231 PersistableBundle seedAccountOptions;
232 // Whether to perist the seed account information to be available after a boot
233 boolean persistSeedData;
234
235 void clearSeedAccountData() {
236 seedAccountName = null;
237 seedAccountType = null;
238 seedAccountOptions = null;
239 persistSeedData = false;
240 }
241 }
242
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800243 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800244 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800245
246 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700247 * User restrictions set via UserManager. This doesn't include restrictions set by
248 * device owner / profile owners.
249 *
250 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
251 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
252 * maybe shared between {@link #mBaseUserRestrictions} and
253 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
254 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700255 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700256 */
257 @GuardedBy("mRestrictionsLock")
258 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
259
260 /**
261 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
262 * with device / profile owner restrictions. We'll initialize it lazily; use
263 * {@link #getEffectiveUserRestrictions} to access it.
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> mCachedEffectiveUserRestrictions = new SparseArray<>();
274
Makoto Onuki4f160732015-10-27 17:15:38 -0700275 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800276 * User restrictions that have already been applied in
277 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
278 * that have changed since the last
279 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700280 */
281 @GuardedBy("mRestrictionsLock")
282 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
283
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800284 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800285 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
286 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800287 */
288 @GuardedBy("mRestrictionsLock")
289 private Bundle mDevicePolicyGlobalUserRestrictions;
290
291 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100292 * Id of the user that set global restrictions.
293 */
294 @GuardedBy("mRestrictionsLock")
295 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
296
297 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800298 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
299 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800300 */
301 @GuardedBy("mRestrictionsLock")
302 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
303
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800304 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530305 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800306
307 /**
308 * Set of user IDs being actively removed. Removed IDs linger in this set
309 * for several seconds to work around a VFS caching issue.
310 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700311 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800312 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700313
Fyodor Kupolov82402752015-10-28 14:54:51 -0700314 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700315 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800316 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700317 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700318 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700319
Jason Monk62062992014-05-06 09:55:28 -0400320 private IAppOpsService mAppOpsService;
321
Makoto Onuki068c54a2015-10-13 14:34:03 -0700322 private final LocalService mLocalService;
323
Makoto Onukie7927da2015-11-25 10:05:17 -0800324 @GuardedBy("mUsersLock")
325 private boolean mIsDeviceManaged;
326
327 @GuardedBy("mUsersLock")
328 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
329
Makoto Onukid45a4a22015-11-02 17:17:38 -0800330 @GuardedBy("mUserRestrictionsListeners")
331 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
332 new ArrayList<>();
333
Clara Bayarria1771112015-12-18 16:29:18 +0000334 private final LockPatternUtils mLockPatternUtils;
335
Ricky Waib1dd80b2016-06-07 18:00:55 +0100336 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
337 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
338
339 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
340 @Override
341 public void onReceive(Context context, Intent intent) {
342 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
343 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
344 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
345 setQuietModeEnabled(userHandle, false);
346 if (target != null) {
347 try {
348 mContext.startIntentSender(target, null, 0, 0, 0);
349 } catch (IntentSender.SendIntentException e) {
350 /* ignore */
351 }
352 }
353 }
354 }
355 };
356
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100357 /**
358 * Whether all users should be created ephemeral.
359 */
360 @GuardedBy("mUsersLock")
361 private boolean mForceEphemeralUsers;
362
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700363 @GuardedBy("mUserStates")
364 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700365
Amith Yamasani258848d2012-08-10 17:06:33 -0700366 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700367
Dianne Hackborn4428e172012-08-24 17:43:05 -0700368 public static UserManagerService getInstance() {
369 synchronized (UserManagerService.class) {
370 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700371 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700372 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700373
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700374 public static class LifeCycle extends SystemService {
375
376 private UserManagerService mUms;
377
378 /**
379 * @param context
380 */
381 public LifeCycle(Context context) {
382 super(context);
383 }
384
385 @Override
386 public void onStart() {
387 mUms = UserManagerService.getInstance();
388 publishBinderService(Context.USER_SERVICE, mUms);
389 }
390
391 @Override
392 public void onBootPhase(int phase) {
393 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
394 mUms.cleanupPartialUsers();
395 }
396 }
397 }
398
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800399 @VisibleForTesting
400 UserManagerService(File dataDir) {
401 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700402 }
403
Dianne Hackborn4428e172012-08-24 17:43:05 -0700404 /**
405 * Called by package manager to create the service. This is closely
406 * associated with the package manager, and the given lock is the
407 * package manager's own lock.
408 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800409 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
410 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700411 }
412
Dianne Hackborn4428e172012-08-24 17:43:05 -0700413 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800414 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700415 mContext = context;
416 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700417 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800418 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800419 synchronized (mPackagesLock) {
420 mUsersDir = new File(dataDir, USER_INFO_DIR);
421 mUsersDir.mkdirs();
422 // Make zeroth user directory, for services to migrate their files to that location
423 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
424 userZeroDir.mkdirs();
425 FileUtils.setPermissions(mUsersDir.toString(),
426 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
427 -1, -1);
428 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
429 initDefaultGuestRestrictions();
430 readUserListLP();
431 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700432 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700433 mLocalService = new LocalService();
434 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000435 mLockPatternUtils = new LockPatternUtils(mContext);
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700436 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700437 }
438
439 void systemReady() {
Jason Monk62062992014-05-06 09:55:28 -0400440 mAppOpsService = IAppOpsService.Stub.asInterface(
441 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800442
443 synchronized (mRestrictionsLock) {
444 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400445 }
Samuel Tand9453b82016-03-14 15:57:02 -0700446
447 UserInfo currentGuestUser = findCurrentGuestUser();
448 if (currentGuestUser != null && !hasUserRestriction(
449 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
450 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
451 // to it, in case this guest was created in a previous version where this
452 // user restriction was not a default guest restriction.
453 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
454 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100455 mContext.registerReceiver(mDisableQuietModeCallback,
456 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
457 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 }
459
Amith Yamasanid04aaa32016-06-13 12:09:36 -0700460 void cleanupPartialUsers() {
461 // Prune out any partially created, partially removed and ephemeral users.
462 ArrayList<UserInfo> partials = new ArrayList<>();
463 synchronized (mUsersLock) {
464 final int userSize = mUsers.size();
465 for (int i = 0; i < userSize; i++) {
466 UserInfo ui = mUsers.valueAt(i).info;
467 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
468 partials.add(ui);
469 }
470 }
471 }
472 final int partialsSize = partials.size();
473 for (int i = 0; i < partialsSize; i++) {
474 UserInfo ui = partials.get(i);
475 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
476 + " (name=" + ui.name + ")");
477 removeUserState(ui.id);
478 }
479 }
480
Amith Yamasani258848d2012-08-10 17:06:33 -0700481 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800482 public String getUserAccount(int userId) {
483 checkManageUserAndAcrossUsersFullPermission("get user account");
484 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800485 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800486 }
487 }
488
489 @Override
490 public void setUserAccount(int userId, String accountName) {
491 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800492 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800493 synchronized (mPackagesLock) {
494 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800495 final UserData userData = mUsers.get(userId);
496 if (userData == null) {
497 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
498 return;
499 }
500 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800501 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800502 userData.account = accountName;
503 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800504 }
505 }
506
507 if (userToUpdate != null) {
508 writeUserLP(userToUpdate);
509 }
510 }
511 }
512
513 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700514 public UserInfo getPrimaryUser() {
515 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700516 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700517 final int userSize = mUsers.size();
518 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800519 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800520 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700521 return ui;
522 }
523 }
524 }
525 return null;
526 }
527
528 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700529 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700530 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700531 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700532 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700533 final int userSize = mUsers.size();
534 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800535 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700536 if (ui.partial) {
537 continue;
538 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800539 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700540 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700541 }
Amith Yamasani13593602012-03-22 16:16:17 -0700542 }
543 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700544 }
Amith Yamasani13593602012-03-22 16:16:17 -0700545 }
546
Amith Yamasani258848d2012-08-10 17:06:33 -0700547 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100548 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700549 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800550 if (userId != UserHandle.getCallingUserId()) {
Sudheer Shanka74680912016-07-29 11:03:37 -0700551 checkManageOrCreateUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700552 } else {
553 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800554 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700555 final long ident = Binder.clearCallingIdentity();
556 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700557 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700558 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100559 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700560 } finally {
561 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000562 }
563 }
564
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700565 @Override
566 public int[] getProfileIds(int userId, boolean enabledOnly) {
567 if (userId != UserHandle.getCallingUserId()) {
568 checkManageUsersPermission("getting profiles related to user " + userId);
569 }
570 final long ident = Binder.clearCallingIdentity();
571 try {
572 synchronized (mUsersLock) {
573 return getProfileIdsLU(userId, enabledOnly).toArray();
574 }
575 } finally {
576 Binder.restoreCallingIdentity(ident);
577 }
578 }
579
Amith Yamasanibe465322014-04-24 13:45:17 -0700580 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700581 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700582 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
583 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
584 for (int i = 0; i < profileIds.size(); i++) {
585 int profileId = profileIds.get(i);
586 UserInfo userInfo = mUsers.get(profileId).info;
587 // If full info is not required - clear PII data to prevent 3P apps from reading it
588 if (!fullInfo) {
589 userInfo = new UserInfo(userInfo);
590 userInfo.name = null;
591 userInfo.iconPath = null;
592 } else {
593 userInfo = userWithName(userInfo);
594 }
595 users.add(userInfo);
596 }
597 return users;
598 }
599
600 /**
601 * Assume permissions already checked and caller's identity cleared
602 */
603 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700604 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700605 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700606 if (user == null) {
607 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700608 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700609 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700610 final int userSize = mUsers.size();
611 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800612 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700613 if (!isProfileOf(user, profile)) {
614 continue;
615 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100616 if (enabledOnly && !profile.isEnabled()) {
617 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700618 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700619 if (mRemovingUserIds.get(profile.id)) {
620 continue;
621 }
Tony Mak80189cd2016-04-05 17:21:42 +0100622 if (profile.partial) {
623 continue;
624 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700625 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700626 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700627 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700628 }
629
Jessica Hummelbe81c802014-04-22 15:49:22 +0100630 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700631 public int getCredentialOwnerProfile(int userHandle) {
632 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000633 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700634 synchronized (mUsersLock) {
635 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700636 if (profileParent != null) {
637 return profileParent.id;
638 }
639 }
640 }
641
642 return userHandle;
643 }
644
645 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700646 public boolean isSameProfileGroup(int userId, int otherUserId) {
647 if (userId == otherUserId) return true;
648 checkManageUsersPermission("check if in the same profile group");
649 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700650 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700651 }
652 }
653
Fyodor Kupolov82402752015-10-28 14:54:51 -0700654 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
655 synchronized (mUsersLock) {
656 UserInfo userInfo = getUserInfoLU(userId);
657 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
658 return false;
659 }
660 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
661 if (otherUserInfo == null
662 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
663 return false;
664 }
665 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700666 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700667 }
668
669 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100670 public UserInfo getProfileParent(int userHandle) {
671 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700672 synchronized (mUsersLock) {
673 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700674 }
675 }
676
Fyodor Kupolov82402752015-10-28 14:54:51 -0700677 private UserInfo getProfileParentLU(int userHandle) {
678 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700679 if (profile == null) {
680 return null;
681 }
682 int parentUserId = profile.profileGroupId;
683 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
684 return null;
685 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700686 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100687 }
688 }
689
Fyodor Kupolov82402752015-10-28 14:54:51 -0700690 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100691 return user.id == profile.id ||
692 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
693 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000694 }
695
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000696 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000697 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100698 Intent intent = new Intent();
699 if (inQuietMode) {
700 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
701 } else {
702 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
703 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000704 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
705 intent.putExtra(Intent.EXTRA_USER, profileHandle);
706 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000707 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000708 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000709 }
710
711 @Override
712 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
713 checkManageUsersPermission("silence profile");
714 boolean changed = false;
715 UserInfo profile, parent;
716 synchronized (mPackagesLock) {
717 synchronized (mUsersLock) {
718 profile = getUserInfoLU(userHandle);
719 parent = getProfileParentLU(userHandle);
720
721 }
722 if (profile == null || !profile.isManagedProfile()) {
723 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
724 }
725 if (profile.isQuietModeEnabled() != enableQuietMode) {
726 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800727 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000728 changed = true;
729 }
730 }
731 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000732 long identity = Binder.clearCallingIdentity();
733 try {
734 if (enableQuietMode) {
Nicolas Prevot1219c922016-06-20 17:25:12 +0100735 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
Rubin Xuf8451b92016-04-01 15:50:58 +0100736 LocalServices.getService(ActivityManagerInternal.class)
737 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000738 } else {
739 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
740 }
741 } catch (RemoteException e) {
742 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
743 } finally {
744 Binder.restoreCallingIdentity(identity);
745 }
746
747 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
748 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000749 }
750 }
751
752 @Override
753 public boolean isQuietModeEnabled(int userHandle) {
754 synchronized (mPackagesLock) {
755 UserInfo info;
756 synchronized (mUsersLock) {
757 info = getUserInfoLU(userHandle);
758 }
759 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000760 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000761 }
762 return info.isQuietModeEnabled();
763 }
764 }
765
Kenny Guya52dc3e2014-02-11 15:33:14 +0000766 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100767 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100768 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600769 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100770 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100771 // if the user is already unlocked, no need to show a profile challenge
772 setQuietModeEnabled(userHandle, false);
773 return true;
774 }
775
776 long identity = Binder.clearCallingIdentity();
777 try {
778 // otherwise, we show a profile challenge to trigger decryption of the user
779 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
780 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100781 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
782 // lock, confirm screenlock page will know and show personal challenge, and unlock
783 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100784 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
785 userHandle);
786 if (unlockIntent == null) {
787 return false;
788 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100789 final Intent callBackIntent = new Intent(
790 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100791 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100792 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100793 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100794 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
795 callBackIntent.setPackage(mContext.getPackageName());
796 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
797 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
798 mContext,
799 0,
800 callBackIntent,
801 PendingIntent.FLAG_CANCEL_CURRENT |
802 PendingIntent.FLAG_ONE_SHOT |
803 PendingIntent.FLAG_IMMUTABLE);
804 // After unlocking the challenge, it will disable quiet mode and run the original
805 // intentSender
806 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100807 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
808 mContext.startActivity(unlockIntent);
809 } finally {
810 Binder.restoreCallingIdentity(identity);
811 }
812 return false;
813 }
814
815 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100816 public void setUserEnabled(int userId) {
817 checkManageUsersPermission("enable user");
818 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700819 UserInfo info;
820 synchronized (mUsersLock) {
821 info = getUserInfoLU(userId);
822 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100823 if (info != null && !info.isEnabled()) {
824 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800825 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100826 }
827 }
828 }
829
830 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700831 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700832 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000833 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700834 return userWithName(getUserInfoLU(userId));
835 }
836 }
837
838 /**
839 * Returns a UserInfo object with the name filled in, for Owner, or the original
840 * if the name is already set.
841 */
842 private UserInfo userWithName(UserInfo orig) {
843 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
844 UserInfo withName = new UserInfo(orig);
845 withName.name = getOwnerName();
846 return withName;
847 } else {
848 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000849 }
850 }
851
852 @Override
853 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000854 int callingUserId = UserHandle.getCallingUserId();
855 if (callingUserId != userId && !hasManageUsersPermission()) {
856 synchronized (mPackagesLock) {
857 if (!isSameProfileGroupLP(callingUserId, userId)) {
858 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000859 "You need MANAGE_USERS permission to: check if specified user a " +
860 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000861 }
862 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000863 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700864 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000865 UserInfo userInfo = getUserInfoLU(userId);
866 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700867 }
868 }
869
Amith Yamasani71e6c692013-03-24 17:39:28 -0700870 @Override
871 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700872 synchronized (mUsersLock) {
873 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700874 }
875 }
876
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700877 @Override
878 public boolean canHaveRestrictedProfile(int userId) {
879 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700880 synchronized (mUsersLock) {
881 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700882 if (userInfo == null || !userInfo.canHaveProfile()) {
883 return false;
884 }
885 if (!userInfo.isAdmin()) {
886 return false;
887 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800888 // restricted profile can be created if there is no DO set and the admin user has no PO;
889 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700890 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700891 }
892
Amith Yamasani195263742012-08-21 15:40:12 -0700893 /*
894 * Should be locked on mUsers before calling this.
895 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700896 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800897 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700898 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800899 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700900 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
901 return null;
902 }
Amith Yamasani12747872015-12-07 14:19:49 -0800903 return userData != null ? userData.info : null;
904 }
905
906 private UserData getUserDataLU(int userId) {
907 final UserData userData = mUsers.get(userId);
908 // If it is partial and not in the process of being removed, return as unknown user.
909 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
910 return null;
911 }
912 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700913 }
914
Fyodor Kupolov82402752015-10-28 14:54:51 -0700915 /**
916 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
917 * <p>No permissions checking or any addition checks are made</p>
918 */
919 private UserInfo getUserInfoNoChecks(int userId) {
920 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800921 final UserData userData = mUsers.get(userId);
922 return userData != null ? userData.info : null;
923 }
924 }
925
926 /**
927 * Obtains {@link #mUsersLock} and return UserData from mUsers.
928 * <p>No permissions checking or any addition checks are made</p>
929 */
930 private UserData getUserDataNoChecks(int userId) {
931 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700932 return mUsers.get(userId);
933 }
934 }
935
Amith Yamasani236b2b52015-08-18 14:32:14 -0700936 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700937 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700938 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700939 }
940
Amith Yamasani258848d2012-08-10 17:06:33 -0700941 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700942 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700943 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700944 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700945 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800946 UserData userData = getUserDataNoChecks(userId);
947 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700948 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
949 return;
950 }
Amith Yamasani12747872015-12-07 14:19:49 -0800951 if (name != null && !name.equals(userData.info.name)) {
952 userData.info.name = name;
953 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700954 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700955 }
956 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700957 if (changed) {
958 sendUserInfoChangedBroadcast(userId);
959 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700960 }
961
Amith Yamasani258848d2012-08-10 17:06:33 -0700962 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700963 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700964 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100965 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
966 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
967 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700968 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100969 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700970 }
971
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100972
973
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700974 private void sendUserInfoChangedBroadcast(int userId) {
975 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
976 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
977 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700978 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700979 }
980
Amith Yamasani258848d2012-08-10 17:06:33 -0700981 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100982 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100983 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700984 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100985 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
986 if (targetUserInfo == null || targetUserInfo.partial) {
987 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700988 return null;
989 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100990
991 final int callingUserId = UserHandle.getCallingUserId();
992 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
993 final int targetGroupId = targetUserInfo.profileGroupId;
994 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
995 && callingGroupId == targetGroupId);
996 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100997 checkManageUsersPermission("get the icon of a user who is not related");
998 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100999
1000 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001001 return null;
1002 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001003 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001004 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001005
1006 try {
1007 return ParcelFileDescriptor.open(
1008 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
1009 } catch (FileNotFoundException e) {
1010 Log.e(LOG_TAG, "Couldn't find icon file", e);
1011 }
1012 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -07001013 }
1014
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001015 public void makeInitialized(int userId) {
1016 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001017 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001018 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001019 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001020 userData = mUsers.get(userId);
1021 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001022 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001023 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001024 }
Amith Yamasani12747872015-12-07 14:19:49 -08001025 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1026 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001027 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001028 }
1029 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001030 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001031 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001032 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001033 }
1034
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001035 /**
1036 * If default guest restrictions haven't been initialized yet, add the basic
1037 * restrictions.
1038 */
1039 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001040 synchronized (mGuestRestrictions) {
1041 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001042 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001043 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001044 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1045 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1046 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001047 }
1048 }
1049
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001050 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301051 public Bundle getDefaultGuestRestrictions() {
1052 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001053 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301054 return new Bundle(mGuestRestrictions);
1055 }
1056 }
1057
1058 @Override
1059 public void setDefaultGuestRestrictions(Bundle restrictions) {
1060 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001061 synchronized (mGuestRestrictions) {
1062 mGuestRestrictions.clear();
1063 mGuestRestrictions.putAll(restrictions);
1064 }
1065 synchronized (mPackagesLock) {
1066 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301067 }
1068 }
1069
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001070 /**
1071 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1072 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001073 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001074 @Nullable Bundle global) {
1075 Preconditions.checkNotNull(local);
1076 boolean globalChanged = false;
1077 boolean localChanged;
1078 synchronized (mRestrictionsLock) {
1079 if (global != null) {
1080 // Update global.
1081 globalChanged = !UserRestrictionsUtils.areEqual(
1082 mDevicePolicyGlobalUserRestrictions, global);
1083 if (globalChanged) {
1084 mDevicePolicyGlobalUserRestrictions = global;
1085 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001086 // Remember the global restriction owner userId to be able to make a distinction
1087 // in getUserRestrictionSource on who set local policies.
1088 mGlobalRestrictionOwnerUserId = userId;
1089 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001090 if (mGlobalRestrictionOwnerUserId == userId) {
1091 // When profile owner sets restrictions it passes null global bundle and we
1092 // reset global restriction owner userId.
1093 // This means this user used to have DO, but now the DO is gone and the user
1094 // instead has PO.
1095 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1096 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001097 }
1098 {
1099 // Update local.
1100 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1101 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1102 if (localChanged) {
1103 mDevicePolicyLocalUserRestrictions.put(userId, local);
1104 }
1105 }
1106 }
1107 if (DBG) {
1108 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1109 + " global=" + global + (globalChanged ? " (changed)" : "")
1110 + " local=" + local + (localChanged ? " (changed)" : "")
1111 );
1112 }
1113 // Don't call them within the mRestrictionsLock.
1114 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001115 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001116 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001117 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001118 if (globalChanged) {
1119 writeUserListLP();
1120 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001121 }
1122
1123 synchronized (mRestrictionsLock) {
1124 if (globalChanged) {
1125 applyUserRestrictionsForAllUsersLR();
1126 } else if (localChanged) {
1127 applyUserRestrictionsLR(userId);
1128 }
1129 }
1130 }
1131
Makoto Onuki068c54a2015-10-13 14:34:03 -07001132 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001133 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001134 final Bundle baseRestrictions =
1135 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1136 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1137 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001138
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001139 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1140 // Common case first.
1141 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001142 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001143 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1144 UserRestrictionsUtils.merge(effective, global);
1145 UserRestrictionsUtils.merge(effective, local);
1146
Makoto Onuki068c54a2015-10-13 14:34:03 -07001147 return effective;
1148 }
1149
1150 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001151 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001152 if (DBG) {
1153 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1154 }
1155 mCachedEffectiveUserRestrictions.remove(userId);
1156 }
1157
1158 private Bundle getEffectiveUserRestrictions(int userId) {
1159 synchronized (mRestrictionsLock) {
1160 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1161 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001162 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001163 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1164 }
1165 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001166 }
1167 }
1168
Makoto Onuki068c54a2015-10-13 14:34:03 -07001169 /** @return a specific user restriction that's in effect currently. */
1170 @Override
1171 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001172 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1173 return false;
1174 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001175 Bundle restrictions = getEffectiveUserRestrictions(userId);
1176 return restrictions != null && restrictions.getBoolean(restrictionKey);
1177 }
1178
1179 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001180 * @hide
1181 *
1182 * Returns who set a user restriction on a user.
1183 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1184 * @param restrictionKey the string key representing the restriction
1185 * @param userId the id of the user for whom to retrieve the restrictions.
1186 * @return The source of user restriction. Any combination of
1187 * {@link UserManager#RESTRICTION_NOT_SET},
1188 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1189 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1190 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1191 */
1192 @Override
1193 public int getUserRestrictionSource(String restrictionKey, int userId) {
1194 checkManageUsersPermission("getUserRestrictionSource");
1195 int result = UserManager.RESTRICTION_NOT_SET;
1196
1197 // Shortcut for the most common case
1198 if (!hasUserRestriction(restrictionKey, userId)) {
1199 return result;
1200 }
1201
1202 if (hasBaseUserRestriction(restrictionKey, userId)) {
1203 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1204 }
1205
1206 synchronized(mRestrictionsLock) {
1207 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1208 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1209 && localRestrictions.getBoolean(restrictionKey)) {
1210 // Local restrictions may have been set by device owner the userId of which is
1211 // stored in mGlobalRestrictionOwnerUserId.
1212 if (mGlobalRestrictionOwnerUserId == userId) {
1213 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1214 } else {
1215 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1216 }
1217 }
1218 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1219 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1220 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1221 }
1222 }
1223
1224 return result;
1225 }
1226
1227 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001228 * @return UserRestrictions that are in effect currently. This always returns a new
1229 * {@link Bundle}.
1230 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001231 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001232 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001233 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001234 }
1235
1236 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001237 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1238 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001239 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1240 return false;
1241 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001242 synchronized (mRestrictionsLock) {
1243 Bundle bundle = mBaseUserRestrictions.get(userId);
1244 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1245 }
1246 }
1247
1248 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001249 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001250 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001251 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1252 return;
1253 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001254 synchronized (mRestrictionsLock) {
1255 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1256 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001257 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1258 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001259 newRestrictions.putBoolean(key, value);
1260
Fyodor Kupolov82402752015-10-28 14:54:51 -07001261 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001262 }
1263 }
1264
Makoto Onuki068c54a2015-10-13 14:34:03 -07001265 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001266 * Optionally updating user restrictions, calculate the effective user restrictions and also
1267 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001268 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001269 * @param newRestrictions User restrictions to set.
1270 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001271 * @param userId target user ID.
1272 */
1273 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001274 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001275 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001276
1277 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1278 mAppliedUserRestrictions.get(userId));
1279
1280 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001281 if (newRestrictions != null) {
1282 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001283 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1284
1285 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001286 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1287 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001288
1289 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1290 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001291 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001292 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001293 }
1294
Fyodor Kupolov82402752015-10-28 14:54:51 -07001295 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001296
Makoto Onuki759a7632015-10-28 16:43:10 -07001297 mCachedEffectiveUserRestrictions.put(userId, effective);
1298
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001299 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001300 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001301 debug("Applying user restrictions: userId=" + userId
1302 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001303 }
1304
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001305 if (mAppOpsService != null) { // We skip it until system-ready.
Fyodor Kupolovec30ca32016-06-16 15:09:29 -07001306 mHandler.post(new Runnable() {
1307 @Override
1308 public void run() {
1309 try {
1310 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
1311 } catch (RemoteException e) {
1312 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1313 }
1314 }
1315 });
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001316 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001317
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001318 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001319
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001320 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001321 }
1322
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001323 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001324 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001325 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1326 // actually, but we still need some kind of synchronization otherwise we might end up
1327 // calling listeners out-of-order, thus "LR".
1328
1329 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1330 return;
1331 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001332
1333 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1334 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1335
1336 mHandler.post(new Runnable() {
1337 @Override
1338 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001339 UserRestrictionsUtils.applyUserRestrictions(
1340 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001341
Makoto Onukid45a4a22015-11-02 17:17:38 -08001342 final UserRestrictionsListener[] listeners;
1343 synchronized (mUserRestrictionsListeners) {
1344 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1345 mUserRestrictionsListeners.toArray(listeners);
1346 }
1347 for (int i = 0; i < listeners.length; i++) {
1348 listeners[i].onUserRestrictionsChanged(userId,
1349 newRestrictionsFinal, prevRestrictionsFinal);
1350 }
1351 }
1352 });
1353 }
1354
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001355 // Package private for the inner class.
1356 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001357 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001358 }
1359
1360 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001361 // Package private for the inner class.
1362 void applyUserRestrictionsForAllUsersLR() {
1363 if (DBG) {
1364 debug("applyUserRestrictionsForAllUsersLR");
1365 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001366 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001367 mCachedEffectiveUserRestrictions.clear();
1368
Makoto Onuki068c54a2015-10-13 14:34:03 -07001369 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1370 // it on a handler.
1371 final Runnable r = new Runnable() {
1372 @Override
1373 public void run() {
1374 // Then get the list of running users.
1375 final int[] runningUsers;
1376 try {
1377 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1378 } catch (RemoteException e) {
1379 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1380 return;
1381 }
1382 // Then re-calculate the effective restrictions and apply, only for running users.
1383 // It's okay if a new user has started after the getRunningUserIds() call,
1384 // because we'll do the same thing (re-calculate the restrictions and apply)
1385 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001386 synchronized (mRestrictionsLock) {
1387 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001388 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001389 }
1390 }
1391 }
1392 };
1393 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001394 }
1395
Amith Yamasani258848d2012-08-10 17:06:33 -07001396 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001397 * Check if we've hit the limit of how many users can be created.
1398 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001399 private boolean isUserLimitReached() {
1400 int count;
1401 synchronized (mUsersLock) {
1402 count = getAliveUsersExcludingGuestsCountLU();
1403 }
1404 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001405 }
1406
1407 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001408 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001409 checkManageUsersPermission("check if more managed profiles can be added.");
1410 if (ActivityManager.isLowRamDeviceStatic()) {
1411 return false;
1412 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001413 if (!mContext.getPackageManager().hasSystemFeature(
1414 PackageManager.FEATURE_MANAGED_USERS)) {
1415 return false;
1416 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001417 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001418 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1419 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1420 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001421 return false;
1422 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001423 synchronized(mUsersLock) {
1424 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001425 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001426 return false;
1427 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001428 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1429 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001430 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001431 return usersCountAfterRemoving == 1
1432 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001433 }
1434 }
1435
Fyodor Kupolov82402752015-10-28 14:54:51 -07001436 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001437 int aliveUserCount = 0;
1438 final int totalUserCount = mUsers.size();
1439 // Skip over users being removed
1440 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001441 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001442 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001443 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001444 aliveUserCount++;
1445 }
1446 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001447 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001448 }
1449
1450 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001451 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001452 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1453 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1454 * permissions can make certain calls to the UserManager.
1455 *
1456 * @param message used as message if SecurityException is thrown
1457 * @throws SecurityException if the caller does not have enough privilege.
1458 */
1459 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1460 final int uid = Binder.getCallingUid();
1461 if (uid != Process.SYSTEM_UID && uid != 0
1462 && ActivityManager.checkComponentPermission(
1463 Manifest.permission.MANAGE_USERS,
1464 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1465 && ActivityManager.checkComponentPermission(
1466 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1467 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1468 throw new SecurityException(
1469 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1470 + message);
1471 }
1472 }
1473
1474 /**
1475 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001476 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001477 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001478 *
1479 * @param message used as message if SecurityException is thrown
1480 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001481 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001482 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001483 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001484 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001485 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1486 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001487 }
1488
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001489 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001490 * Enforces that only the system UID or root's UID or apps that have the
1491 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1492 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1493 * can make certain calls to the UserManager.
1494 *
1495 * @param message used as message if SecurityException is thrown
1496 * @throws SecurityException if the caller is not system or root
1497 * @see #hasManageOrCreateUsersPermission()
1498 */
1499 private static final void checkManageOrCreateUsersPermission(String message) {
1500 if (!hasManageOrCreateUsersPermission()) {
1501 throw new SecurityException(
1502 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1503 }
1504 }
1505
1506 /**
1507 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1508 * to create user/profiles other than what is allowed for
1509 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1510 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1511 */
1512 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1513 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1514 if (!hasManageOrCreateUsersPermission()) {
1515 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1516 + "permission to create an user with flags: " + creationFlags);
1517 }
1518 } else if (!hasManageUsersPermission()) {
1519 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1520 + " with flags: " + creationFlags);
1521 }
1522 }
1523
1524 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001525 * @return whether the calling UID is system UID or root's UID or the calling app has the
1526 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1527 */
1528 private static final boolean hasManageUsersPermission() {
1529 final int callingUid = Binder.getCallingUid();
1530 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1531 || callingUid == Process.ROOT_UID
1532 || ActivityManager.checkComponentPermission(
1533 android.Manifest.permission.MANAGE_USERS,
1534 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1535 }
1536
1537 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001538 * @return whether the calling UID is system UID or root's UID or the calling app has the
1539 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1540 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1541 */
1542 private static final boolean hasManageOrCreateUsersPermission() {
1543 final int callingUid = Binder.getCallingUid();
1544 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1545 || callingUid == Process.ROOT_UID
1546 || ActivityManager.checkComponentPermission(
1547 android.Manifest.permission.MANAGE_USERS,
1548 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1549 || ActivityManager.checkComponentPermission(
1550 android.Manifest.permission.CREATE_USERS,
1551 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1552 }
1553
1554 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001555 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1556 * UserManager.
1557 *
1558 * @param message used as message if SecurityException is thrown
1559 * @throws SecurityException if the caller is not system or root
1560 */
1561 private static void checkSystemOrRoot(String message) {
1562 final int uid = Binder.getCallingUid();
1563 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1564 throw new SecurityException("Only system may: " + message);
1565 }
1566 }
1567
Fyodor Kupolov82402752015-10-28 14:54:51 -07001568 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001569 try {
1570 File dir = new File(mUsersDir, Integer.toString(info.id));
1571 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001572 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001573 if (!dir.exists()) {
1574 dir.mkdir();
1575 FileUtils.setPermissions(
1576 dir.getPath(),
1577 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1578 -1, -1);
1579 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001580 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001581 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001582 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001583 info.iconPath = file.getAbsolutePath();
1584 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001585 try {
1586 os.close();
1587 } catch (IOException ioe) {
1588 // What the ... !
1589 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001590 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001591 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001592 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001593 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001594 }
1595
Amith Yamasani0b285492011-04-14 17:35:23 -07001596 /**
1597 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1598 * cache it elsewhere.
1599 * @return the array of user ids.
1600 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001601 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001602 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001603 return mUserIds;
1604 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001605 }
1606
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001607 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001608 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001609 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001610 return;
1611 }
1612 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001613 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001614 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001615 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001616 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001617 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001618 int type;
1619 while ((type = parser.next()) != XmlPullParser.START_TAG
1620 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001621 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001622 }
1623
1624 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001625 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001626 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001627 return;
1628 }
1629
Amith Yamasani2a003292012-08-14 18:25:45 -07001630 mNextSerialNumber = -1;
1631 if (parser.getName().equals(TAG_USERS)) {
1632 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1633 if (lastSerialNumber != null) {
1634 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1635 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001636 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1637 if (versionNumber != null) {
1638 mUserVersion = Integer.parseInt(versionNumber);
1639 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001640 }
1641
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1643
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001644 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301645 if (type == XmlPullParser.START_TAG) {
1646 final String name = parser.getName();
1647 if (name.equals(TAG_USER)) {
1648 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001649
Amith Yamasani12747872015-12-07 14:19:49 -08001650 UserData userData = readUserLP(Integer.parseInt(id));
1651
1652 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001653 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001654 mUsers.put(userData.info.id, userData);
1655 if (mNextSerialNumber < 0
1656 || mNextSerialNumber <= userData.info.id) {
1657 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001658 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301659 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001660 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301661 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001662 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1663 && type != XmlPullParser.END_TAG) {
1664 if (type == XmlPullParser.START_TAG) {
1665 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001666 synchronized (mGuestRestrictions) {
1667 UserRestrictionsUtils
1668 .readRestrictions(parser, mGuestRestrictions);
1669 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1671 ) {
1672 UserRestrictionsUtils.readRestrictions(parser,
1673 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001674 }
1675 break;
1676 }
1677 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001678 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1679 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1680 if (ownerUserId != null) {
1681 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1682 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001683 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001684 }
1685 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 synchronized (mRestrictionsLock) {
1687 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1688 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001689 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001690 upgradeIfNecessaryLP();
1691 } catch (IOException | XmlPullParserException e) {
1692 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001693 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001694 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001695 }
1696 }
1697
Amith Yamasani6f34b412012-10-22 18:19:27 -07001698 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001699 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001700 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001701 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001703 int userVersion = mUserVersion;
1704 if (userVersion < 1) {
1705 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001706 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1707 if ("Primary".equals(userData.info.name)) {
1708 userData.info.name =
1709 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1710 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001711 }
1712 userVersion = 1;
1713 }
1714
Amith Yamasanibc9625052012-11-15 14:39:18 -08001715 if (userVersion < 2) {
1716 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001717 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1718 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1719 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1720 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001721 }
1722 userVersion = 2;
1723 }
1724
Amith Yamasani350962c2013-08-06 11:18:53 -07001725
Amith Yamasani5e486f52013-08-07 11:06:44 -07001726 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001727 userVersion = 4;
1728 }
1729
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001730 if (userVersion < 5) {
1731 initDefaultGuestRestrictions();
1732 userVersion = 5;
1733 }
1734
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001735 if (userVersion < 6) {
1736 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001737 synchronized (mUsersLock) {
1738 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001739 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001740 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001741 if (!splitSystemUser && userData.info.isRestricted()
1742 && (userData.info.restrictedProfileParentId
1743 == UserInfo.NO_PROFILE_GROUP_ID)) {
1744 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1745 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001746 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001747 }
1748 }
1749 userVersion = 6;
1750 }
1751
Amith Yamasani6f34b412012-10-22 18:19:27 -07001752 if (userVersion < USER_VERSION) {
1753 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1754 + USER_VERSION);
1755 } else {
1756 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001757
1758 if (originalVersion < mUserVersion) {
1759 writeUserListLP();
1760 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001761 }
1762 }
1763
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001764 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001765 int flags = UserInfo.FLAG_INITIALIZED;
1766 // In split system user mode, the admin and primary flags are assigned to the first human
1767 // user.
1768 if (!UserManager.isSplitSystemUser()) {
1769 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1770 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001771 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001772 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001773 UserData userData = new UserData();
1774 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001775 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001776 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001777 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001778 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001779 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001780
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001781 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001782 synchronized (mRestrictionsLock) {
1783 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1784 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001785
Fyodor Kupolov82402752015-10-28 14:54:51 -07001786 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001787 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001788
Amith Yamasani12747872015-12-07 14:19:49 -08001789 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001790 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001791 }
1792
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001793 private String getOwnerName() {
1794 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1795 }
1796
Amith Yamasani12747872015-12-07 14:19:49 -08001797 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001798 if (DBG) {
1799 debug("scheduleWriteUser");
1800 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001801 // No need to wrap it within a lock -- worst case, we'll just post the same message
1802 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001803 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1804 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001805 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1806 }
1807 }
1808
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001809 /*
1810 * Writes the user file in this format:
1811 *
1812 * <user flags="20039023" id="0">
1813 * <name>Primary</name>
1814 * </user>
1815 */
Amith Yamasani12747872015-12-07 14:19:49 -08001816 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001817 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001818 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001819 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001820 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001821 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001822 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001823 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001824 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1825
1826 // XmlSerializer serializer = XmlUtils.serializerInstance();
1827 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001828 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001829 serializer.startDocument(null, true);
1830 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1831
Amith Yamasani12747872015-12-07 14:19:49 -08001832 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001833 serializer.startTag(null, TAG_USER);
1834 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001835 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001836 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001837 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1838 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1839 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001840 if (userInfo.lastLoggedInFingerprint != null) {
1841 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1842 userInfo.lastLoggedInFingerprint);
1843 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001844 if (userInfo.iconPath != null) {
1845 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1846 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001847 if (userInfo.partial) {
1848 serializer.attribute(null, ATTR_PARTIAL, "true");
1849 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001850 if (userInfo.guestToRemove) {
1851 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1852 }
Kenny Guy2a764942014-04-02 13:29:20 +01001853 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1854 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1855 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001856 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001857 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1858 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1859 Integer.toString(userInfo.restrictedProfileParentId));
1860 }
Amith Yamasani12747872015-12-07 14:19:49 -08001861 // Write seed data
1862 if (userData.persistSeedData) {
1863 if (userData.seedAccountName != null) {
1864 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1865 }
1866 if (userData.seedAccountType != null) {
1867 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1868 }
1869 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001870 if (userInfo.name != null) {
1871 serializer.startTag(null, TAG_NAME);
1872 serializer.text(userInfo.name);
1873 serializer.endTag(null, TAG_NAME);
1874 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001875 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001876 UserRestrictionsUtils.writeRestrictions(serializer,
1877 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1878 UserRestrictionsUtils.writeRestrictions(serializer,
1879 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1880 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001881 }
Amith Yamasani12747872015-12-07 14:19:49 -08001882
1883 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001884 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001885 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001886 serializer.endTag(null, TAG_ACCOUNT);
1887 }
1888
Amith Yamasani12747872015-12-07 14:19:49 -08001889 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1890 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1891 userData.seedAccountOptions.saveToXml(serializer);
1892 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1893 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001894 serializer.endTag(null, TAG_USER);
1895
1896 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001897 userFile.finishWrite(fos);
1898 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001899 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001900 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001901 }
1902 }
1903
1904 /*
1905 * Writes the user list file in this format:
1906 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001907 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001908 * <user id="0"></user>
1909 * <user id="2"></user>
1910 * </users>
1911 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001912 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001913 if (DBG) {
1914 debug("writeUserList");
1915 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001916 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001917 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001918 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001919 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001920 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1921
1922 // XmlSerializer serializer = XmlUtils.serializerInstance();
1923 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001924 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001925 serializer.startDocument(null, true);
1926 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1927
1928 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001929 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001930 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001931
Adam Lesinskieddeb492014-09-08 17:50:03 -07001932 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001933 synchronized (mGuestRestrictions) {
1934 UserRestrictionsUtils
1935 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1936 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301937 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001938 synchronized (mRestrictionsLock) {
1939 UserRestrictionsUtils.writeRestrictions(serializer,
1940 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1941 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001942 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1943 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1944 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001945 int[] userIdsToWrite;
1946 synchronized (mUsersLock) {
1947 userIdsToWrite = new int[mUsers.size()];
1948 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001949 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001950 userIdsToWrite[i] = user.id;
1951 }
1952 }
1953 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001954 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001955 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001956 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001957 }
1958
1959 serializer.endTag(null, TAG_USERS);
1960
1961 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001962 userListFile.finishWrite(fos);
1963 } catch (Exception e) {
1964 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001965 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001966 }
1967 }
1968
Amith Yamasani12747872015-12-07 14:19:49 -08001969 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001970 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001971 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001972 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001973 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001974 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001975 long creationTime = 0L;
1976 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001977 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001978 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001979 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001980 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001981 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001982 boolean persistSeedData = false;
1983 String seedAccountName = null;
1984 String seedAccountType = null;
1985 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001986 Bundle baseRestrictions = new Bundle();
1987 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001988
1989 FileInputStream fis = null;
1990 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001991 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001992 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001993 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001994 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001995 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001996 int type;
1997 while ((type = parser.next()) != XmlPullParser.START_TAG
1998 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001999 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002000 }
2001
2002 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002003 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002004 return null;
2005 }
2006
2007 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002008 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2009 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002010 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002011 return null;
2012 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002013 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2014 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002015 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002016 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2017 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002018 lastLoggedInFingerprint = parser.getAttributeValue(null,
2019 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002020 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2021 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002022 restrictedProfileParentId = readIntAttribute(parser,
2023 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002024 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2025 if ("true".equals(valueString)) {
2026 partial = true;
2027 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002028 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2029 if ("true".equals(valueString)) {
2030 guestToRemove = true;
2031 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002032
Amith Yamasani12747872015-12-07 14:19:49 -08002033 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2034 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2035 if (seedAccountName != null || seedAccountType != null) {
2036 persistSeedData = true;
2037 }
2038
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002039 int outerDepth = parser.getDepth();
2040 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2041 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2042 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2043 continue;
2044 }
2045 String tag = parser.getName();
2046 if (TAG_NAME.equals(tag)) {
2047 type = parser.next();
2048 if (type == XmlPullParser.TEXT) {
2049 name = parser.getText();
2050 }
2051 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002052 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2053 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2054 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002055 } else if (TAG_ACCOUNT.equals(tag)) {
2056 type = parser.next();
2057 if (type == XmlPullParser.TEXT) {
2058 account = parser.getText();
2059 }
Amith Yamasani12747872015-12-07 14:19:49 -08002060 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2061 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2062 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002063 }
2064 }
2065 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002066
Amith Yamasani12747872015-12-07 14:19:49 -08002067 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002068 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002069 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002070 userInfo.creationTime = creationTime;
2071 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002072 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002073 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002074 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002075 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002076 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002077
2078 // Create the UserData object that's internal to this class
2079 UserData userData = new UserData();
2080 userData.info = userInfo;
2081 userData.account = account;
2082 userData.seedAccountName = seedAccountName;
2083 userData.seedAccountType = seedAccountType;
2084 userData.persistSeedData = persistSeedData;
2085 userData.seedAccountOptions = seedAccountOptions;
2086
Makoto Onuki068c54a2015-10-13 14:34:03 -07002087 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002088 mBaseUserRestrictions.put(id, baseRestrictions);
2089 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002090 }
Amith Yamasani12747872015-12-07 14:19:49 -08002091 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002092 } catch (IOException ioe) {
2093 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002094 } finally {
2095 if (fis != null) {
2096 try {
2097 fis.close();
2098 } catch (IOException e) {
2099 }
2100 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002101 }
2102 return null;
2103 }
2104
Amith Yamasani920ace02012-09-20 22:15:37 -07002105 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2106 String valueString = parser.getAttributeValue(null, attr);
2107 if (valueString == null) return defaultValue;
2108 try {
2109 return Integer.parseInt(valueString);
2110 } catch (NumberFormatException nfe) {
2111 return defaultValue;
2112 }
2113 }
2114
2115 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2116 String valueString = parser.getAttributeValue(null, attr);
2117 if (valueString == null) return defaultValue;
2118 try {
2119 return Long.parseLong(valueString);
2120 } catch (NumberFormatException nfe) {
2121 return defaultValue;
2122 }
2123 }
2124
Amith Yamasanib82add22013-07-09 11:24:44 -07002125 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002126 * Removes the app restrictions file for a specific package and user id, if it exists.
2127 */
2128 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2129 synchronized (mPackagesLock) {
2130 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002131 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002132 if (resFile.exists()) {
2133 resFile.delete();
2134 }
2135 }
2136 }
2137
Kenny Guya52dc3e2014-02-11 15:33:14 +00002138 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002139 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002140 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002141 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002142 }
2143
Amith Yamasani258848d2012-08-10 17:06:33 -07002144 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002145 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002146 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002147 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002148 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002149
Jessica Hummelbe81c802014-04-22 15:49:22 +01002150 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002151 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002152 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2153 return null;
2154 }
phweisse9c44062016-02-10 12:57:38 +01002155 return createUserInternalUnchecked(name, flags, parentId);
2156 }
2157
2158 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002159 if (ActivityManager.isLowRamDeviceStatic()) {
2160 return null;
2161 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002162 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002163 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002164 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002165 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002166 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002167 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002168 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002169 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002170 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002171 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002172 if (parentId != UserHandle.USER_NULL) {
2173 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002174 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002175 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002176 if (parent == null) return null;
2177 }
2178 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2179 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2180 return null;
2181 }
2182 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
2183 // If we're not adding a guest user or a managed profile and the limit has
2184 // been reached, cannot add a user.
2185 return null;
2186 }
2187 // If we're adding a guest and there already exists one, bail.
2188 if (isGuest && findCurrentGuestUser() != null) {
2189 return null;
2190 }
2191 // In legacy mode, restricted profile's parent can only be the owner user
2192 if (isRestricted && !UserManager.isSplitSystemUser()
2193 && (parentId != UserHandle.USER_SYSTEM)) {
2194 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2195 return null;
2196 }
2197 if (isRestricted && UserManager.isSplitSystemUser()) {
2198 if (parent == null) {
2199 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2200 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002201 return null;
2202 }
Amith Yamasani12747872015-12-07 14:19:49 -08002203 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002204 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2205 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002206 return null;
2207 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002208 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01002209 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
2210 Log.e(LOG_TAG,
2211 "Ephemeral users are supported on split-system-user systems only.");
2212 return null;
2213 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002214 // In split system user mode, we assign the first human user the primary flag.
2215 // And if there is no device owner, we also assign the admin flag to primary user.
2216 if (UserManager.isSplitSystemUser()
2217 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2218 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002219 synchronized (mUsersLock) {
2220 if (!mIsDeviceManaged) {
2221 flags |= UserInfo.FLAG_ADMIN;
2222 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002223 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002224 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002225
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002226 userId = getNextAvailableId();
2227 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002228 boolean ephemeralGuests = Resources.getSystem()
2229 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002230
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002231 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002232 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2233 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2234 || (parent != null && parent.info.isEphemeral())) {
2235 flags |= UserInfo.FLAG_EPHEMERAL;
2236 }
2237
2238 userInfo = new UserInfo(userId, name, null, flags);
2239 userInfo.serialNumber = mNextSerialNumber++;
2240 long now = System.currentTimeMillis();
2241 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2242 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002243 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002244 userData = new UserData();
2245 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002246 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002247 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002248 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002249 writeUserListLP();
2250 if (parent != null) {
2251 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002252 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2253 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002254 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002255 }
Amith Yamasani12747872015-12-07 14:19:49 -08002256 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002257 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002258 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2259 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002260 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002261 }
Amith Yamasani12747872015-12-07 14:19:49 -08002262 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002263 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002264 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002265 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002266 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002267 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002268 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002269 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002270 mPm.createNewUser(userId);
2271 userInfo.partial = false;
2272 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002273 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002274 }
2275 updateUserIds();
2276 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002277 if (isGuest) {
2278 synchronized (mGuestRestrictions) {
2279 restrictions.putAll(mGuestRestrictions);
2280 }
2281 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002282 synchronized (mRestrictionsLock) {
2283 mBaseUserRestrictions.append(userId, restrictions);
2284 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002285 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2286 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2287 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2288 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002289 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002290 } finally {
2291 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002292 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002293 return userInfo;
2294 }
2295
Amith Yamasani0b285492011-04-14 17:35:23 -07002296 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002297 * @hide
2298 */
Amith Yamasani12747872015-12-07 14:19:49 -08002299 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002300 public UserInfo createRestrictedProfile(String name, int parentUserId) {
Sudheer Shanka53d41472016-06-16 09:11:08 -07002301 checkManageOrCreateUsersPermission("setupRestrictedProfile");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002302 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2303 if (user == null) {
2304 return null;
2305 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002306 long identity = Binder.clearCallingIdentity();
2307 try {
2308 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2309 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2310 // the putIntForUser() will fail.
2311 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2312 android.provider.Settings.Secure.LOCATION_MODE,
2313 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2314 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2315 } finally {
2316 Binder.restoreCallingIdentity(identity);
2317 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002318 return user;
2319 }
2320
2321 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002322 * Find the current guest user. If the Guest user is partial,
2323 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002324 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002325 private UserInfo findCurrentGuestUser() {
2326 synchronized (mUsersLock) {
2327 final int size = mUsers.size();
2328 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002329 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002330 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2331 return user;
2332 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002333 }
2334 }
2335 return null;
2336 }
2337
2338 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002339 * Mark this guest user for deletion to allow us to create another guest
2340 * and switch to that user before actually removing this guest.
2341 * @param userHandle the userid of the current guest
2342 * @return whether the user could be marked for deletion
2343 */
Amith Yamasani12747872015-12-07 14:19:49 -08002344 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002345 public boolean markGuestForDeletion(int userHandle) {
2346 checkManageUsersPermission("Only the system can remove users");
2347 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2348 UserManager.DISALLOW_REMOVE_USER, false)) {
2349 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2350 return false;
2351 }
2352
2353 long ident = Binder.clearCallingIdentity();
2354 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002355 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002356 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002357 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002358 userData = mUsers.get(userHandle);
2359 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002360 return false;
2361 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002362 }
Amith Yamasani12747872015-12-07 14:19:49 -08002363 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002364 return false;
2365 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002366 // We set this to a guest user that is to be removed. This is a temporary state
2367 // where we are allowed to add new Guest users, even if this one is still not
2368 // removed. This user will still show up in getUserInfo() calls.
2369 // If we don't get around to removing this Guest user, it will be purged on next
2370 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002371 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002372 // Mark it as disabled, so that it isn't returned any more when
2373 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002374 userData.info.flags |= UserInfo.FLAG_DISABLED;
2375 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002376 }
2377 } finally {
2378 Binder.restoreCallingIdentity(ident);
2379 }
2380 return true;
2381 }
2382
2383 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002384 * Removes a user and all data directories created for that user. This method should be called
2385 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002386 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002387 */
Amith Yamasani12747872015-12-07 14:19:49 -08002388 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002389 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002390 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002391 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2392 UserManager.DISALLOW_REMOVE_USER, false)) {
2393 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2394 return false;
2395 }
2396
Kenny Guyee58b4f2014-05-23 15:19:53 +01002397 long ident = Binder.clearCallingIdentity();
2398 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002399 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002400 int currentUser = ActivityManager.getCurrentUser();
2401 if (currentUser == userHandle) {
2402 Log.w(LOG_TAG, "Current user cannot be removed");
2403 return false;
2404 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002405 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002406 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002407 userData = mUsers.get(userHandle);
2408 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002409 return false;
2410 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002411
Fyodor Kupolov82402752015-10-28 14:54:51 -07002412 // We remember deleted user IDs to prevent them from being
2413 // reused during the current boot; they can still be reused
2414 // after a reboot.
2415 mRemovingUserIds.put(userHandle, true);
2416 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002417
Kenny Guyee58b4f2014-05-23 15:19:53 +01002418 try {
2419 mAppOpsService.removeUser(userHandle);
2420 } catch (RemoteException e) {
2421 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2422 }
2423 // Set this to a partially created user, so that the user will be purged
2424 // on next startup, in case the runtime stops now before stopping and
2425 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002426 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002427 // Mark it as disabled, so that it isn't returned any more when
2428 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002429 userData.info.flags |= UserInfo.FLAG_DISABLED;
2430 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002431 }
2432
Amith Yamasani12747872015-12-07 14:19:49 -08002433 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2434 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002435 // Send broadcast to notify system that the user removed was a
2436 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002437 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002438 }
2439
2440 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2441 int res;
2442 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002443 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2444 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002445 @Override
2446 public void userStopped(int userId) {
2447 finishRemoveUser(userId);
2448 }
2449 @Override
2450 public void userStopAborted(int userId) {
2451 }
2452 });
2453 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002454 return false;
2455 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002456 return res == ActivityManager.USER_OP_SUCCESS;
2457 } finally {
2458 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002459 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002460 }
2461
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002462 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002463 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002464 // Let other services shutdown any activity and clean up their state before completely
2465 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002466 long ident = Binder.clearCallingIdentity();
2467 try {
2468 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2469 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002470 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2471 android.Manifest.permission.MANAGE_USERS,
2472
2473 new BroadcastReceiver() {
2474 @Override
2475 public void onReceive(Context context, Intent intent) {
2476 if (DBG) {
2477 Slog.i(LOG_TAG,
2478 "USER_REMOVED broadcast sent, cleaning up user data "
2479 + userHandle);
2480 }
2481 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002482 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002483 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002484 // Clean up any ActivityManager state
2485 LocalServices.getService(ActivityManagerInternal.class)
2486 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002487 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002488 }
2489 }.start();
2490 }
2491 },
2492
2493 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002494 } finally {
2495 Binder.restoreCallingIdentity(ident);
2496 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002497 }
2498
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002499 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002500 try {
2501 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2502 } catch (IllegalStateException e) {
2503 // This may be simply because the user was partially created.
2504 Slog.i(LOG_TAG,
2505 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2506 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002507
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002508 // Cleanup gatekeeper secure user id
2509 try {
2510 final IGateKeeperService gk = GateKeeper.getService();
2511 if (gk != null) {
2512 gk.clearSecureUserId(userHandle);
2513 }
2514 } catch (Exception ex) {
2515 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2516 }
2517
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002518 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002519 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002520
2521 // Clean up all data before removing metadata
2522 mPm.destroyUserData(userHandle,
2523 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2524
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002525 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002526 synchronized (mUsersLock) {
2527 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002528 mIsUserManaged.delete(userHandle);
Fyodor Kupolovac06a492016-05-25 14:45:29 -07002529 }
2530 synchronized (mUserStates) {
2531 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002532 }
2533 synchronized (mRestrictionsLock) {
2534 mBaseUserRestrictions.remove(userHandle);
2535 mAppliedUserRestrictions.remove(userHandle);
2536 mCachedEffectiveUserRestrictions.remove(userHandle);
2537 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002538 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002539 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002540 synchronized (mPackagesLock) {
2541 writeUserListLP();
2542 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002543 // Remove user file
2544 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2545 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002546 updateUserIds();
Amith Yamasani61f57372012-08-31 12:12:28 -07002547 }
2548
Kenny Guyf8d3a232014-05-15 16:09:52 +01002549 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002550 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002551 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2552 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002553 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002554 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002555 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002556 }
2557
Amith Yamasani2a003292012-08-14 18:25:45 -07002558 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002559 public Bundle getApplicationRestrictions(String packageName) {
2560 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2561 }
2562
2563 @Override
2564 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002565 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002566 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002567 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002568 }
2569 synchronized (mPackagesLock) {
2570 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002571 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002572 }
2573 }
2574
2575 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002576 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002577 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002578 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002579 if (restrictions != null) {
2580 restrictions.setDefusable(true);
2581 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002582 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002583 if (restrictions == null || restrictions.isEmpty()) {
2584 cleanAppRestrictionsForPackage(packageName, userId);
2585 } else {
2586 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002587 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002588 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002589 }
Robin Lee66e5d962014-04-09 16:44:21 +01002590
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002591 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2592 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2593 changeIntent.setPackage(packageName);
2594 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2595 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002596 }
2597
2598 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002599 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002600 try {
2601 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002602 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002603 } catch (NameNotFoundException nnfe) {
2604 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002605 } finally {
2606 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002607 }
2608 }
2609
Fyodor Kupolov82402752015-10-28 14:54:51 -07002610 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002611 AtomicFile restrictionsFile =
2612 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2613 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002614 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002615 }
2616
2617 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002618 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002619 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002620 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002621 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002622 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002623 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002624
2625 FileInputStream fis = null;
2626 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002627 fis = restrictionsFile.openRead();
2628 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002629 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002630 XmlUtils.nextElement(parser);
2631 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002632 Slog.e(LOG_TAG, "Unable to read restrictions file "
2633 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002634 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002635 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002636 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2637 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002638 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002639 } catch (IOException|XmlPullParserException e) {
2640 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002641 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002642 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002643 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002644 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002645 }
2646
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002647 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2648 XmlPullParser parser) throws XmlPullParserException, IOException {
2649 int type = parser.getEventType();
2650 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2651 String key = parser.getAttributeValue(null, ATTR_KEY);
2652 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2653 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2654 if (multiple != null) {
2655 values.clear();
2656 int count = Integer.parseInt(multiple);
2657 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2658 if (type == XmlPullParser.START_TAG
2659 && parser.getName().equals(TAG_VALUE)) {
2660 values.add(parser.nextText().trim());
2661 count--;
2662 }
2663 }
2664 String [] valueStrings = new String[values.size()];
2665 values.toArray(valueStrings);
2666 restrictions.putStringArray(key, valueStrings);
2667 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2668 restrictions.putBundle(key, readBundleEntry(parser, values));
2669 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2670 final int outerDepth = parser.getDepth();
2671 ArrayList<Bundle> bundleList = new ArrayList<>();
2672 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2673 Bundle childBundle = readBundleEntry(parser, values);
2674 bundleList.add(childBundle);
2675 }
2676 restrictions.putParcelableArray(key,
2677 bundleList.toArray(new Bundle[bundleList.size()]));
2678 } else {
2679 String value = parser.nextText().trim();
2680 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2681 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2682 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2683 restrictions.putInt(key, Integer.parseInt(value));
2684 } else {
2685 restrictions.putString(key, value);
2686 }
2687 }
2688 }
2689 }
2690
2691 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2692 throws IOException, XmlPullParserException {
2693 Bundle childBundle = new Bundle();
2694 final int outerDepth = parser.getDepth();
2695 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2696 readEntry(childBundle, values, parser);
2697 }
2698 return childBundle;
2699 }
2700
Fyodor Kupolov82402752015-10-28 14:54:51 -07002701 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002702 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002703 AtomicFile restrictionsFile = new AtomicFile(
2704 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002705 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002706 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002707 }
2708
2709 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002710 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002711 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002712 try {
2713 fos = restrictionsFile.startWrite();
2714 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2715
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002716 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002717 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002718 serializer.startDocument(null, true);
2719 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2720
2721 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002722 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002723 serializer.endTag(null, TAG_RESTRICTIONS);
2724
2725 serializer.endDocument();
2726 restrictionsFile.finishWrite(fos);
2727 } catch (Exception e) {
2728 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002729 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2730 }
2731 }
2732
2733 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2734 throws IOException {
2735 for (String key : restrictions.keySet()) {
2736 Object value = restrictions.get(key);
2737 serializer.startTag(null, TAG_ENTRY);
2738 serializer.attribute(null, ATTR_KEY, key);
2739
2740 if (value instanceof Boolean) {
2741 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2742 serializer.text(value.toString());
2743 } else if (value instanceof Integer) {
2744 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2745 serializer.text(value.toString());
2746 } else if (value == null || value instanceof String) {
2747 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2748 serializer.text(value != null ? (String) value : "");
2749 } else if (value instanceof Bundle) {
2750 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2751 writeBundle((Bundle) value, serializer);
2752 } else if (value instanceof Parcelable[]) {
2753 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2754 Parcelable[] array = (Parcelable[]) value;
2755 for (Parcelable parcelable : array) {
2756 if (!(parcelable instanceof Bundle)) {
2757 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2758 }
2759 serializer.startTag(null, TAG_ENTRY);
2760 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2761 writeBundle((Bundle) parcelable, serializer);
2762 serializer.endTag(null, TAG_ENTRY);
2763 }
2764 } else {
2765 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2766 String[] values = (String[]) value;
2767 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2768 for (String choice : values) {
2769 serializer.startTag(null, TAG_VALUE);
2770 serializer.text(choice != null ? choice : "");
2771 serializer.endTag(null, TAG_VALUE);
2772 }
2773 }
2774 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002775 }
2776 }
2777
2778 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002779 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002780 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002781 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002782 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002783 }
2784 }
2785
2786 @Override
2787 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002788 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002789 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002790 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002791 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002792 }
2793 // Not found
2794 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002795 }
2796 }
2797
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002798 @Override
2799 public long getUserCreationTime(int userHandle) {
2800 int callingUserId = UserHandle.getCallingUserId();
2801 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002802 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002803 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002804 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002805 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002806 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002807 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002808 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002809 }
2810 }
2811 }
2812 if (userInfo == null) {
2813 throw new SecurityException("userHandle can only be the calling user or a managed "
2814 + "profile associated with this user");
2815 }
2816 return userInfo.creationTime;
2817 }
2818
Amith Yamasani0b285492011-04-14 17:35:23 -07002819 /**
2820 * Caches the list of user ids in an array, adjusting the array size when necessary.
2821 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002822 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002823 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002824 synchronized (mUsersLock) {
2825 final int userSize = mUsers.size();
2826 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002827 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002828 num++;
2829 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002830 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002831 final int[] newUsers = new int[num];
2832 int n = 0;
2833 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002834 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002835 newUsers[n++] = mUsers.keyAt(i);
2836 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002837 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002838 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002839 }
2840 }
2841
2842 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002843 * Called right before a user is started. This gives us a chance to prepare
2844 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002845 */
2846 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002847 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002848 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002849 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002850
2851 if (userId != UserHandle.USER_SYSTEM) {
2852 synchronized (mRestrictionsLock) {
2853 applyUserRestrictionsLR(userId);
2854 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002855 UserInfo userInfo = getUserInfoNoChecks(userId);
2856 if (userInfo != null && !userInfo.isInitialized()) {
2857 mPm.onBeforeUserStartUninitialized(userId);
2858 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002859 }
2860 }
2861
2862 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002863 * Called right before a user is unlocked. This gives us a chance to prepare
2864 * app storage.
2865 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002866 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002867 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002868 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002869 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002870 }
2871
2872 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002873 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002874 * @param userId the user that was just foregrounded
2875 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002876 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002877 UserData userData = getUserDataNoChecks(userId);
2878 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002879 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2880 return;
2881 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002882
2883 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002884 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002885 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002886 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002887 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2888 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002889 }
2890
2891 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002892 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002893 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2894 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002895 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002896 private int getNextAvailableId() {
2897 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002898 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002899 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002900 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002901 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002902 }
2903 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002904 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002905 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002906 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002907 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002908
Amith Yamasanifc95e702013-09-26 13:20:17 -07002909 private String packageToRestrictionsFileName(String packageName) {
2910 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2911 }
2912
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002913 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002914 * Enforce that serial number stored in user directory inode matches the
2915 * given expected value. Gracefully sets the serial number if currently
2916 * undefined.
2917 *
2918 * @throws IOException when problem extracting serial number, or serial
2919 * number is mismatched.
2920 */
2921 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2922 final int foundSerial = getSerialNumber(file);
2923 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2924
2925 if (foundSerial == -1) {
2926 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2927 try {
2928 setSerialNumber(file, serialNumber);
2929 } catch (IOException e) {
2930 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2931 }
2932
2933 } else if (foundSerial != serialNumber) {
2934 throw new IOException("Found serial number " + foundSerial
2935 + " doesn't match expected " + serialNumber);
2936 }
2937 }
2938
2939 /**
2940 * Set serial number stored in user directory inode.
2941 *
2942 * @throws IOException if serial number was already set
2943 */
2944 private static void setSerialNumber(File file, int serialNumber)
2945 throws IOException {
2946 try {
2947 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2948 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2949 } catch (ErrnoException e) {
2950 throw e.rethrowAsIOException();
2951 }
2952 }
2953
2954 /**
2955 * Return serial number stored in user directory inode.
2956 *
2957 * @return parsed serial number, or -1 if not set
2958 */
2959 private static int getSerialNumber(File file) throws IOException {
2960 try {
2961 final byte[] buf = new byte[256];
2962 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2963 final String serial = new String(buf, 0, len);
2964 try {
2965 return Integer.parseInt(serial);
2966 } catch (NumberFormatException e) {
2967 throw new IOException("Bad serial number: " + serial);
2968 }
2969 } catch (ErrnoException e) {
2970 if (e.errno == OsConstants.ENODATA) {
2971 return -1;
2972 } else {
2973 throw e.rethrowAsIOException();
2974 }
2975 }
2976 }
2977
Amith Yamasani920ace02012-09-20 22:15:37 -07002978 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002979 public void setSeedAccountData(int userId, String accountName, String accountType,
2980 PersistableBundle accountOptions, boolean persist) {
2981 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2982 synchronized (mPackagesLock) {
2983 final UserData userData;
2984 synchronized (mUsersLock) {
2985 userData = getUserDataLU(userId);
2986 if (userData == null) {
2987 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2988 return;
2989 }
2990 userData.seedAccountName = accountName;
2991 userData.seedAccountType = accountType;
2992 userData.seedAccountOptions = accountOptions;
2993 userData.persistSeedData = persist;
2994 }
2995 if (persist) {
2996 writeUserLP(userData);
2997 }
2998 }
2999 }
3000
3001 @Override
3002 public String getSeedAccountName() throws RemoteException {
3003 checkManageUsersPermission("Cannot get seed account information");
3004 synchronized (mUsersLock) {
3005 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3006 return userData.seedAccountName;
3007 }
3008 }
3009
3010 @Override
3011 public String getSeedAccountType() throws RemoteException {
3012 checkManageUsersPermission("Cannot get seed account information");
3013 synchronized (mUsersLock) {
3014 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3015 return userData.seedAccountType;
3016 }
3017 }
3018
3019 @Override
3020 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3021 checkManageUsersPermission("Cannot get seed account information");
3022 synchronized (mUsersLock) {
3023 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3024 return userData.seedAccountOptions;
3025 }
3026 }
3027
3028 @Override
3029 public void clearSeedAccountData() throws RemoteException {
3030 checkManageUsersPermission("Cannot clear seed account information");
3031 synchronized (mPackagesLock) {
3032 UserData userData;
3033 synchronized (mUsersLock) {
3034 userData = getUserDataLU(UserHandle.getCallingUserId());
3035 if (userData == null) return;
3036 userData.clearSeedAccountData();
3037 }
3038 writeUserLP(userData);
3039 }
3040 }
3041
3042 @Override
3043 public boolean someUserHasSeedAccount(String accountName, String accountType)
3044 throws RemoteException {
3045 checkManageUsersPermission("Cannot check seed account information");
3046 synchronized (mUsersLock) {
3047 final int userSize = mUsers.size();
3048 for (int i = 0; i < userSize; i++) {
3049 final UserData data = mUsers.valueAt(i);
3050 if (data.info.isInitialized()) continue;
3051 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3052 continue;
3053 }
3054 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3055 continue;
3056 }
3057 return true;
3058 }
3059 }
3060 return false;
3061 }
3062
3063 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003064 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3065 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3066 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3067 }
3068
3069 int onShellCommand(Shell shell, String cmd) {
3070 if (cmd == null) {
3071 return shell.handleDefaultCommands(cmd);
3072 }
3073
3074 final PrintWriter pw = shell.getOutPrintWriter();
3075 try {
3076 switch(cmd) {
3077 case "list":
3078 return runList(pw);
3079 }
3080 } catch (RemoteException e) {
3081 pw.println("Remote exception: " + e);
3082 }
3083 return -1;
3084 }
3085
3086 private int runList(PrintWriter pw) throws RemoteException {
3087 final IActivityManager am = ActivityManagerNative.getDefault();
3088 final List<UserInfo> users = getUsers(false);
3089 if (users == null) {
3090 pw.println("Error: couldn't get users");
3091 return 1;
3092 } else {
3093 pw.println("Users:");
3094 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003095 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003096 pw.println("\t" + users.get(i).toString() + running);
3097 }
3098 return 0;
3099 }
3100 }
3101
3102 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003103 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3104 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3105 != PackageManager.PERMISSION_GRANTED) {
3106 pw.println("Permission Denial: can't dump UserManager from from pid="
3107 + Binder.getCallingPid()
3108 + ", uid=" + Binder.getCallingUid()
3109 + " without permission "
3110 + android.Manifest.permission.DUMP);
3111 return;
3112 }
3113
3114 long now = System.currentTimeMillis();
3115 StringBuilder sb = new StringBuilder();
3116 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003117 synchronized (mUsersLock) {
3118 pw.println("Users:");
3119 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003120 UserData userData = mUsers.valueAt(i);
3121 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003122 continue;
3123 }
Amith Yamasani12747872015-12-07 14:19:49 -08003124 UserInfo userInfo = userData.info;
3125 final int userId = userInfo.id;
3126 pw.print(" "); pw.print(userInfo);
3127 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003128 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003129 pw.print(" <removing> ");
3130 }
Amith Yamasani12747872015-12-07 14:19:49 -08003131 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003132 pw.print(" <partial>");
3133 }
3134 pw.println();
3135 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003136 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003137 pw.println("<unknown>");
3138 } else {
3139 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003140 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003141 sb.append(" ago");
3142 pw.println(sb);
3143 }
3144 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003145 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003146 pw.println("<unknown>");
3147 } else {
3148 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003149 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003150 sb.append(" ago");
3151 pw.println(sb);
3152 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003153 pw.print(" Last logged in fingerprint: ");
3154 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003155 pw.print(" Has profile owner: ");
3156 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003157 pw.println(" Restrictions:");
3158 synchronized (mRestrictionsLock) {
3159 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003160 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003161 pw.println(" Device policy local restrictions:");
3162 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003163 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003164 pw.println(" Effective restrictions:");
3165 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003166 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003167 }
Amith Yamasani12747872015-12-07 14:19:49 -08003168
3169 if (userData.account != null) {
3170 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003171 pw.println();
3172 }
Amith Yamasani12747872015-12-07 14:19:49 -08003173
3174 if (userData.seedAccountName != null) {
3175 pw.print(" Seed account name: " + userData.seedAccountName);
3176 pw.println();
3177 if (userData.seedAccountType != null) {
3178 pw.print(" account type: " + userData.seedAccountType);
3179 pw.println();
3180 }
3181 if (userData.seedAccountOptions != null) {
3182 pw.print(" account options exist");
3183 pw.println();
3184 }
3185 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003186 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003187 }
Amith Yamasani12747872015-12-07 14:19:49 -08003188 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003189 pw.println(" Device policy global restrictions:");
3190 synchronized (mRestrictionsLock) {
3191 UserRestrictionsUtils
3192 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3193 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003194 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003195 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3196 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003197 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003198 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003199 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003200 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003201 synchronized (mUsersLock) {
3202 pw.println();
3203 pw.println(" Device managed: " + mIsDeviceManaged);
3204 }
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003205 synchronized (mUserStates) {
3206 pw.println(" Started users state: " + mUserStates);
3207 }
Amith Yamasani12747872015-12-07 14:19:49 -08003208 // Dump some capabilities
3209 pw.println();
3210 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3211 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003212 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3213 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003214 }
3215 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003216
3217 final class MainHandler extends Handler {
3218
3219 @Override
3220 public void handleMessage(Message msg) {
3221 switch (msg.what) {
3222 case WRITE_USER_MSG:
3223 removeMessages(WRITE_USER_MSG, msg.obj);
3224 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003225 int userId = ((UserData) msg.obj).info.id;
3226 UserData userData = getUserDataNoChecks(userId);
3227 if (userData != null) {
3228 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003229 }
3230 }
3231 }
3232 }
3233 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003234
3235 /**
3236 * @param userId
3237 * @return whether the user has been initialized yet
3238 */
3239 boolean isInitialized(int userId) {
3240 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3241 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003242
3243 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003244 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003245 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3246 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003247 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003248 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003249 }
3250
3251 @Override
3252 public Bundle getBaseUserRestrictions(int userId) {
3253 synchronized (mRestrictionsLock) {
3254 return mBaseUserRestrictions.get(userId);
3255 }
3256 }
3257
3258 @Override
3259 public void setBaseUserRestrictionsByDpmsForMigration(
3260 int userId, Bundle baseRestrictions) {
3261 synchronized (mRestrictionsLock) {
3262 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003263 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003264 }
3265
Amith Yamasani12747872015-12-07 14:19:49 -08003266 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003267 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003268 if (userData != null) {
3269 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003270 } else {
3271 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3272 }
3273 }
3274 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003275
3276 @Override
3277 public boolean getUserRestriction(int userId, String key) {
3278 return getUserRestrictions(userId).getBoolean(key);
3279 }
3280
3281 @Override
3282 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3283 synchronized (mUserRestrictionsListeners) {
3284 mUserRestrictionsListeners.add(listener);
3285 }
3286 }
3287
3288 @Override
3289 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3290 synchronized (mUserRestrictionsListeners) {
3291 mUserRestrictionsListeners.remove(listener);
3292 }
3293 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003294
3295 @Override
3296 public void setDeviceManaged(boolean isManaged) {
3297 synchronized (mUsersLock) {
3298 mIsDeviceManaged = isManaged;
3299 }
3300 }
3301
3302 @Override
3303 public void setUserManaged(int userId, boolean isManaged) {
3304 synchronized (mUsersLock) {
3305 mIsUserManaged.put(userId, isManaged);
3306 }
3307 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003308
3309 @Override
3310 public void setUserIcon(int userId, Bitmap bitmap) {
3311 long ident = Binder.clearCallingIdentity();
3312 try {
3313 synchronized (mPackagesLock) {
3314 UserData userData = getUserDataNoChecks(userId);
3315 if (userData == null || userData.info.partial) {
3316 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3317 return;
3318 }
3319 writeBitmapLP(userData.info, bitmap);
3320 writeUserLP(userData);
3321 }
3322 sendUserInfoChangedBroadcast(userId);
3323 } finally {
3324 Binder.restoreCallingIdentity(ident);
3325 }
3326 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003327
3328 @Override
3329 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3330 synchronized (mUsersLock) {
3331 mForceEphemeralUsers = forceEphemeralUsers;
3332 }
3333 }
3334
3335 @Override
3336 public void removeAllUsers() {
3337 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3338 // Remove the non-system users straight away.
3339 removeNonSystemUsers();
3340 } else {
3341 // Switch to the system user first and then remove the other users.
3342 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3343 @Override
3344 public void onReceive(Context context, Intent intent) {
3345 int userId =
3346 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3347 if (userId != UserHandle.USER_SYSTEM) {
3348 return;
3349 }
3350 mContext.unregisterReceiver(this);
3351 removeNonSystemUsers();
3352 }
3353 };
3354 IntentFilter userSwitchedFilter = new IntentFilter();
3355 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3356 mContext.registerReceiver(
3357 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3358
3359 // Switch to the system user.
3360 ActivityManager am =
3361 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3362 am.switchUser(UserHandle.USER_SYSTEM);
3363 }
3364 }
phweisse9c44062016-02-10 12:57:38 +01003365
3366 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003367 public void onEphemeralUserStop(int userId) {
3368 synchronized (mUsersLock) {
3369 UserInfo userInfo = getUserInfoLU(userId);
3370 if (userInfo != null && userInfo.isEphemeral()) {
3371 // Do not allow switching back to the ephemeral user again as the user is going
3372 // to be deleted.
3373 userInfo.flags |= UserInfo.FLAG_DISABLED;
3374 if (userInfo.isGuest()) {
3375 // Indicate that the guest will be deleted after it stops.
3376 userInfo.guestToRemove = true;
3377 }
3378 }
3379 }
3380 }
3381
3382 @Override
phweisse9c44062016-02-10 12:57:38 +01003383 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3384 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3385 // Keep this in sync with UserManager.createUser
3386 if (user != null && !user.isAdmin()) {
3387 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3388 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3389 }
3390 return user;
3391 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003392
3393 @Override
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003394 public boolean isUserRunning(int userId) {
3395 synchronized (mUserStates) {
3396 return mUserStates.get(userId, -1) >= 0;
3397 }
3398 }
3399
3400 @Override
3401 public void setUserState(int userId, int userState) {
3402 synchronized (mUserStates) {
3403 mUserStates.put(userId, userState);
3404 }
3405 }
3406
3407 @Override
3408 public void removeUserState(int userId) {
3409 synchronized (mUserStates) {
3410 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003411 }
3412 }
3413
3414 @Override
3415 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003416 synchronized (mUserStates) {
3417 int state = mUserStates.get(userId, -1);
3418 return (state == UserState.STATE_RUNNING_UNLOCKING)
3419 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003420 }
3421 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003422 }
3423
3424 /* Remove all the users except of the system one. */
3425 private void removeNonSystemUsers() {
3426 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3427 synchronized (mUsersLock) {
3428 final int userSize = mUsers.size();
3429 for (int i = 0; i < userSize; i++) {
3430 UserInfo ui = mUsers.valueAt(i).info;
3431 if (ui.id != UserHandle.USER_SYSTEM) {
3432 usersToRemove.add(ui);
3433 }
3434 }
3435 }
3436 for (UserInfo ui: usersToRemove) {
3437 removeUser(ui.id);
3438 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003439 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003440
3441 private class Shell extends ShellCommand {
3442 @Override
3443 public int onCommand(String cmd) {
3444 return onShellCommand(this, cmd);
3445 }
3446
3447 @Override
3448 public void onHelp() {
3449 final PrintWriter pw = getOutPrintWriter();
3450 pw.println("User manager (user) commands:");
3451 pw.println(" help");
3452 pw.println(" Print this help text.");
3453 pw.println("");
3454 pw.println(" list");
3455 pw.println(" Prints all users on the system.");
3456 }
3457 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003458
3459 private static void debug(String message) {
3460 Log.d(LOG_TAG, message +
3461 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3462 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003463}