blob: a85064b70f22a6bd05d443c2b29612e359d4e6fe [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()) {
551 checkManageUsersPermission("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) {
Rubin Xuf8451b92016-04-01 15:50:58 +0100735 LocalServices.getService(ActivityManagerInternal.class)
736 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000737 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
738 } 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.
1306 final long token = Binder.clearCallingIdentity();
1307 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001308 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001309 } catch (RemoteException e) {
1310 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1311 } finally {
1312 Binder.restoreCallingIdentity(token);
1313 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001314 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001315
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001316 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001317
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001318 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001319 }
1320
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001321 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001322 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001323 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1324 // actually, but we still need some kind of synchronization otherwise we might end up
1325 // calling listeners out-of-order, thus "LR".
1326
1327 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1328 return;
1329 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001330
1331 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1332 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1333
1334 mHandler.post(new Runnable() {
1335 @Override
1336 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001337 UserRestrictionsUtils.applyUserRestrictions(
1338 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001339
Makoto Onukid45a4a22015-11-02 17:17:38 -08001340 final UserRestrictionsListener[] listeners;
1341 synchronized (mUserRestrictionsListeners) {
1342 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1343 mUserRestrictionsListeners.toArray(listeners);
1344 }
1345 for (int i = 0; i < listeners.length; i++) {
1346 listeners[i].onUserRestrictionsChanged(userId,
1347 newRestrictionsFinal, prevRestrictionsFinal);
1348 }
1349 }
1350 });
1351 }
1352
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001353 // Package private for the inner class.
1354 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001355 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001356 }
1357
1358 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001359 // Package private for the inner class.
1360 void applyUserRestrictionsForAllUsersLR() {
1361 if (DBG) {
1362 debug("applyUserRestrictionsForAllUsersLR");
1363 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001364 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001365 mCachedEffectiveUserRestrictions.clear();
1366
Makoto Onuki068c54a2015-10-13 14:34:03 -07001367 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1368 // it on a handler.
1369 final Runnable r = new Runnable() {
1370 @Override
1371 public void run() {
1372 // Then get the list of running users.
1373 final int[] runningUsers;
1374 try {
1375 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1376 } catch (RemoteException e) {
1377 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1378 return;
1379 }
1380 // Then re-calculate the effective restrictions and apply, only for running users.
1381 // It's okay if a new user has started after the getRunningUserIds() call,
1382 // because we'll do the same thing (re-calculate the restrictions and apply)
1383 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001384 synchronized (mRestrictionsLock) {
1385 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001386 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001387 }
1388 }
1389 }
1390 };
1391 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001392 }
1393
Amith Yamasani258848d2012-08-10 17:06:33 -07001394 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001395 * Check if we've hit the limit of how many users can be created.
1396 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001397 private boolean isUserLimitReached() {
1398 int count;
1399 synchronized (mUsersLock) {
1400 count = getAliveUsersExcludingGuestsCountLU();
1401 }
1402 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001403 }
1404
1405 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001406 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001407 checkManageUsersPermission("check if more managed profiles can be added.");
1408 if (ActivityManager.isLowRamDeviceStatic()) {
1409 return false;
1410 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001411 if (!mContext.getPackageManager().hasSystemFeature(
1412 PackageManager.FEATURE_MANAGED_USERS)) {
1413 return false;
1414 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001415 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001416 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1417 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1418 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001419 return false;
1420 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001421 synchronized(mUsersLock) {
1422 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001423 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001424 return false;
1425 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001426 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1427 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001428 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001429 return usersCountAfterRemoving == 1
1430 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001431 }
1432 }
1433
Fyodor Kupolov82402752015-10-28 14:54:51 -07001434 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001435 int aliveUserCount = 0;
1436 final int totalUserCount = mUsers.size();
1437 // Skip over users being removed
1438 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001439 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001440 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001441 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001442 aliveUserCount++;
1443 }
1444 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001445 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001446 }
1447
1448 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001449 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001450 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1451 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1452 * permissions can make certain calls to the UserManager.
1453 *
1454 * @param message used as message if SecurityException is thrown
1455 * @throws SecurityException if the caller does not have enough privilege.
1456 */
1457 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1458 final int uid = Binder.getCallingUid();
1459 if (uid != Process.SYSTEM_UID && uid != 0
1460 && ActivityManager.checkComponentPermission(
1461 Manifest.permission.MANAGE_USERS,
1462 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1463 && ActivityManager.checkComponentPermission(
1464 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1465 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1466 throw new SecurityException(
1467 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1468 + message);
1469 }
1470 }
1471
1472 /**
1473 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001474 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001475 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001476 *
1477 * @param message used as message if SecurityException is thrown
1478 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001479 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001480 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001481 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001482 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001483 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1484 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001485 }
1486
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001487 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001488 * Enforces that only the system UID or root's UID or apps that have the
1489 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1490 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1491 * can make certain calls to the UserManager.
1492 *
1493 * @param message used as message if SecurityException is thrown
1494 * @throws SecurityException if the caller is not system or root
1495 * @see #hasManageOrCreateUsersPermission()
1496 */
1497 private static final void checkManageOrCreateUsersPermission(String message) {
1498 if (!hasManageOrCreateUsersPermission()) {
1499 throw new SecurityException(
1500 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1501 }
1502 }
1503
1504 /**
1505 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1506 * to create user/profiles other than what is allowed for
1507 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1508 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1509 */
1510 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1511 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1512 if (!hasManageOrCreateUsersPermission()) {
1513 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1514 + "permission to create an user with flags: " + creationFlags);
1515 }
1516 } else if (!hasManageUsersPermission()) {
1517 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1518 + " with flags: " + creationFlags);
1519 }
1520 }
1521
1522 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001523 * @return whether the calling UID is system UID or root's UID or the calling app has the
1524 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1525 */
1526 private static final boolean hasManageUsersPermission() {
1527 final int callingUid = Binder.getCallingUid();
1528 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1529 || callingUid == Process.ROOT_UID
1530 || ActivityManager.checkComponentPermission(
1531 android.Manifest.permission.MANAGE_USERS,
1532 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1533 }
1534
1535 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001536 * @return whether the calling UID is system UID or root's UID or the calling app has the
1537 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1538 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1539 */
1540 private static final boolean hasManageOrCreateUsersPermission() {
1541 final int callingUid = Binder.getCallingUid();
1542 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1543 || callingUid == Process.ROOT_UID
1544 || ActivityManager.checkComponentPermission(
1545 android.Manifest.permission.MANAGE_USERS,
1546 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1547 || ActivityManager.checkComponentPermission(
1548 android.Manifest.permission.CREATE_USERS,
1549 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1550 }
1551
1552 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001553 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1554 * UserManager.
1555 *
1556 * @param message used as message if SecurityException is thrown
1557 * @throws SecurityException if the caller is not system or root
1558 */
1559 private static void checkSystemOrRoot(String message) {
1560 final int uid = Binder.getCallingUid();
1561 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1562 throw new SecurityException("Only system may: " + message);
1563 }
1564 }
1565
Fyodor Kupolov82402752015-10-28 14:54:51 -07001566 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001567 try {
1568 File dir = new File(mUsersDir, Integer.toString(info.id));
1569 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001570 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001571 if (!dir.exists()) {
1572 dir.mkdir();
1573 FileUtils.setPermissions(
1574 dir.getPath(),
1575 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1576 -1, -1);
1577 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001578 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001579 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001580 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001581 info.iconPath = file.getAbsolutePath();
1582 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001583 try {
1584 os.close();
1585 } catch (IOException ioe) {
1586 // What the ... !
1587 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001588 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001589 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001590 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001591 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001592 }
1593
Amith Yamasani0b285492011-04-14 17:35:23 -07001594 /**
1595 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1596 * cache it elsewhere.
1597 * @return the array of user ids.
1598 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001599 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001600 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001601 return mUserIds;
1602 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001603 }
1604
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001605 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001606 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001607 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001608 return;
1609 }
1610 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001611 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001612 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001613 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001614 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001615 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001616 int type;
1617 while ((type = parser.next()) != XmlPullParser.START_TAG
1618 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001619 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001620 }
1621
1622 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001623 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001624 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001625 return;
1626 }
1627
Amith Yamasani2a003292012-08-14 18:25:45 -07001628 mNextSerialNumber = -1;
1629 if (parser.getName().equals(TAG_USERS)) {
1630 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1631 if (lastSerialNumber != null) {
1632 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1633 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001634 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1635 if (versionNumber != null) {
1636 mUserVersion = Integer.parseInt(versionNumber);
1637 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001638 }
1639
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1641
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001642 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301643 if (type == XmlPullParser.START_TAG) {
1644 final String name = parser.getName();
1645 if (name.equals(TAG_USER)) {
1646 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001647
Amith Yamasani12747872015-12-07 14:19:49 -08001648 UserData userData = readUserLP(Integer.parseInt(id));
1649
1650 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001651 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001652 mUsers.put(userData.info.id, userData);
1653 if (mNextSerialNumber < 0
1654 || mNextSerialNumber <= userData.info.id) {
1655 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001656 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301657 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001658 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301659 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001660 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1661 && type != XmlPullParser.END_TAG) {
1662 if (type == XmlPullParser.START_TAG) {
1663 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001664 synchronized (mGuestRestrictions) {
1665 UserRestrictionsUtils
1666 .readRestrictions(parser, mGuestRestrictions);
1667 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001668 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1669 ) {
1670 UserRestrictionsUtils.readRestrictions(parser,
1671 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001672 }
1673 break;
1674 }
1675 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001676 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1677 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1678 if (ownerUserId != null) {
1679 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1680 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001681 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001682 }
1683 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001684 synchronized (mRestrictionsLock) {
1685 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1686 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001687 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001688 upgradeIfNecessaryLP();
1689 } catch (IOException | XmlPullParserException e) {
1690 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001691 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001692 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001693 }
1694 }
1695
Amith Yamasani6f34b412012-10-22 18:19:27 -07001696 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001697 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001698 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001699 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001701 int userVersion = mUserVersion;
1702 if (userVersion < 1) {
1703 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001704 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1705 if ("Primary".equals(userData.info.name)) {
1706 userData.info.name =
1707 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1708 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001709 }
1710 userVersion = 1;
1711 }
1712
Amith Yamasanibc9625052012-11-15 14:39:18 -08001713 if (userVersion < 2) {
1714 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001715 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1716 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1717 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1718 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001719 }
1720 userVersion = 2;
1721 }
1722
Amith Yamasani350962c2013-08-06 11:18:53 -07001723
Amith Yamasani5e486f52013-08-07 11:06:44 -07001724 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001725 userVersion = 4;
1726 }
1727
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001728 if (userVersion < 5) {
1729 initDefaultGuestRestrictions();
1730 userVersion = 5;
1731 }
1732
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001733 if (userVersion < 6) {
1734 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001735 synchronized (mUsersLock) {
1736 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001737 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001738 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001739 if (!splitSystemUser && userData.info.isRestricted()
1740 && (userData.info.restrictedProfileParentId
1741 == UserInfo.NO_PROFILE_GROUP_ID)) {
1742 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1743 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001744 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001745 }
1746 }
1747 userVersion = 6;
1748 }
1749
Amith Yamasani6f34b412012-10-22 18:19:27 -07001750 if (userVersion < USER_VERSION) {
1751 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1752 + USER_VERSION);
1753 } else {
1754 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001755
1756 if (originalVersion < mUserVersion) {
1757 writeUserListLP();
1758 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001759 }
1760 }
1761
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001762 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001763 int flags = UserInfo.FLAG_INITIALIZED;
1764 // In split system user mode, the admin and primary flags are assigned to the first human
1765 // user.
1766 if (!UserManager.isSplitSystemUser()) {
1767 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1768 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001769 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001770 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001771 UserData userData = new UserData();
1772 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001773 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001774 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001775 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001776 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001777 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001778
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001779 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001780 synchronized (mRestrictionsLock) {
1781 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1782 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001783
Fyodor Kupolov82402752015-10-28 14:54:51 -07001784 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001785 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001786
Amith Yamasani12747872015-12-07 14:19:49 -08001787 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001788 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001789 }
1790
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001791 private String getOwnerName() {
1792 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1793 }
1794
Amith Yamasani12747872015-12-07 14:19:49 -08001795 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001796 if (DBG) {
1797 debug("scheduleWriteUser");
1798 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001799 // No need to wrap it within a lock -- worst case, we'll just post the same message
1800 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001801 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1802 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001803 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1804 }
1805 }
1806
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001807 /*
1808 * Writes the user file in this format:
1809 *
1810 * <user flags="20039023" id="0">
1811 * <name>Primary</name>
1812 * </user>
1813 */
Amith Yamasani12747872015-12-07 14:19:49 -08001814 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001815 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001816 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001817 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001818 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001819 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001820 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001821 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001822 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1823
1824 // XmlSerializer serializer = XmlUtils.serializerInstance();
1825 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001826 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001827 serializer.startDocument(null, true);
1828 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1829
Amith Yamasani12747872015-12-07 14:19:49 -08001830 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001831 serializer.startTag(null, TAG_USER);
1832 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001833 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001834 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001835 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1836 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1837 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001838 if (userInfo.lastLoggedInFingerprint != null) {
1839 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1840 userInfo.lastLoggedInFingerprint);
1841 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001842 if (userInfo.iconPath != null) {
1843 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1844 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001845 if (userInfo.partial) {
1846 serializer.attribute(null, ATTR_PARTIAL, "true");
1847 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001848 if (userInfo.guestToRemove) {
1849 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1850 }
Kenny Guy2a764942014-04-02 13:29:20 +01001851 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1852 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1853 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001854 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001855 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1856 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1857 Integer.toString(userInfo.restrictedProfileParentId));
1858 }
Amith Yamasani12747872015-12-07 14:19:49 -08001859 // Write seed data
1860 if (userData.persistSeedData) {
1861 if (userData.seedAccountName != null) {
1862 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1863 }
1864 if (userData.seedAccountType != null) {
1865 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1866 }
1867 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001868 if (userInfo.name != null) {
1869 serializer.startTag(null, TAG_NAME);
1870 serializer.text(userInfo.name);
1871 serializer.endTag(null, TAG_NAME);
1872 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001873 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001874 UserRestrictionsUtils.writeRestrictions(serializer,
1875 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1876 UserRestrictionsUtils.writeRestrictions(serializer,
1877 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1878 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001879 }
Amith Yamasani12747872015-12-07 14:19:49 -08001880
1881 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001882 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001883 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001884 serializer.endTag(null, TAG_ACCOUNT);
1885 }
1886
Amith Yamasani12747872015-12-07 14:19:49 -08001887 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1888 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1889 userData.seedAccountOptions.saveToXml(serializer);
1890 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1891 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001892 serializer.endTag(null, TAG_USER);
1893
1894 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001895 userFile.finishWrite(fos);
1896 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001897 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001898 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001899 }
1900 }
1901
1902 /*
1903 * Writes the user list file in this format:
1904 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001905 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001906 * <user id="0"></user>
1907 * <user id="2"></user>
1908 * </users>
1909 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001910 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001911 if (DBG) {
1912 debug("writeUserList");
1913 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001914 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001915 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001916 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001917 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001918 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1919
1920 // XmlSerializer serializer = XmlUtils.serializerInstance();
1921 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001922 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001923 serializer.startDocument(null, true);
1924 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1925
1926 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001927 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001928 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001929
Adam Lesinskieddeb492014-09-08 17:50:03 -07001930 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001931 synchronized (mGuestRestrictions) {
1932 UserRestrictionsUtils
1933 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1934 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301935 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001936 synchronized (mRestrictionsLock) {
1937 UserRestrictionsUtils.writeRestrictions(serializer,
1938 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1939 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001940 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1941 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1942 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001943 int[] userIdsToWrite;
1944 synchronized (mUsersLock) {
1945 userIdsToWrite = new int[mUsers.size()];
1946 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001947 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001948 userIdsToWrite[i] = user.id;
1949 }
1950 }
1951 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001952 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001953 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001954 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001955 }
1956
1957 serializer.endTag(null, TAG_USERS);
1958
1959 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001960 userListFile.finishWrite(fos);
1961 } catch (Exception e) {
1962 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001963 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001964 }
1965 }
1966
Amith Yamasani12747872015-12-07 14:19:49 -08001967 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001968 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001969 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001970 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001971 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001972 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001973 long creationTime = 0L;
1974 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001975 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001976 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001977 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001978 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001979 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001980 boolean persistSeedData = false;
1981 String seedAccountName = null;
1982 String seedAccountType = null;
1983 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001984 Bundle baseRestrictions = new Bundle();
1985 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001986
1987 FileInputStream fis = null;
1988 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001989 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001990 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001991 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001992 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001993 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001994 int type;
1995 while ((type = parser.next()) != XmlPullParser.START_TAG
1996 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001997 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001998 }
1999
2000 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002001 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002002 return null;
2003 }
2004
2005 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002006 int storedId = readIntAttribute(parser, ATTR_ID, -1);
2007 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07002008 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002009 return null;
2010 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002011 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
2012 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002013 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07002014 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
2015 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002016 lastLoggedInFingerprint = parser.getAttributeValue(null,
2017 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01002018 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
2019 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002020 restrictedProfileParentId = readIntAttribute(parser,
2021 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002022 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
2023 if ("true".equals(valueString)) {
2024 partial = true;
2025 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002026 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
2027 if ("true".equals(valueString)) {
2028 guestToRemove = true;
2029 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002030
Amith Yamasani12747872015-12-07 14:19:49 -08002031 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2032 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2033 if (seedAccountName != null || seedAccountType != null) {
2034 persistSeedData = true;
2035 }
2036
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002037 int outerDepth = parser.getDepth();
2038 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2039 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2040 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2041 continue;
2042 }
2043 String tag = parser.getName();
2044 if (TAG_NAME.equals(tag)) {
2045 type = parser.next();
2046 if (type == XmlPullParser.TEXT) {
2047 name = parser.getText();
2048 }
2049 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002050 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2051 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2052 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002053 } else if (TAG_ACCOUNT.equals(tag)) {
2054 type = parser.next();
2055 if (type == XmlPullParser.TEXT) {
2056 account = parser.getText();
2057 }
Amith Yamasani12747872015-12-07 14:19:49 -08002058 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2059 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2060 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002061 }
2062 }
2063 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002064
Amith Yamasani12747872015-12-07 14:19:49 -08002065 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002066 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002067 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002068 userInfo.creationTime = creationTime;
2069 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002070 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002071 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002072 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002073 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002074 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002075
2076 // Create the UserData object that's internal to this class
2077 UserData userData = new UserData();
2078 userData.info = userInfo;
2079 userData.account = account;
2080 userData.seedAccountName = seedAccountName;
2081 userData.seedAccountType = seedAccountType;
2082 userData.persistSeedData = persistSeedData;
2083 userData.seedAccountOptions = seedAccountOptions;
2084
Makoto Onuki068c54a2015-10-13 14:34:03 -07002085 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002086 mBaseUserRestrictions.put(id, baseRestrictions);
2087 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002088 }
Amith Yamasani12747872015-12-07 14:19:49 -08002089 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002090 } catch (IOException ioe) {
2091 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002092 } finally {
2093 if (fis != null) {
2094 try {
2095 fis.close();
2096 } catch (IOException e) {
2097 }
2098 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002099 }
2100 return null;
2101 }
2102
Amith Yamasani920ace02012-09-20 22:15:37 -07002103 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2104 String valueString = parser.getAttributeValue(null, attr);
2105 if (valueString == null) return defaultValue;
2106 try {
2107 return Integer.parseInt(valueString);
2108 } catch (NumberFormatException nfe) {
2109 return defaultValue;
2110 }
2111 }
2112
2113 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2114 String valueString = parser.getAttributeValue(null, attr);
2115 if (valueString == null) return defaultValue;
2116 try {
2117 return Long.parseLong(valueString);
2118 } catch (NumberFormatException nfe) {
2119 return defaultValue;
2120 }
2121 }
2122
Amith Yamasanib82add22013-07-09 11:24:44 -07002123 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002124 * Removes the app restrictions file for a specific package and user id, if it exists.
2125 */
2126 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2127 synchronized (mPackagesLock) {
2128 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002129 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002130 if (resFile.exists()) {
2131 resFile.delete();
2132 }
2133 }
2134 }
2135
Kenny Guya52dc3e2014-02-11 15:33:14 +00002136 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002137 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002138 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002139 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002140 }
2141
Amith Yamasani258848d2012-08-10 17:06:33 -07002142 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002143 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002144 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002145 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002146 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002147
Jessica Hummelbe81c802014-04-22 15:49:22 +01002148 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002149 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002150 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2151 return null;
2152 }
phweisse9c44062016-02-10 12:57:38 +01002153 return createUserInternalUnchecked(name, flags, parentId);
2154 }
2155
2156 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002157 if (ActivityManager.isLowRamDeviceStatic()) {
2158 return null;
2159 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002160 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002161 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002162 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002163 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002164 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002165 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002166 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002167 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002168 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002169 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002170 if (parentId != UserHandle.USER_NULL) {
2171 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002172 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002173 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002174 if (parent == null) return null;
2175 }
2176 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2177 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2178 return null;
2179 }
2180 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
2181 // If we're not adding a guest user or a managed profile and the limit has
2182 // been reached, cannot add a user.
2183 return null;
2184 }
2185 // If we're adding a guest and there already exists one, bail.
2186 if (isGuest && findCurrentGuestUser() != null) {
2187 return null;
2188 }
2189 // In legacy mode, restricted profile's parent can only be the owner user
2190 if (isRestricted && !UserManager.isSplitSystemUser()
2191 && (parentId != UserHandle.USER_SYSTEM)) {
2192 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2193 return null;
2194 }
2195 if (isRestricted && UserManager.isSplitSystemUser()) {
2196 if (parent == null) {
2197 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2198 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002199 return null;
2200 }
Amith Yamasani12747872015-12-07 14:19:49 -08002201 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002202 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2203 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002204 return null;
2205 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002206 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01002207 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
2208 Log.e(LOG_TAG,
2209 "Ephemeral users are supported on split-system-user systems only.");
2210 return null;
2211 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002212 // In split system user mode, we assign the first human user the primary flag.
2213 // And if there is no device owner, we also assign the admin flag to primary user.
2214 if (UserManager.isSplitSystemUser()
2215 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2216 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002217 synchronized (mUsersLock) {
2218 if (!mIsDeviceManaged) {
2219 flags |= UserInfo.FLAG_ADMIN;
2220 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002221 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002222 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002223
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002224 userId = getNextAvailableId();
2225 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002226 boolean ephemeralGuests = Resources.getSystem()
2227 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002228
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002229 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002230 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2231 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2232 || (parent != null && parent.info.isEphemeral())) {
2233 flags |= UserInfo.FLAG_EPHEMERAL;
2234 }
2235
2236 userInfo = new UserInfo(userId, name, null, flags);
2237 userInfo.serialNumber = mNextSerialNumber++;
2238 long now = System.currentTimeMillis();
2239 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2240 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002241 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002242 userData = new UserData();
2243 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002244 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002245 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002246 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002247 writeUserListLP();
2248 if (parent != null) {
2249 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002250 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2251 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002252 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002253 }
Amith Yamasani12747872015-12-07 14:19:49 -08002254 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002255 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002256 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2257 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002258 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002259 }
Amith Yamasani12747872015-12-07 14:19:49 -08002260 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002261 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002262 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002263 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002264 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002265 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002266 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002267 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002268 mPm.createNewUser(userId);
2269 userInfo.partial = false;
2270 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002271 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002272 }
2273 updateUserIds();
2274 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002275 if (isGuest) {
2276 synchronized (mGuestRestrictions) {
2277 restrictions.putAll(mGuestRestrictions);
2278 }
2279 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002280 synchronized (mRestrictionsLock) {
2281 mBaseUserRestrictions.append(userId, restrictions);
2282 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002283 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2284 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2285 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2286 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002287 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002288 } finally {
2289 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002290 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002291 return userInfo;
2292 }
2293
Amith Yamasani0b285492011-04-14 17:35:23 -07002294 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002295 * @hide
2296 */
Amith Yamasani12747872015-12-07 14:19:49 -08002297 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002298 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2299 checkManageUsersPermission("setupRestrictedProfile");
2300 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2301 if (user == null) {
2302 return null;
2303 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002304 long identity = Binder.clearCallingIdentity();
2305 try {
2306 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2307 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2308 // the putIntForUser() will fail.
2309 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2310 android.provider.Settings.Secure.LOCATION_MODE,
2311 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2312 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2313 } finally {
2314 Binder.restoreCallingIdentity(identity);
2315 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002316 return user;
2317 }
2318
2319 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002320 * Find the current guest user. If the Guest user is partial,
2321 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002322 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002323 private UserInfo findCurrentGuestUser() {
2324 synchronized (mUsersLock) {
2325 final int size = mUsers.size();
2326 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002327 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002328 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2329 return user;
2330 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002331 }
2332 }
2333 return null;
2334 }
2335
2336 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002337 * Mark this guest user for deletion to allow us to create another guest
2338 * and switch to that user before actually removing this guest.
2339 * @param userHandle the userid of the current guest
2340 * @return whether the user could be marked for deletion
2341 */
Amith Yamasani12747872015-12-07 14:19:49 -08002342 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002343 public boolean markGuestForDeletion(int userHandle) {
2344 checkManageUsersPermission("Only the system can remove users");
2345 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2346 UserManager.DISALLOW_REMOVE_USER, false)) {
2347 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2348 return false;
2349 }
2350
2351 long ident = Binder.clearCallingIdentity();
2352 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002353 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002354 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002355 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002356 userData = mUsers.get(userHandle);
2357 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002358 return false;
2359 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002360 }
Amith Yamasani12747872015-12-07 14:19:49 -08002361 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002362 return false;
2363 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002364 // We set this to a guest user that is to be removed. This is a temporary state
2365 // where we are allowed to add new Guest users, even if this one is still not
2366 // removed. This user will still show up in getUserInfo() calls.
2367 // If we don't get around to removing this Guest user, it will be purged on next
2368 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002369 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002370 // Mark it as disabled, so that it isn't returned any more when
2371 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002372 userData.info.flags |= UserInfo.FLAG_DISABLED;
2373 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002374 }
2375 } finally {
2376 Binder.restoreCallingIdentity(ident);
2377 }
2378 return true;
2379 }
2380
2381 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002382 * Removes a user and all data directories created for that user. This method should be called
2383 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002384 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002385 */
Amith Yamasani12747872015-12-07 14:19:49 -08002386 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002387 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002388 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002389 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2390 UserManager.DISALLOW_REMOVE_USER, false)) {
2391 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2392 return false;
2393 }
2394
Kenny Guyee58b4f2014-05-23 15:19:53 +01002395 long ident = Binder.clearCallingIdentity();
2396 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002397 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002398 int currentUser = ActivityManager.getCurrentUser();
2399 if (currentUser == userHandle) {
2400 Log.w(LOG_TAG, "Current user cannot be removed");
2401 return false;
2402 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002403 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002404 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002405 userData = mUsers.get(userHandle);
2406 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002407 return false;
2408 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002409
Fyodor Kupolov82402752015-10-28 14:54:51 -07002410 // We remember deleted user IDs to prevent them from being
2411 // reused during the current boot; they can still be reused
2412 // after a reboot.
2413 mRemovingUserIds.put(userHandle, true);
2414 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002415
Kenny Guyee58b4f2014-05-23 15:19:53 +01002416 try {
2417 mAppOpsService.removeUser(userHandle);
2418 } catch (RemoteException e) {
2419 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2420 }
2421 // Set this to a partially created user, so that the user will be purged
2422 // on next startup, in case the runtime stops now before stopping and
2423 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002424 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002425 // Mark it as disabled, so that it isn't returned any more when
2426 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002427 userData.info.flags |= UserInfo.FLAG_DISABLED;
2428 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002429 }
2430
Amith Yamasani12747872015-12-07 14:19:49 -08002431 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2432 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002433 // Send broadcast to notify system that the user removed was a
2434 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002435 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002436 }
2437
2438 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2439 int res;
2440 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002441 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2442 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002443 @Override
2444 public void userStopped(int userId) {
2445 finishRemoveUser(userId);
2446 }
2447 @Override
2448 public void userStopAborted(int userId) {
2449 }
2450 });
2451 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002452 return false;
2453 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002454 return res == ActivityManager.USER_OP_SUCCESS;
2455 } finally {
2456 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002457 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002458 }
2459
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002460 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002461 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002462 // Let other services shutdown any activity and clean up their state before completely
2463 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002464 long ident = Binder.clearCallingIdentity();
2465 try {
2466 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2467 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002468 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2469 android.Manifest.permission.MANAGE_USERS,
2470
2471 new BroadcastReceiver() {
2472 @Override
2473 public void onReceive(Context context, Intent intent) {
2474 if (DBG) {
2475 Slog.i(LOG_TAG,
2476 "USER_REMOVED broadcast sent, cleaning up user data "
2477 + userHandle);
2478 }
2479 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002480 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002481 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002482 // Clean up any ActivityManager state
2483 LocalServices.getService(ActivityManagerInternal.class)
2484 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002485 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002486 }
2487 }.start();
2488 }
2489 },
2490
2491 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002492 } finally {
2493 Binder.restoreCallingIdentity(ident);
2494 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002495 }
2496
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002497 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002498 try {
2499 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2500 } catch (IllegalStateException e) {
2501 // This may be simply because the user was partially created.
2502 Slog.i(LOG_TAG,
2503 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2504 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002505
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002506 // Cleanup gatekeeper secure user id
2507 try {
2508 final IGateKeeperService gk = GateKeeper.getService();
2509 if (gk != null) {
2510 gk.clearSecureUserId(userHandle);
2511 }
2512 } catch (Exception ex) {
2513 Slog.w(LOG_TAG, "unable to clear GK secure user id");
2514 }
2515
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002516 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002517 mPm.cleanUpUser(this, userHandle);
Amith Yamasanid04aaa32016-06-13 12:09:36 -07002518
2519 // Clean up all data before removing metadata
2520 mPm.destroyUserData(userHandle,
2521 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2522
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002523 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002524 synchronized (mUsersLock) {
2525 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002526 mIsUserManaged.delete(userHandle);
Fyodor Kupolovac06a492016-05-25 14:45:29 -07002527 }
2528 synchronized (mUserStates) {
2529 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002530 }
2531 synchronized (mRestrictionsLock) {
2532 mBaseUserRestrictions.remove(userHandle);
2533 mAppliedUserRestrictions.remove(userHandle);
2534 mCachedEffectiveUserRestrictions.remove(userHandle);
2535 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002536 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002537 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002538 synchronized (mPackagesLock) {
2539 writeUserListLP();
2540 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002541 // Remove user file
2542 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2543 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002544 updateUserIds();
Amith Yamasani61f57372012-08-31 12:12:28 -07002545 }
2546
Kenny Guyf8d3a232014-05-15 16:09:52 +01002547 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002548 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002549 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2550 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002551 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002552 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002553 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002554 }
2555
Amith Yamasani2a003292012-08-14 18:25:45 -07002556 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002557 public Bundle getApplicationRestrictions(String packageName) {
2558 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2559 }
2560
2561 @Override
2562 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002563 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002564 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002565 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002566 }
2567 synchronized (mPackagesLock) {
2568 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002569 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002570 }
2571 }
2572
2573 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002574 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002575 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002576 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002577 if (restrictions != null) {
2578 restrictions.setDefusable(true);
2579 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002580 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002581 if (restrictions == null || restrictions.isEmpty()) {
2582 cleanAppRestrictionsForPackage(packageName, userId);
2583 } else {
2584 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002585 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002586 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002587 }
Robin Lee66e5d962014-04-09 16:44:21 +01002588
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002589 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2590 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2591 changeIntent.setPackage(packageName);
2592 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2593 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002594 }
2595
2596 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002597 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002598 try {
2599 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002600 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002601 } catch (NameNotFoundException nnfe) {
2602 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002603 } finally {
2604 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002605 }
2606 }
2607
Fyodor Kupolov82402752015-10-28 14:54:51 -07002608 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002609 AtomicFile restrictionsFile =
2610 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2611 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002612 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002613 }
2614
2615 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002616 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002617 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002618 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002619 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002620 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002621 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002622
2623 FileInputStream fis = null;
2624 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002625 fis = restrictionsFile.openRead();
2626 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002627 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002628 XmlUtils.nextElement(parser);
2629 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002630 Slog.e(LOG_TAG, "Unable to read restrictions file "
2631 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002632 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002633 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002634 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2635 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002636 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002637 } catch (IOException|XmlPullParserException e) {
2638 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002639 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002640 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002641 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002642 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002643 }
2644
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002645 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2646 XmlPullParser parser) throws XmlPullParserException, IOException {
2647 int type = parser.getEventType();
2648 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2649 String key = parser.getAttributeValue(null, ATTR_KEY);
2650 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2651 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2652 if (multiple != null) {
2653 values.clear();
2654 int count = Integer.parseInt(multiple);
2655 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2656 if (type == XmlPullParser.START_TAG
2657 && parser.getName().equals(TAG_VALUE)) {
2658 values.add(parser.nextText().trim());
2659 count--;
2660 }
2661 }
2662 String [] valueStrings = new String[values.size()];
2663 values.toArray(valueStrings);
2664 restrictions.putStringArray(key, valueStrings);
2665 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2666 restrictions.putBundle(key, readBundleEntry(parser, values));
2667 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2668 final int outerDepth = parser.getDepth();
2669 ArrayList<Bundle> bundleList = new ArrayList<>();
2670 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2671 Bundle childBundle = readBundleEntry(parser, values);
2672 bundleList.add(childBundle);
2673 }
2674 restrictions.putParcelableArray(key,
2675 bundleList.toArray(new Bundle[bundleList.size()]));
2676 } else {
2677 String value = parser.nextText().trim();
2678 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2679 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2680 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2681 restrictions.putInt(key, Integer.parseInt(value));
2682 } else {
2683 restrictions.putString(key, value);
2684 }
2685 }
2686 }
2687 }
2688
2689 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2690 throws IOException, XmlPullParserException {
2691 Bundle childBundle = new Bundle();
2692 final int outerDepth = parser.getDepth();
2693 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2694 readEntry(childBundle, values, parser);
2695 }
2696 return childBundle;
2697 }
2698
Fyodor Kupolov82402752015-10-28 14:54:51 -07002699 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002700 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002701 AtomicFile restrictionsFile = new AtomicFile(
2702 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002703 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002704 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002705 }
2706
2707 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002708 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002709 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002710 try {
2711 fos = restrictionsFile.startWrite();
2712 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2713
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002714 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002715 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002716 serializer.startDocument(null, true);
2717 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2718
2719 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002720 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002721 serializer.endTag(null, TAG_RESTRICTIONS);
2722
2723 serializer.endDocument();
2724 restrictionsFile.finishWrite(fos);
2725 } catch (Exception e) {
2726 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002727 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2728 }
2729 }
2730
2731 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2732 throws IOException {
2733 for (String key : restrictions.keySet()) {
2734 Object value = restrictions.get(key);
2735 serializer.startTag(null, TAG_ENTRY);
2736 serializer.attribute(null, ATTR_KEY, key);
2737
2738 if (value instanceof Boolean) {
2739 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2740 serializer.text(value.toString());
2741 } else if (value instanceof Integer) {
2742 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2743 serializer.text(value.toString());
2744 } else if (value == null || value instanceof String) {
2745 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2746 serializer.text(value != null ? (String) value : "");
2747 } else if (value instanceof Bundle) {
2748 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2749 writeBundle((Bundle) value, serializer);
2750 } else if (value instanceof Parcelable[]) {
2751 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2752 Parcelable[] array = (Parcelable[]) value;
2753 for (Parcelable parcelable : array) {
2754 if (!(parcelable instanceof Bundle)) {
2755 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2756 }
2757 serializer.startTag(null, TAG_ENTRY);
2758 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2759 writeBundle((Bundle) parcelable, serializer);
2760 serializer.endTag(null, TAG_ENTRY);
2761 }
2762 } else {
2763 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2764 String[] values = (String[]) value;
2765 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2766 for (String choice : values) {
2767 serializer.startTag(null, TAG_VALUE);
2768 serializer.text(choice != null ? choice : "");
2769 serializer.endTag(null, TAG_VALUE);
2770 }
2771 }
2772 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002773 }
2774 }
2775
2776 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002777 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002778 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002779 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002780 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002781 }
2782 }
2783
2784 @Override
2785 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002786 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002787 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002788 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002789 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002790 }
2791 // Not found
2792 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002793 }
2794 }
2795
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002796 @Override
2797 public long getUserCreationTime(int userHandle) {
2798 int callingUserId = UserHandle.getCallingUserId();
2799 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002800 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002801 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002802 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002803 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002804 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002805 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002806 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002807 }
2808 }
2809 }
2810 if (userInfo == null) {
2811 throw new SecurityException("userHandle can only be the calling user or a managed "
2812 + "profile associated with this user");
2813 }
2814 return userInfo.creationTime;
2815 }
2816
Amith Yamasani0b285492011-04-14 17:35:23 -07002817 /**
2818 * Caches the list of user ids in an array, adjusting the array size when necessary.
2819 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002820 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002821 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002822 synchronized (mUsersLock) {
2823 final int userSize = mUsers.size();
2824 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002825 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002826 num++;
2827 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002828 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002829 final int[] newUsers = new int[num];
2830 int n = 0;
2831 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002832 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002833 newUsers[n++] = mUsers.keyAt(i);
2834 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002835 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002836 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002837 }
2838 }
2839
2840 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002841 * Called right before a user is started. This gives us a chance to prepare
2842 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002843 */
2844 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002845 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002846 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002847 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002848
2849 if (userId != UserHandle.USER_SYSTEM) {
2850 synchronized (mRestrictionsLock) {
2851 applyUserRestrictionsLR(userId);
2852 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002853 UserInfo userInfo = getUserInfoNoChecks(userId);
2854 if (userInfo != null && !userInfo.isInitialized()) {
2855 mPm.onBeforeUserStartUninitialized(userId);
2856 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002857 }
2858 }
2859
2860 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002861 * Called right before a user is unlocked. This gives us a chance to prepare
2862 * app storage.
2863 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002864 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002865 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002866 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002867 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002868 }
2869
2870 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002871 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002872 * @param userId the user that was just foregrounded
2873 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002874 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002875 UserData userData = getUserDataNoChecks(userId);
2876 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002877 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2878 return;
2879 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002880
2881 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002882 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002883 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002884 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002885 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2886 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002887 }
2888
2889 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002890 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002891 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2892 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002893 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002894 private int getNextAvailableId() {
2895 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002896 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002897 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002898 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002899 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002900 }
2901 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002902 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002903 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002904 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002905 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002906
Amith Yamasanifc95e702013-09-26 13:20:17 -07002907 private String packageToRestrictionsFileName(String packageName) {
2908 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2909 }
2910
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002911 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002912 * Enforce that serial number stored in user directory inode matches the
2913 * given expected value. Gracefully sets the serial number if currently
2914 * undefined.
2915 *
2916 * @throws IOException when problem extracting serial number, or serial
2917 * number is mismatched.
2918 */
2919 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2920 final int foundSerial = getSerialNumber(file);
2921 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2922
2923 if (foundSerial == -1) {
2924 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2925 try {
2926 setSerialNumber(file, serialNumber);
2927 } catch (IOException e) {
2928 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2929 }
2930
2931 } else if (foundSerial != serialNumber) {
2932 throw new IOException("Found serial number " + foundSerial
2933 + " doesn't match expected " + serialNumber);
2934 }
2935 }
2936
2937 /**
2938 * Set serial number stored in user directory inode.
2939 *
2940 * @throws IOException if serial number was already set
2941 */
2942 private static void setSerialNumber(File file, int serialNumber)
2943 throws IOException {
2944 try {
2945 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2946 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2947 } catch (ErrnoException e) {
2948 throw e.rethrowAsIOException();
2949 }
2950 }
2951
2952 /**
2953 * Return serial number stored in user directory inode.
2954 *
2955 * @return parsed serial number, or -1 if not set
2956 */
2957 private static int getSerialNumber(File file) throws IOException {
2958 try {
2959 final byte[] buf = new byte[256];
2960 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2961 final String serial = new String(buf, 0, len);
2962 try {
2963 return Integer.parseInt(serial);
2964 } catch (NumberFormatException e) {
2965 throw new IOException("Bad serial number: " + serial);
2966 }
2967 } catch (ErrnoException e) {
2968 if (e.errno == OsConstants.ENODATA) {
2969 return -1;
2970 } else {
2971 throw e.rethrowAsIOException();
2972 }
2973 }
2974 }
2975
Amith Yamasani920ace02012-09-20 22:15:37 -07002976 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002977 public void setSeedAccountData(int userId, String accountName, String accountType,
2978 PersistableBundle accountOptions, boolean persist) {
2979 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2980 synchronized (mPackagesLock) {
2981 final UserData userData;
2982 synchronized (mUsersLock) {
2983 userData = getUserDataLU(userId);
2984 if (userData == null) {
2985 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2986 return;
2987 }
2988 userData.seedAccountName = accountName;
2989 userData.seedAccountType = accountType;
2990 userData.seedAccountOptions = accountOptions;
2991 userData.persistSeedData = persist;
2992 }
2993 if (persist) {
2994 writeUserLP(userData);
2995 }
2996 }
2997 }
2998
2999 @Override
3000 public String getSeedAccountName() throws RemoteException {
3001 checkManageUsersPermission("Cannot get seed account information");
3002 synchronized (mUsersLock) {
3003 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3004 return userData.seedAccountName;
3005 }
3006 }
3007
3008 @Override
3009 public String getSeedAccountType() throws RemoteException {
3010 checkManageUsersPermission("Cannot get seed account information");
3011 synchronized (mUsersLock) {
3012 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3013 return userData.seedAccountType;
3014 }
3015 }
3016
3017 @Override
3018 public PersistableBundle getSeedAccountOptions() throws RemoteException {
3019 checkManageUsersPermission("Cannot get seed account information");
3020 synchronized (mUsersLock) {
3021 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
3022 return userData.seedAccountOptions;
3023 }
3024 }
3025
3026 @Override
3027 public void clearSeedAccountData() throws RemoteException {
3028 checkManageUsersPermission("Cannot clear seed account information");
3029 synchronized (mPackagesLock) {
3030 UserData userData;
3031 synchronized (mUsersLock) {
3032 userData = getUserDataLU(UserHandle.getCallingUserId());
3033 if (userData == null) return;
3034 userData.clearSeedAccountData();
3035 }
3036 writeUserLP(userData);
3037 }
3038 }
3039
3040 @Override
3041 public boolean someUserHasSeedAccount(String accountName, String accountType)
3042 throws RemoteException {
3043 checkManageUsersPermission("Cannot check seed account information");
3044 synchronized (mUsersLock) {
3045 final int userSize = mUsers.size();
3046 for (int i = 0; i < userSize; i++) {
3047 final UserData data = mUsers.valueAt(i);
3048 if (data.info.isInitialized()) continue;
3049 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3050 continue;
3051 }
3052 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3053 continue;
3054 }
3055 return true;
3056 }
3057 }
3058 return false;
3059 }
3060
3061 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003062 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3063 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3064 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3065 }
3066
3067 int onShellCommand(Shell shell, String cmd) {
3068 if (cmd == null) {
3069 return shell.handleDefaultCommands(cmd);
3070 }
3071
3072 final PrintWriter pw = shell.getOutPrintWriter();
3073 try {
3074 switch(cmd) {
3075 case "list":
3076 return runList(pw);
3077 }
3078 } catch (RemoteException e) {
3079 pw.println("Remote exception: " + e);
3080 }
3081 return -1;
3082 }
3083
3084 private int runList(PrintWriter pw) throws RemoteException {
3085 final IActivityManager am = ActivityManagerNative.getDefault();
3086 final List<UserInfo> users = getUsers(false);
3087 if (users == null) {
3088 pw.println("Error: couldn't get users");
3089 return 1;
3090 } else {
3091 pw.println("Users:");
3092 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003093 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003094 pw.println("\t" + users.get(i).toString() + running);
3095 }
3096 return 0;
3097 }
3098 }
3099
3100 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003101 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3102 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3103 != PackageManager.PERMISSION_GRANTED) {
3104 pw.println("Permission Denial: can't dump UserManager from from pid="
3105 + Binder.getCallingPid()
3106 + ", uid=" + Binder.getCallingUid()
3107 + " without permission "
3108 + android.Manifest.permission.DUMP);
3109 return;
3110 }
3111
3112 long now = System.currentTimeMillis();
3113 StringBuilder sb = new StringBuilder();
3114 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003115 synchronized (mUsersLock) {
3116 pw.println("Users:");
3117 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003118 UserData userData = mUsers.valueAt(i);
3119 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003120 continue;
3121 }
Amith Yamasani12747872015-12-07 14:19:49 -08003122 UserInfo userInfo = userData.info;
3123 final int userId = userInfo.id;
3124 pw.print(" "); pw.print(userInfo);
3125 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003126 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003127 pw.print(" <removing> ");
3128 }
Amith Yamasani12747872015-12-07 14:19:49 -08003129 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003130 pw.print(" <partial>");
3131 }
3132 pw.println();
3133 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003134 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003135 pw.println("<unknown>");
3136 } else {
3137 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003138 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003139 sb.append(" ago");
3140 pw.println(sb);
3141 }
3142 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003143 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003144 pw.println("<unknown>");
3145 } else {
3146 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003147 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003148 sb.append(" ago");
3149 pw.println(sb);
3150 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003151 pw.print(" Last logged in fingerprint: ");
3152 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003153 pw.print(" Has profile owner: ");
3154 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003155 pw.println(" Restrictions:");
3156 synchronized (mRestrictionsLock) {
3157 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003158 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003159 pw.println(" Device policy local restrictions:");
3160 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003161 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003162 pw.println(" Effective restrictions:");
3163 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003164 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003165 }
Amith Yamasani12747872015-12-07 14:19:49 -08003166
3167 if (userData.account != null) {
3168 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003169 pw.println();
3170 }
Amith Yamasani12747872015-12-07 14:19:49 -08003171
3172 if (userData.seedAccountName != null) {
3173 pw.print(" Seed account name: " + userData.seedAccountName);
3174 pw.println();
3175 if (userData.seedAccountType != null) {
3176 pw.print(" account type: " + userData.seedAccountType);
3177 pw.println();
3178 }
3179 if (userData.seedAccountOptions != null) {
3180 pw.print(" account options exist");
3181 pw.println();
3182 }
3183 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003184 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003185 }
Amith Yamasani12747872015-12-07 14:19:49 -08003186 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003187 pw.println(" Device policy global restrictions:");
3188 synchronized (mRestrictionsLock) {
3189 UserRestrictionsUtils
3190 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3191 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003192 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003193 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3194 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003195 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003196 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003197 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003198 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003199 synchronized (mUsersLock) {
3200 pw.println();
3201 pw.println(" Device managed: " + mIsDeviceManaged);
3202 }
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003203 synchronized (mUserStates) {
3204 pw.println(" Started users state: " + mUserStates);
3205 }
Amith Yamasani12747872015-12-07 14:19:49 -08003206 // Dump some capabilities
3207 pw.println();
3208 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3209 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003210 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3211 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003212 }
3213 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003214
3215 final class MainHandler extends Handler {
3216
3217 @Override
3218 public void handleMessage(Message msg) {
3219 switch (msg.what) {
3220 case WRITE_USER_MSG:
3221 removeMessages(WRITE_USER_MSG, msg.obj);
3222 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003223 int userId = ((UserData) msg.obj).info.id;
3224 UserData userData = getUserDataNoChecks(userId);
3225 if (userData != null) {
3226 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003227 }
3228 }
3229 }
3230 }
3231 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003232
3233 /**
3234 * @param userId
3235 * @return whether the user has been initialized yet
3236 */
3237 boolean isInitialized(int userId) {
3238 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3239 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003240
3241 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003242 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003243 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3244 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003245 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003246 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003247 }
3248
3249 @Override
3250 public Bundle getBaseUserRestrictions(int userId) {
3251 synchronized (mRestrictionsLock) {
3252 return mBaseUserRestrictions.get(userId);
3253 }
3254 }
3255
3256 @Override
3257 public void setBaseUserRestrictionsByDpmsForMigration(
3258 int userId, Bundle baseRestrictions) {
3259 synchronized (mRestrictionsLock) {
3260 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003261 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003262 }
3263
Amith Yamasani12747872015-12-07 14:19:49 -08003264 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003265 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003266 if (userData != null) {
3267 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003268 } else {
3269 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3270 }
3271 }
3272 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003273
3274 @Override
3275 public boolean getUserRestriction(int userId, String key) {
3276 return getUserRestrictions(userId).getBoolean(key);
3277 }
3278
3279 @Override
3280 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3281 synchronized (mUserRestrictionsListeners) {
3282 mUserRestrictionsListeners.add(listener);
3283 }
3284 }
3285
3286 @Override
3287 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3288 synchronized (mUserRestrictionsListeners) {
3289 mUserRestrictionsListeners.remove(listener);
3290 }
3291 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003292
3293 @Override
3294 public void setDeviceManaged(boolean isManaged) {
3295 synchronized (mUsersLock) {
3296 mIsDeviceManaged = isManaged;
3297 }
3298 }
3299
3300 @Override
3301 public void setUserManaged(int userId, boolean isManaged) {
3302 synchronized (mUsersLock) {
3303 mIsUserManaged.put(userId, isManaged);
3304 }
3305 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003306
3307 @Override
3308 public void setUserIcon(int userId, Bitmap bitmap) {
3309 long ident = Binder.clearCallingIdentity();
3310 try {
3311 synchronized (mPackagesLock) {
3312 UserData userData = getUserDataNoChecks(userId);
3313 if (userData == null || userData.info.partial) {
3314 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3315 return;
3316 }
3317 writeBitmapLP(userData.info, bitmap);
3318 writeUserLP(userData);
3319 }
3320 sendUserInfoChangedBroadcast(userId);
3321 } finally {
3322 Binder.restoreCallingIdentity(ident);
3323 }
3324 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003325
3326 @Override
3327 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3328 synchronized (mUsersLock) {
3329 mForceEphemeralUsers = forceEphemeralUsers;
3330 }
3331 }
3332
3333 @Override
3334 public void removeAllUsers() {
3335 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3336 // Remove the non-system users straight away.
3337 removeNonSystemUsers();
3338 } else {
3339 // Switch to the system user first and then remove the other users.
3340 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3341 @Override
3342 public void onReceive(Context context, Intent intent) {
3343 int userId =
3344 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3345 if (userId != UserHandle.USER_SYSTEM) {
3346 return;
3347 }
3348 mContext.unregisterReceiver(this);
3349 removeNonSystemUsers();
3350 }
3351 };
3352 IntentFilter userSwitchedFilter = new IntentFilter();
3353 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3354 mContext.registerReceiver(
3355 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3356
3357 // Switch to the system user.
3358 ActivityManager am =
3359 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3360 am.switchUser(UserHandle.USER_SYSTEM);
3361 }
3362 }
phweisse9c44062016-02-10 12:57:38 +01003363
3364 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003365 public void onEphemeralUserStop(int userId) {
3366 synchronized (mUsersLock) {
3367 UserInfo userInfo = getUserInfoLU(userId);
3368 if (userInfo != null && userInfo.isEphemeral()) {
3369 // Do not allow switching back to the ephemeral user again as the user is going
3370 // to be deleted.
3371 userInfo.flags |= UserInfo.FLAG_DISABLED;
3372 if (userInfo.isGuest()) {
3373 // Indicate that the guest will be deleted after it stops.
3374 userInfo.guestToRemove = true;
3375 }
3376 }
3377 }
3378 }
3379
3380 @Override
phweisse9c44062016-02-10 12:57:38 +01003381 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3382 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3383 // Keep this in sync with UserManager.createUser
3384 if (user != null && !user.isAdmin()) {
3385 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3386 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3387 }
3388 return user;
3389 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003390
3391 @Override
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003392 public boolean isUserRunning(int userId) {
3393 synchronized (mUserStates) {
3394 return mUserStates.get(userId, -1) >= 0;
3395 }
3396 }
3397
3398 @Override
3399 public void setUserState(int userId, int userState) {
3400 synchronized (mUserStates) {
3401 mUserStates.put(userId, userState);
3402 }
3403 }
3404
3405 @Override
3406 public void removeUserState(int userId) {
3407 synchronized (mUserStates) {
3408 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003409 }
3410 }
3411
3412 @Override
3413 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003414 synchronized (mUserStates) {
3415 int state = mUserStates.get(userId, -1);
3416 return (state == UserState.STATE_RUNNING_UNLOCKING)
3417 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003418 }
3419 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003420 }
3421
3422 /* Remove all the users except of the system one. */
3423 private void removeNonSystemUsers() {
3424 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3425 synchronized (mUsersLock) {
3426 final int userSize = mUsers.size();
3427 for (int i = 0; i < userSize; i++) {
3428 UserInfo ui = mUsers.valueAt(i).info;
3429 if (ui.id != UserHandle.USER_SYSTEM) {
3430 usersToRemove.add(ui);
3431 }
3432 }
3433 }
3434 for (UserInfo ui: usersToRemove) {
3435 removeUser(ui.id);
3436 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003437 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003438
3439 private class Shell extends ShellCommand {
3440 @Override
3441 public int onCommand(String cmd) {
3442 return onShellCommand(this, cmd);
3443 }
3444
3445 @Override
3446 public void onHelp() {
3447 final PrintWriter pw = getOutPrintWriter();
3448 pw.println("User manager (user) commands:");
3449 pw.println(" help");
3450 pw.println(" Print this help text.");
3451 pw.println("");
3452 pw.println(" list");
3453 pw.println(" Prints all users on the system.");
3454 }
3455 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003456
3457 private static void debug(String message) {
3458 Log.d(LOG_TAG, message +
3459 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3460 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003461}