blob: 9c62b2016595db37c83c4bb3e863b92a028850c9 [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;
Amith Yamasanieb437d42016-04-29 09:31:25 -070030import android.app.AppGlobals;
Todd Kennedy60459ab2015-10-30 11:32:16 -070031import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070032import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010033import android.app.KeyguardManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Bart Searsc51e7252016-05-27 04:12:51 +000035import android.content.ComponentName;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.content.Context;
37import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010038import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010039import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070040import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080041import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010043import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070044import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060046import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080047import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080048import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.os.Environment;
50import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080052import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070053import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080054import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010055import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070056import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080057import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070058import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070059import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070060import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010061import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040062import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070063import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070064import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070065import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070066import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080067import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010068import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070069import android.system.ErrnoException;
70import android.system.Os;
71import android.system.OsConstants;
Amith Yamasanieb437d42016-04-29 09:31:25 -070072import android.text.TextUtils;
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;
Amith Yamasaniea1b9d72016-05-27 15:57:38 +000079import 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 Yamasaniea1b9d72016-05-27 15:57:38 +000092import com.android.server.am.UserState;
Jeff Sharkey47f71082016-02-01 17:03:54 -070093
94import libcore.io.IoUtils;
95import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080096
97import org.xmlpull.v1.XmlPullParser;
98import org.xmlpull.v1.XmlPullParserException;
99import org.xmlpull.v1.XmlSerializer;
100
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700101import java.io.BufferedOutputStream;
102import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700103import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700105import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106import java.io.FileOutputStream;
107import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700108import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100109import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110import java.util.ArrayList;
111import java.util.List;
112
Makoto Onuki068c54a2015-10-13 14:34:03 -0700113/**
114 * Service for {@link UserManager}.
115 *
116 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700117 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800118 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700119 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
120 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
121 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700122 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700123public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700124 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800125 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800126 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700127
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800129 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700131 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700133 private static final String ATTR_CREATION_TIME = "created";
134 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600135 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700136 private static final String ATTR_SERIAL_NO = "serialNumber";
137 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700138 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700139 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700140 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100141 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700142 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800143 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
144 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530145 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700146 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700147 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800148 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800149 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100150 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800151 private static final String TAG_ENTRY = "entry";
152 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800153 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800154 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700155 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800156 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700158 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
159 private static final String ATTR_TYPE_STRING = "s";
160 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700161 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700162 private static final String ATTR_TYPE_BUNDLE = "B";
163 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700164
Amith Yamasani0b285492011-04-14 17:35:23 -0700165 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700167 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100168 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700169
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800170 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700171 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800172
Amith Yamasani634cf312012-10-04 17:34:21 -0700173 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700174 // We need to keep process uid within Integer.MAX_VALUE.
175 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700176
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700177 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700178
Amith Yamasani920ace02012-09-20 22:15:37 -0700179 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
180
Nicolas Prevotb8186812015-08-06 15:00:03 +0100181 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700182 // without first making sure that the rest of the framework is prepared for it.
183 private static final int MAX_MANAGED_PROFILES = 1;
184
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800185 static final int WRITE_USER_MSG = 1;
186 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530187
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700188 private static final String XATTR_SERIAL = "user.serial";
189
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800190 // Tron counters
191 private static final String TRON_GUEST_CREATED = "users_guest_created";
192 private static final String TRON_USER_CREATED = "users_user_created";
193
Dianne Hackborn4428e172012-08-24 17:43:05 -0700194 private final Context mContext;
195 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700197 // Short-term lock for internal state, when interaction/sync with PM is not required
198 private final Object mUsersLock = new Object();
199 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700200
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800201 private final Handler mHandler;
202
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700203 private final File mUsersDir;
204 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700205
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800206 private static final IBinder mUserRestriconToken = new Binder();
207
Makoto Onuki068c54a2015-10-13 14:34:03 -0700208 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800209 * User-related information that is used for persisting to flash. Only UserInfo is
210 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800211 */
Amith Yamasani12747872015-12-07 14:19:49 -0800212 private static class UserData {
213 // Basic user information and properties
214 UserInfo info;
215 // Account name used when there is a strong association between a user and an account
216 String account;
217 // Account information for seeding into a newly created user. This could also be
218 // used for login validation for an existing user, for updating their credentials.
219 // In the latter case, data may not need to be persisted as it is only valid for the
220 // current login session.
221 String seedAccountName;
222 String seedAccountType;
223 PersistableBundle seedAccountOptions;
224 // Whether to perist the seed account information to be available after a boot
225 boolean persistSeedData;
226
227 void clearSeedAccountData() {
228 seedAccountName = null;
229 seedAccountType = null;
230 seedAccountOptions = null;
231 persistSeedData = false;
232 }
233 }
234
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800235 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800236 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800237
238 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700239 * User restrictions set via UserManager. This doesn't include restrictions set by
240 * device owner / profile owners.
241 *
242 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
243 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
244 * maybe shared between {@link #mBaseUserRestrictions} and
245 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
246 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700247 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700248 */
249 @GuardedBy("mRestrictionsLock")
250 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
251
252 /**
253 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
254 * with device / profile owner restrictions. We'll initialize it lazily; use
255 * {@link #getEffectiveUserRestrictions} to access it.
256 *
257 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
258 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
259 * maybe shared between {@link #mBaseUserRestrictions} and
260 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
261 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700262 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700263 */
264 @GuardedBy("mRestrictionsLock")
265 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
266
Makoto Onuki4f160732015-10-27 17:15:38 -0700267 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800268 * User restrictions that have already been applied in
269 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
270 * that have changed since the last
271 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700272 */
273 @GuardedBy("mRestrictionsLock")
274 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
275
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800276 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800277 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
278 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800279 */
280 @GuardedBy("mRestrictionsLock")
281 private Bundle mDevicePolicyGlobalUserRestrictions;
282
283 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100284 * Id of the user that set global restrictions.
285 */
286 @GuardedBy("mRestrictionsLock")
287 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
288
289 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800290 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
291 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800292 */
293 @GuardedBy("mRestrictionsLock")
294 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
295
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800296 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530297 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800298
299 /**
300 * Set of user IDs being actively removed. Removed IDs linger in this set
301 * for several seconds to work around a VFS caching issue.
302 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700303 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800304 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700305
Fyodor Kupolov82402752015-10-28 14:54:51 -0700306 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700307 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800308 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700309 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700310 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700311
Jason Monk62062992014-05-06 09:55:28 -0400312 private IAppOpsService mAppOpsService;
313
Makoto Onuki068c54a2015-10-13 14:34:03 -0700314 private final LocalService mLocalService;
315
Makoto Onukie7927da2015-11-25 10:05:17 -0800316 @GuardedBy("mUsersLock")
317 private boolean mIsDeviceManaged;
318
319 @GuardedBy("mUsersLock")
320 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
321
Makoto Onukid45a4a22015-11-02 17:17:38 -0800322 @GuardedBy("mUserRestrictionsListeners")
323 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
324 new ArrayList<>();
325
Clara Bayarria1771112015-12-18 16:29:18 +0000326 private final LockPatternUtils mLockPatternUtils;
327
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100328 /**
329 * Whether all users should be created ephemeral.
330 */
331 @GuardedBy("mUsersLock")
332 private boolean mForceEphemeralUsers;
333
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000334 @GuardedBy("mUserStates")
335 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700336
Amith Yamasani258848d2012-08-10 17:06:33 -0700337 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700338
Dianne Hackborn4428e172012-08-24 17:43:05 -0700339 public static UserManagerService getInstance() {
340 synchronized (UserManagerService.class) {
341 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700342 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700343 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700344
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800345 @VisibleForTesting
346 UserManagerService(File dataDir) {
347 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700348 }
349
Dianne Hackborn4428e172012-08-24 17:43:05 -0700350 /**
351 * Called by package manager to create the service. This is closely
352 * associated with the package manager, and the given lock is the
353 * package manager's own lock.
354 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800355 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
356 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700357 }
358
Dianne Hackborn4428e172012-08-24 17:43:05 -0700359 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800360 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700361 mContext = context;
362 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700363 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800364 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800365 synchronized (mPackagesLock) {
366 mUsersDir = new File(dataDir, USER_INFO_DIR);
367 mUsersDir.mkdirs();
368 // Make zeroth user directory, for services to migrate their files to that location
369 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
370 userZeroDir.mkdirs();
371 FileUtils.setPermissions(mUsersDir.toString(),
372 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
373 -1, -1);
374 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
375 initDefaultGuestRestrictions();
376 readUserListLP();
377 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700378 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700379 mLocalService = new LocalService();
380 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000381 mLockPatternUtils = new LockPatternUtils(mContext);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +0000382 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700383 }
384
385 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100386 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800387 ArrayList<UserInfo> partials = new ArrayList<>();
388 synchronized (mUsersLock) {
389 final int userSize = mUsers.size();
390 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800391 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100392 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800393 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700394 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700395 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700396 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800397 final int partialsSize = partials.size();
398 for (int i = 0; i < partialsSize; i++) {
399 UserInfo ui = partials.get(i);
400 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
401 + " (name=" + ui.name + ")");
402 removeUserState(ui.id);
403 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800404
Jason Monk62062992014-05-06 09:55:28 -0400405 mAppOpsService = IAppOpsService.Stub.asInterface(
406 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800407
408 synchronized (mRestrictionsLock) {
409 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400410 }
Samuel Tand9453b82016-03-14 15:57:02 -0700411
412 UserInfo currentGuestUser = findCurrentGuestUser();
413 if (currentGuestUser != null && !hasUserRestriction(
414 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
415 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
416 // to it, in case this guest was created in a previous version where this
417 // user restriction was not a default guest restriction.
418 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
419 }
Amith Yamasanieb437d42016-04-29 09:31:25 -0700420
421 maybeInitializeDemoMode(UserHandle.USER_SYSTEM);
422}
Amith Yamasani258848d2012-08-10 17:06:33 -0700423
424 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800425 public String getUserAccount(int userId) {
426 checkManageUserAndAcrossUsersFullPermission("get user account");
427 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800428 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800429 }
430 }
431
432 @Override
433 public void setUserAccount(int userId, String accountName) {
434 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800435 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800436 synchronized (mPackagesLock) {
437 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800438 final UserData userData = mUsers.get(userId);
439 if (userData == null) {
440 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
441 return;
442 }
443 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800444 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800445 userData.account = accountName;
446 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800447 }
448 }
449
450 if (userToUpdate != null) {
451 writeUserLP(userToUpdate);
452 }
453 }
454 }
455
456 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700457 public UserInfo getPrimaryUser() {
458 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700459 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700460 final int userSize = mUsers.size();
461 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800462 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800463 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700464 return ui;
465 }
466 }
467 }
468 return null;
469 }
470
471 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700472 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700473 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700474 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700475 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700476 final int userSize = mUsers.size();
477 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800478 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700479 if (ui.partial) {
480 continue;
481 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800482 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700483 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700484 }
Amith Yamasani13593602012-03-22 16:16:17 -0700485 }
486 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700487 }
Amith Yamasani13593602012-03-22 16:16:17 -0700488 }
489
Amith Yamasani258848d2012-08-10 17:06:33 -0700490 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100491 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700492 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800493 if (userId != UserHandle.getCallingUserId()) {
494 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700495 } else {
496 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800497 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700498 final long ident = Binder.clearCallingIdentity();
499 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700500 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700501 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100502 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700503 } finally {
504 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000505 }
506 }
507
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700508 @Override
509 public int[] getProfileIds(int userId, boolean enabledOnly) {
510 if (userId != UserHandle.getCallingUserId()) {
511 checkManageUsersPermission("getting profiles related to user " + userId);
512 }
513 final long ident = Binder.clearCallingIdentity();
514 try {
515 synchronized (mUsersLock) {
516 return getProfileIdsLU(userId, enabledOnly).toArray();
517 }
518 } finally {
519 Binder.restoreCallingIdentity(ident);
520 }
521 }
522
Amith Yamasanibe465322014-04-24 13:45:17 -0700523 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700524 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700525 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
526 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
527 for (int i = 0; i < profileIds.size(); i++) {
528 int profileId = profileIds.get(i);
529 UserInfo userInfo = mUsers.get(profileId).info;
530 // If full info is not required - clear PII data to prevent 3P apps from reading it
531 if (!fullInfo) {
532 userInfo = new UserInfo(userInfo);
533 userInfo.name = null;
534 userInfo.iconPath = null;
535 } else {
536 userInfo = userWithName(userInfo);
537 }
538 users.add(userInfo);
539 }
540 return users;
541 }
542
543 /**
544 * Assume permissions already checked and caller's identity cleared
545 */
546 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700547 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700548 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700549 if (user == null) {
550 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700551 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700552 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700553 final int userSize = mUsers.size();
554 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800555 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700556 if (!isProfileOf(user, profile)) {
557 continue;
558 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100559 if (enabledOnly && !profile.isEnabled()) {
560 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700561 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700562 if (mRemovingUserIds.get(profile.id)) {
563 continue;
564 }
Tony Mak80189cd2016-04-05 17:21:42 +0100565 if (profile.partial) {
566 continue;
567 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700568 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700569 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700570 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700571 }
572
Jessica Hummelbe81c802014-04-22 15:49:22 +0100573 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700574 public int getCredentialOwnerProfile(int userHandle) {
575 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000576 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700577 synchronized (mUsersLock) {
578 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700579 if (profileParent != null) {
580 return profileParent.id;
581 }
582 }
583 }
584
585 return userHandle;
586 }
587
588 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700589 public boolean isSameProfileGroup(int userId, int otherUserId) {
590 if (userId == otherUserId) return true;
591 checkManageUsersPermission("check if in the same profile group");
592 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700593 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700594 }
595 }
596
Fyodor Kupolov82402752015-10-28 14:54:51 -0700597 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
598 synchronized (mUsersLock) {
599 UserInfo userInfo = getUserInfoLU(userId);
600 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
601 return false;
602 }
603 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
604 if (otherUserInfo == null
605 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
606 return false;
607 }
608 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700609 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700610 }
611
612 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100613 public UserInfo getProfileParent(int userHandle) {
614 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700615 synchronized (mUsersLock) {
616 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700617 }
618 }
619
Fyodor Kupolov82402752015-10-28 14:54:51 -0700620 private UserInfo getProfileParentLU(int userHandle) {
621 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700622 if (profile == null) {
623 return null;
624 }
625 int parentUserId = profile.profileGroupId;
626 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
627 return null;
628 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700629 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100630 }
631 }
632
Fyodor Kupolov82402752015-10-28 14:54:51 -0700633 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100634 return user.id == profile.id ||
635 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
636 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000637 }
638
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000639 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000640 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100641 Intent intent = new Intent();
642 if (inQuietMode) {
643 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
644 } else {
645 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
646 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000647 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
648 intent.putExtra(Intent.EXTRA_USER, profileHandle);
649 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000650 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000651 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000652 }
653
654 @Override
655 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
656 checkManageUsersPermission("silence profile");
657 boolean changed = false;
658 UserInfo profile, parent;
659 synchronized (mPackagesLock) {
660 synchronized (mUsersLock) {
661 profile = getUserInfoLU(userHandle);
662 parent = getProfileParentLU(userHandle);
663
664 }
665 if (profile == null || !profile.isManagedProfile()) {
666 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
667 }
668 if (profile.isQuietModeEnabled() != enableQuietMode) {
669 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800670 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000671 changed = true;
672 }
673 }
674 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000675 long identity = Binder.clearCallingIdentity();
676 try {
677 if (enableQuietMode) {
Rubin Xuf8451b92016-04-01 15:50:58 +0100678 LocalServices.getService(ActivityManagerInternal.class)
679 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000680 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
681 } else {
682 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
683 }
684 } catch (RemoteException e) {
685 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
686 } finally {
687 Binder.restoreCallingIdentity(identity);
688 }
689
690 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
691 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000692 }
693 }
694
695 @Override
696 public boolean isQuietModeEnabled(int userHandle) {
697 synchronized (mPackagesLock) {
698 UserInfo info;
699 synchronized (mUsersLock) {
700 info = getUserInfoLU(userHandle);
701 }
702 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000703 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000704 }
705 return info.isQuietModeEnabled();
706 }
707 }
708
Kenny Guya52dc3e2014-02-11 15:33:14 +0000709 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100710 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600711 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100712 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100713 // if the user is already unlocked, no need to show a profile challenge
714 setQuietModeEnabled(userHandle, false);
715 return true;
716 }
717
718 long identity = Binder.clearCallingIdentity();
719 try {
720 // otherwise, we show a profile challenge to trigger decryption of the user
721 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
722 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100723 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
724 // lock, confirm screenlock page will know and show personal challenge, and unlock
725 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100726 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
727 userHandle);
728 if (unlockIntent == null) {
729 return false;
730 }
731 if (target != null) {
732 unlockIntent.putExtra(Intent.EXTRA_INTENT, target);
733 }
734 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
735 mContext.startActivity(unlockIntent);
736 } finally {
737 Binder.restoreCallingIdentity(identity);
738 }
739 return false;
740 }
741
742 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100743 public void setUserEnabled(int userId) {
744 checkManageUsersPermission("enable user");
745 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700746 UserInfo info;
747 synchronized (mUsersLock) {
748 info = getUserInfoLU(userId);
749 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100750 if (info != null && !info.isEnabled()) {
751 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800752 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100753 }
754 }
755 }
756
757 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700758 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000759 checkManageUsersPermission("query user");
760 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700761 return userWithName(getUserInfoLU(userId));
762 }
763 }
764
765 /**
766 * Returns a UserInfo object with the name filled in, for Owner, or the original
767 * if the name is already set.
768 */
769 private UserInfo userWithName(UserInfo orig) {
770 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
771 UserInfo withName = new UserInfo(orig);
772 withName.name = getOwnerName();
773 return withName;
774 } else {
775 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000776 }
777 }
778
779 @Override
780 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000781 int callingUserId = UserHandle.getCallingUserId();
782 if (callingUserId != userId && !hasManageUsersPermission()) {
783 synchronized (mPackagesLock) {
784 if (!isSameProfileGroupLP(callingUserId, userId)) {
785 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000786 "You need MANAGE_USERS permission to: check if specified user a " +
787 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000788 }
789 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000790 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700791 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000792 UserInfo userInfo = getUserInfoLU(userId);
793 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700794 }
795 }
796
Amith Yamasani71e6c692013-03-24 17:39:28 -0700797 @Override
798 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700799 synchronized (mUsersLock) {
800 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700801 }
802 }
803
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700804 @Override
805 public boolean canHaveRestrictedProfile(int userId) {
806 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700807 synchronized (mUsersLock) {
808 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700809 if (userInfo == null || !userInfo.canHaveProfile()) {
810 return false;
811 }
812 if (!userInfo.isAdmin()) {
813 return false;
814 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800815 // restricted profile can be created if there is no DO set and the admin user has no PO;
816 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700817 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700818 }
819
Amith Yamasani195263742012-08-21 15:40:12 -0700820 /*
821 * Should be locked on mUsers before calling this.
822 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700823 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800824 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700825 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800826 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700827 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
828 return null;
829 }
Amith Yamasani12747872015-12-07 14:19:49 -0800830 return userData != null ? userData.info : null;
831 }
832
833 private UserData getUserDataLU(int userId) {
834 final UserData userData = mUsers.get(userId);
835 // If it is partial and not in the process of being removed, return as unknown user.
836 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
837 return null;
838 }
839 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700840 }
841
Fyodor Kupolov82402752015-10-28 14:54:51 -0700842 /**
843 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
844 * <p>No permissions checking or any addition checks are made</p>
845 */
846 private UserInfo getUserInfoNoChecks(int userId) {
847 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800848 final UserData userData = mUsers.get(userId);
849 return userData != null ? userData.info : null;
850 }
851 }
852
853 /**
854 * Obtains {@link #mUsersLock} and return UserData from mUsers.
855 * <p>No permissions checking or any addition checks are made</p>
856 */
857 private UserData getUserDataNoChecks(int userId) {
858 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700859 return mUsers.get(userId);
860 }
861 }
862
Amith Yamasani236b2b52015-08-18 14:32:14 -0700863 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700864 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700865 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700866 }
867
Amith Yamasani258848d2012-08-10 17:06:33 -0700868 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700869 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700870 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700871 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700872 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800873 UserData userData = getUserDataNoChecks(userId);
874 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700875 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
876 return;
877 }
Amith Yamasani12747872015-12-07 14:19:49 -0800878 if (name != null && !name.equals(userData.info.name)) {
879 userData.info.name = name;
880 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700881 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700882 }
883 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700884 if (changed) {
885 sendUserInfoChangedBroadcast(userId);
886 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700887 }
888
Amith Yamasani258848d2012-08-10 17:06:33 -0700889 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700890 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700891 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100892 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
893 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
894 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700895 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100896 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700897 }
898
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100899
900
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700901 private void sendUserInfoChangedBroadcast(int userId) {
902 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
903 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
904 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700905 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700906 }
907
Amith Yamasani258848d2012-08-10 17:06:33 -0700908 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100909 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100910 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700911 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100912 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
913 if (targetUserInfo == null || targetUserInfo.partial) {
914 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700915 return null;
916 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100917
918 final int callingUserId = UserHandle.getCallingUserId();
919 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
920 final int targetGroupId = targetUserInfo.profileGroupId;
921 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
922 && callingGroupId == targetGroupId);
923 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100924 checkManageUsersPermission("get the icon of a user who is not related");
925 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100926
927 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700928 return null;
929 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100930 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700931 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100932
933 try {
934 return ParcelFileDescriptor.open(
935 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
936 } catch (FileNotFoundException e) {
937 Log.e(LOG_TAG, "Couldn't find icon file", e);
938 }
939 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700940 }
941
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700942 public void makeInitialized(int userId) {
943 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800944 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800945 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800946 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800947 userData = mUsers.get(userId);
948 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700949 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800950 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700951 }
Amith Yamasani12747872015-12-07 14:19:49 -0800952 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
953 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800954 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700955 }
956 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800957 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800958 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800959 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700960 }
961
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700962 /**
963 * If default guest restrictions haven't been initialized yet, add the basic
964 * restrictions.
965 */
966 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800967 synchronized (mGuestRestrictions) {
968 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700969 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800970 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800971 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
972 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
973 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700974 }
975 }
976
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800977 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530978 public Bundle getDefaultGuestRestrictions() {
979 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800980 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530981 return new Bundle(mGuestRestrictions);
982 }
983 }
984
985 @Override
986 public void setDefaultGuestRestrictions(Bundle restrictions) {
987 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800988 synchronized (mGuestRestrictions) {
989 mGuestRestrictions.clear();
990 mGuestRestrictions.putAll(restrictions);
991 }
992 synchronized (mPackagesLock) {
993 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530994 }
995 }
996
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800997 /**
998 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
999 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001000 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001001 @Nullable Bundle global) {
1002 Preconditions.checkNotNull(local);
1003 boolean globalChanged = false;
1004 boolean localChanged;
1005 synchronized (mRestrictionsLock) {
1006 if (global != null) {
1007 // Update global.
1008 globalChanged = !UserRestrictionsUtils.areEqual(
1009 mDevicePolicyGlobalUserRestrictions, global);
1010 if (globalChanged) {
1011 mDevicePolicyGlobalUserRestrictions = global;
1012 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001013 // Remember the global restriction owner userId to be able to make a distinction
1014 // in getUserRestrictionSource on who set local policies.
1015 mGlobalRestrictionOwnerUserId = userId;
1016 } else {
1017 // When profile owner sets restrictions it passes null global bundle and we reset
1018 // global restriction owner userId.
1019 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001020 }
1021 {
1022 // Update local.
1023 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1024 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1025 if (localChanged) {
1026 mDevicePolicyLocalUserRestrictions.put(userId, local);
1027 }
1028 }
1029 }
1030 if (DBG) {
1031 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1032 + " global=" + global + (globalChanged ? " (changed)" : "")
1033 + " local=" + local + (localChanged ? " (changed)" : "")
1034 );
1035 }
1036 // Don't call them within the mRestrictionsLock.
1037 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001038 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001039 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001040 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001041 if (globalChanged) {
1042 writeUserListLP();
1043 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001044 }
1045
1046 synchronized (mRestrictionsLock) {
1047 if (globalChanged) {
1048 applyUserRestrictionsForAllUsersLR();
1049 } else if (localChanged) {
1050 applyUserRestrictionsLR(userId);
1051 }
1052 }
1053 }
1054
Makoto Onuki068c54a2015-10-13 14:34:03 -07001055 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001056 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001057 final Bundle baseRestrictions =
1058 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1059 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1060 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001061
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001062 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1063 // Common case first.
1064 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001065 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001066 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1067 UserRestrictionsUtils.merge(effective, global);
1068 UserRestrictionsUtils.merge(effective, local);
1069
Makoto Onuki068c54a2015-10-13 14:34:03 -07001070 return effective;
1071 }
1072
1073 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001074 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001075 if (DBG) {
1076 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1077 }
1078 mCachedEffectiveUserRestrictions.remove(userId);
1079 }
1080
1081 private Bundle getEffectiveUserRestrictions(int userId) {
1082 synchronized (mRestrictionsLock) {
1083 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1084 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001085 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001086 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1087 }
1088 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001089 }
1090 }
1091
Makoto Onuki068c54a2015-10-13 14:34:03 -07001092 /** @return a specific user restriction that's in effect currently. */
1093 @Override
1094 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001095 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1096 return false;
1097 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001098 Bundle restrictions = getEffectiveUserRestrictions(userId);
1099 return restrictions != null && restrictions.getBoolean(restrictionKey);
1100 }
1101
1102 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001103 * @hide
1104 *
1105 * Returns who set a user restriction on a user.
1106 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1107 * @param restrictionKey the string key representing the restriction
1108 * @param userId the id of the user for whom to retrieve the restrictions.
1109 * @return The source of user restriction. Any combination of
1110 * {@link UserManager#RESTRICTION_NOT_SET},
1111 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1112 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1113 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1114 */
1115 @Override
1116 public int getUserRestrictionSource(String restrictionKey, int userId) {
1117 checkManageUsersPermission("getUserRestrictionSource");
1118 int result = UserManager.RESTRICTION_NOT_SET;
1119
1120 // Shortcut for the most common case
1121 if (!hasUserRestriction(restrictionKey, userId)) {
1122 return result;
1123 }
1124
1125 if (hasBaseUserRestriction(restrictionKey, userId)) {
1126 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1127 }
1128
1129 synchronized(mRestrictionsLock) {
1130 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1131 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1132 && localRestrictions.getBoolean(restrictionKey)) {
1133 // Local restrictions may have been set by device owner the userId of which is
1134 // stored in mGlobalRestrictionOwnerUserId.
1135 if (mGlobalRestrictionOwnerUserId == userId) {
1136 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1137 } else {
1138 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1139 }
1140 }
1141 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1142 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1143 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1144 }
1145 }
1146
1147 return result;
1148 }
1149
1150 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001151 * @return UserRestrictions that are in effect currently. This always returns a new
1152 * {@link Bundle}.
1153 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001154 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001155 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001156 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001157 }
1158
1159 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001160 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1161 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001162 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1163 return false;
1164 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001165 synchronized (mRestrictionsLock) {
1166 Bundle bundle = mBaseUserRestrictions.get(userId);
1167 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1168 }
1169 }
1170
1171 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001172 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001173 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001174 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1175 return;
1176 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001177 synchronized (mRestrictionsLock) {
1178 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1179 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001180 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1181 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001182 newRestrictions.putBoolean(key, value);
1183
Fyodor Kupolov82402752015-10-28 14:54:51 -07001184 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001185 }
1186 }
1187
Makoto Onuki068c54a2015-10-13 14:34:03 -07001188 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001189 * Optionally updating user restrictions, calculate the effective user restrictions and also
1190 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001191 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001192 * @param newRestrictions User restrictions to set.
1193 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001194 * @param userId target user ID.
1195 */
1196 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001197 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001198 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001199
1200 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1201 mAppliedUserRestrictions.get(userId));
1202
1203 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001204 if (newRestrictions != null) {
1205 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001206 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1207
1208 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001209 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1210 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001211
1212 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1213 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001214 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001215 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001216 }
1217
Fyodor Kupolov82402752015-10-28 14:54:51 -07001218 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001219
Makoto Onuki759a7632015-10-28 16:43:10 -07001220 mCachedEffectiveUserRestrictions.put(userId, effective);
1221
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001222 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001223 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001224 debug("Applying user restrictions: userId=" + userId
1225 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001226 }
1227
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001228 if (mAppOpsService != null) { // We skip it until system-ready.
1229 final long token = Binder.clearCallingIdentity();
1230 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001231 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001232 } catch (RemoteException e) {
1233 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1234 } finally {
1235 Binder.restoreCallingIdentity(token);
1236 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001237 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001238
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001239 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001240
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001241 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001242 }
1243
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001244 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001245 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001246 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1247 // actually, but we still need some kind of synchronization otherwise we might end up
1248 // calling listeners out-of-order, thus "LR".
1249
1250 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1251 return;
1252 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001253
1254 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1255 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1256
1257 mHandler.post(new Runnable() {
1258 @Override
1259 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001260 UserRestrictionsUtils.applyUserRestrictions(
1261 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001262
Makoto Onukid45a4a22015-11-02 17:17:38 -08001263 final UserRestrictionsListener[] listeners;
1264 synchronized (mUserRestrictionsListeners) {
1265 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1266 mUserRestrictionsListeners.toArray(listeners);
1267 }
1268 for (int i = 0; i < listeners.length; i++) {
1269 listeners[i].onUserRestrictionsChanged(userId,
1270 newRestrictionsFinal, prevRestrictionsFinal);
1271 }
1272 }
1273 });
1274 }
1275
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001276 // Package private for the inner class.
1277 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001278 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001279 }
1280
1281 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001282 // Package private for the inner class.
1283 void applyUserRestrictionsForAllUsersLR() {
1284 if (DBG) {
1285 debug("applyUserRestrictionsForAllUsersLR");
1286 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001287 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001288 mCachedEffectiveUserRestrictions.clear();
1289
Makoto Onuki068c54a2015-10-13 14:34:03 -07001290 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1291 // it on a handler.
1292 final Runnable r = new Runnable() {
1293 @Override
1294 public void run() {
1295 // Then get the list of running users.
1296 final int[] runningUsers;
1297 try {
1298 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1299 } catch (RemoteException e) {
1300 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1301 return;
1302 }
1303 // Then re-calculate the effective restrictions and apply, only for running users.
1304 // It's okay if a new user has started after the getRunningUserIds() call,
1305 // because we'll do the same thing (re-calculate the restrictions and apply)
1306 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001307 synchronized (mRestrictionsLock) {
1308 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001309 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001310 }
1311 }
1312 }
1313 };
1314 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001315 }
1316
Amith Yamasani258848d2012-08-10 17:06:33 -07001317 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001318 * Check if we've hit the limit of how many users can be created.
1319 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001320 private boolean isUserLimitReached() {
1321 int count;
1322 synchronized (mUsersLock) {
1323 count = getAliveUsersExcludingGuestsCountLU();
1324 }
1325 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001326 }
1327
1328 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001329 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001330 checkManageUsersPermission("check if more managed profiles can be added.");
1331 if (ActivityManager.isLowRamDeviceStatic()) {
1332 return false;
1333 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001334 if (!mContext.getPackageManager().hasSystemFeature(
1335 PackageManager.FEATURE_MANAGED_USERS)) {
1336 return false;
1337 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001338 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001339 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1340 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1341 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001342 return false;
1343 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001344 synchronized(mUsersLock) {
1345 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001346 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001347 return false;
1348 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001349 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1350 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001351 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001352 return usersCountAfterRemoving == 1
1353 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001354 }
1355 }
1356
Fyodor Kupolov82402752015-10-28 14:54:51 -07001357 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001358 int aliveUserCount = 0;
1359 final int totalUserCount = mUsers.size();
1360 // Skip over users being removed
1361 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001362 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001363 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001364 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001365 aliveUserCount++;
1366 }
1367 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001368 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001369 }
1370
1371 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001372 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001373 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1374 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1375 * permissions can make certain calls to the UserManager.
1376 *
1377 * @param message used as message if SecurityException is thrown
1378 * @throws SecurityException if the caller does not have enough privilege.
1379 */
1380 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1381 final int uid = Binder.getCallingUid();
1382 if (uid != Process.SYSTEM_UID && uid != 0
1383 && ActivityManager.checkComponentPermission(
1384 Manifest.permission.MANAGE_USERS,
1385 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1386 && ActivityManager.checkComponentPermission(
1387 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1388 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1389 throw new SecurityException(
1390 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1391 + message);
1392 }
1393 }
1394
1395 /**
1396 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001397 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001398 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001399 *
1400 * @param message used as message if SecurityException is thrown
1401 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001402 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001403 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001404 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001405 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001406 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1407 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001408 }
1409
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001410 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001411 * @return whether the calling UID is system UID or root's UID or the calling app has the
1412 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1413 */
1414 private static final boolean hasManageUsersPermission() {
1415 final int callingUid = Binder.getCallingUid();
1416 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1417 || callingUid == Process.ROOT_UID
1418 || ActivityManager.checkComponentPermission(
1419 android.Manifest.permission.MANAGE_USERS,
1420 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1421 }
1422
1423 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001424 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1425 * UserManager.
1426 *
1427 * @param message used as message if SecurityException is thrown
1428 * @throws SecurityException if the caller is not system or root
1429 */
1430 private static void checkSystemOrRoot(String message) {
1431 final int uid = Binder.getCallingUid();
1432 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1433 throw new SecurityException("Only system may: " + message);
1434 }
1435 }
1436
Fyodor Kupolov82402752015-10-28 14:54:51 -07001437 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001438 try {
1439 File dir = new File(mUsersDir, Integer.toString(info.id));
1440 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001441 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001442 if (!dir.exists()) {
1443 dir.mkdir();
1444 FileUtils.setPermissions(
1445 dir.getPath(),
1446 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1447 -1, -1);
1448 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001449 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001450 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001451 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001452 info.iconPath = file.getAbsolutePath();
1453 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001454 try {
1455 os.close();
1456 } catch (IOException ioe) {
1457 // What the ... !
1458 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001459 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001460 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001461 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001462 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001463 }
1464
Amith Yamasani0b285492011-04-14 17:35:23 -07001465 /**
1466 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1467 * cache it elsewhere.
1468 * @return the array of user ids.
1469 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001470 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001471 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001472 return mUserIds;
1473 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001474 }
1475
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001476 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001477 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001478 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001479 return;
1480 }
1481 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001482 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001483 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001484 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001485 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001486 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001487 int type;
1488 while ((type = parser.next()) != XmlPullParser.START_TAG
1489 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001490 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001491 }
1492
1493 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001494 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001495 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001496 return;
1497 }
1498
Amith Yamasani2a003292012-08-14 18:25:45 -07001499 mNextSerialNumber = -1;
1500 if (parser.getName().equals(TAG_USERS)) {
1501 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1502 if (lastSerialNumber != null) {
1503 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1504 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001505 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1506 if (versionNumber != null) {
1507 mUserVersion = Integer.parseInt(versionNumber);
1508 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001509 }
1510
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001511 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1512
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001513 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301514 if (type == XmlPullParser.START_TAG) {
1515 final String name = parser.getName();
1516 if (name.equals(TAG_USER)) {
1517 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001518
Amith Yamasani12747872015-12-07 14:19:49 -08001519 UserData userData = readUserLP(Integer.parseInt(id));
1520
1521 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001522 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001523 mUsers.put(userData.info.id, userData);
1524 if (mNextSerialNumber < 0
1525 || mNextSerialNumber <= userData.info.id) {
1526 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001527 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301528 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001529 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301530 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001531 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1532 && type != XmlPullParser.END_TAG) {
1533 if (type == XmlPullParser.START_TAG) {
1534 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001535 synchronized (mGuestRestrictions) {
1536 UserRestrictionsUtils
1537 .readRestrictions(parser, mGuestRestrictions);
1538 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001539 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1540 ) {
1541 UserRestrictionsUtils.readRestrictions(parser,
1542 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001543 }
1544 break;
1545 }
1546 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001547 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1548 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1549 if (ownerUserId != null) {
1550 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1551 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001552 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001553 }
1554 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001555 synchronized (mRestrictionsLock) {
1556 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1557 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001558 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001559 upgradeIfNecessaryLP();
1560 } catch (IOException | XmlPullParserException e) {
1561 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001562 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001563 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001564 }
1565 }
1566
Amith Yamasani6f34b412012-10-22 18:19:27 -07001567 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001568 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001569 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001570 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001571 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001572 int userVersion = mUserVersion;
1573 if (userVersion < 1) {
1574 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001575 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1576 if ("Primary".equals(userData.info.name)) {
1577 userData.info.name =
1578 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1579 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001580 }
1581 userVersion = 1;
1582 }
1583
Amith Yamasanibc9625052012-11-15 14:39:18 -08001584 if (userVersion < 2) {
1585 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001586 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1587 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1588 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1589 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001590 }
1591 userVersion = 2;
1592 }
1593
Amith Yamasani350962c2013-08-06 11:18:53 -07001594
Amith Yamasani5e486f52013-08-07 11:06:44 -07001595 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001596 userVersion = 4;
1597 }
1598
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001599 if (userVersion < 5) {
1600 initDefaultGuestRestrictions();
1601 userVersion = 5;
1602 }
1603
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001604 if (userVersion < 6) {
1605 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001606 synchronized (mUsersLock) {
1607 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001608 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001609 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001610 if (!splitSystemUser && userData.info.isRestricted()
1611 && (userData.info.restrictedProfileParentId
1612 == UserInfo.NO_PROFILE_GROUP_ID)) {
1613 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1614 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001615 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001616 }
1617 }
1618 userVersion = 6;
1619 }
1620
Amith Yamasani6f34b412012-10-22 18:19:27 -07001621 if (userVersion < USER_VERSION) {
1622 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1623 + USER_VERSION);
1624 } else {
1625 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001626
1627 if (originalVersion < mUserVersion) {
1628 writeUserListLP();
1629 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001630 }
1631 }
1632
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001633 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001634 int flags = UserInfo.FLAG_INITIALIZED;
1635 // In split system user mode, the admin and primary flags are assigned to the first human
1636 // user.
1637 if (!UserManager.isSplitSystemUser()) {
1638 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1639 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001640 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001641 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001642 UserData userData = new UserData();
1643 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001644 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001645 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001646 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001647 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001648 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001649
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001650 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001651 synchronized (mRestrictionsLock) {
1652 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1653 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001654
Fyodor Kupolov82402752015-10-28 14:54:51 -07001655 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001656 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001657
Amith Yamasani12747872015-12-07 14:19:49 -08001658 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001659 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001660 }
1661
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001662 private String getOwnerName() {
1663 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1664 }
1665
Amith Yamasani12747872015-12-07 14:19:49 -08001666 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001667 if (DBG) {
1668 debug("scheduleWriteUser");
1669 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001670 // No need to wrap it within a lock -- worst case, we'll just post the same message
1671 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001672 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1673 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001674 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1675 }
1676 }
1677
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001678 /*
1679 * Writes the user file in this format:
1680 *
1681 * <user flags="20039023" id="0">
1682 * <name>Primary</name>
1683 * </user>
1684 */
Amith Yamasani12747872015-12-07 14:19:49 -08001685 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001687 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001688 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001689 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001690 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001691 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001692 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001693 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1694
1695 // XmlSerializer serializer = XmlUtils.serializerInstance();
1696 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001697 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001698 serializer.startDocument(null, true);
1699 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1700
Amith Yamasani12747872015-12-07 14:19:49 -08001701 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001702 serializer.startTag(null, TAG_USER);
1703 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001704 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001705 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001706 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1707 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1708 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001709 if (userInfo.lastLoggedInFingerprint != null) {
1710 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1711 userInfo.lastLoggedInFingerprint);
1712 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001713 if (userInfo.iconPath != null) {
1714 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1715 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001716 if (userInfo.partial) {
1717 serializer.attribute(null, ATTR_PARTIAL, "true");
1718 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001719 if (userInfo.guestToRemove) {
1720 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1721 }
Kenny Guy2a764942014-04-02 13:29:20 +01001722 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1723 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1724 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001725 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001726 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1727 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1728 Integer.toString(userInfo.restrictedProfileParentId));
1729 }
Amith Yamasani12747872015-12-07 14:19:49 -08001730 // Write seed data
1731 if (userData.persistSeedData) {
1732 if (userData.seedAccountName != null) {
1733 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1734 }
1735 if (userData.seedAccountType != null) {
1736 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1737 }
1738 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001739 if (userInfo.name != null) {
1740 serializer.startTag(null, TAG_NAME);
1741 serializer.text(userInfo.name);
1742 serializer.endTag(null, TAG_NAME);
1743 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001744 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001745 UserRestrictionsUtils.writeRestrictions(serializer,
1746 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1747 UserRestrictionsUtils.writeRestrictions(serializer,
1748 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1749 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001750 }
Amith Yamasani12747872015-12-07 14:19:49 -08001751
1752 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001753 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001754 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001755 serializer.endTag(null, TAG_ACCOUNT);
1756 }
1757
Amith Yamasani12747872015-12-07 14:19:49 -08001758 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1759 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1760 userData.seedAccountOptions.saveToXml(serializer);
1761 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1762 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001763 serializer.endTag(null, TAG_USER);
1764
1765 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001766 userFile.finishWrite(fos);
1767 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001768 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001769 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001770 }
1771 }
1772
1773 /*
1774 * Writes the user list file in this format:
1775 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001776 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001777 * <user id="0"></user>
1778 * <user id="2"></user>
1779 * </users>
1780 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001781 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001782 if (DBG) {
1783 debug("writeUserList");
1784 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001785 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001786 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001787 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001788 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001789 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1790
1791 // XmlSerializer serializer = XmlUtils.serializerInstance();
1792 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001793 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001794 serializer.startDocument(null, true);
1795 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1796
1797 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001798 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001799 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001800
Adam Lesinskieddeb492014-09-08 17:50:03 -07001801 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001802 synchronized (mGuestRestrictions) {
1803 UserRestrictionsUtils
1804 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1805 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301806 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001807 synchronized (mRestrictionsLock) {
1808 UserRestrictionsUtils.writeRestrictions(serializer,
1809 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1810 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001811 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1812 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1813 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001814 int[] userIdsToWrite;
1815 synchronized (mUsersLock) {
1816 userIdsToWrite = new int[mUsers.size()];
1817 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001818 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001819 userIdsToWrite[i] = user.id;
1820 }
1821 }
1822 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001823 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001824 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001825 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001826 }
1827
1828 serializer.endTag(null, TAG_USERS);
1829
1830 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001831 userListFile.finishWrite(fos);
1832 } catch (Exception e) {
1833 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001834 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001835 }
1836 }
1837
Amith Yamasani12747872015-12-07 14:19:49 -08001838 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001839 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001840 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001841 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001842 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001843 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001844 long creationTime = 0L;
1845 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001846 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001847 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001848 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001849 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001850 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001851 boolean persistSeedData = false;
1852 String seedAccountName = null;
1853 String seedAccountType = null;
1854 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001855 Bundle baseRestrictions = new Bundle();
1856 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001857
1858 FileInputStream fis = null;
1859 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001860 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001861 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001862 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001863 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001864 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001865 int type;
1866 while ((type = parser.next()) != XmlPullParser.START_TAG
1867 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001868 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001869 }
1870
1871 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001872 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001873 return null;
1874 }
1875
1876 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001877 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1878 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001879 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001880 return null;
1881 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001882 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1883 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001884 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001885 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1886 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001887 lastLoggedInFingerprint = parser.getAttributeValue(null,
1888 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001889 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1890 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001891 restrictedProfileParentId = readIntAttribute(parser,
1892 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001893 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1894 if ("true".equals(valueString)) {
1895 partial = true;
1896 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001897 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1898 if ("true".equals(valueString)) {
1899 guestToRemove = true;
1900 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001901
Amith Yamasani12747872015-12-07 14:19:49 -08001902 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1903 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1904 if (seedAccountName != null || seedAccountType != null) {
1905 persistSeedData = true;
1906 }
1907
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001908 int outerDepth = parser.getDepth();
1909 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1910 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1911 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1912 continue;
1913 }
1914 String tag = parser.getName();
1915 if (TAG_NAME.equals(tag)) {
1916 type = parser.next();
1917 if (type == XmlPullParser.TEXT) {
1918 name = parser.getText();
1919 }
1920 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001921 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1922 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1923 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001924 } else if (TAG_ACCOUNT.equals(tag)) {
1925 type = parser.next();
1926 if (type == XmlPullParser.TEXT) {
1927 account = parser.getText();
1928 }
Amith Yamasani12747872015-12-07 14:19:49 -08001929 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1930 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1931 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001932 }
1933 }
1934 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001935
Amith Yamasani12747872015-12-07 14:19:49 -08001936 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001937 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001938 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001939 userInfo.creationTime = creationTime;
1940 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001941 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001942 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001943 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001944 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001945 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001946
1947 // Create the UserData object that's internal to this class
1948 UserData userData = new UserData();
1949 userData.info = userInfo;
1950 userData.account = account;
1951 userData.seedAccountName = seedAccountName;
1952 userData.seedAccountType = seedAccountType;
1953 userData.persistSeedData = persistSeedData;
1954 userData.seedAccountOptions = seedAccountOptions;
1955
Makoto Onuki068c54a2015-10-13 14:34:03 -07001956 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001957 mBaseUserRestrictions.put(id, baseRestrictions);
1958 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001959 }
Amith Yamasani12747872015-12-07 14:19:49 -08001960 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001961 } catch (IOException ioe) {
1962 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001963 } finally {
1964 if (fis != null) {
1965 try {
1966 fis.close();
1967 } catch (IOException e) {
1968 }
1969 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001970 }
1971 return null;
1972 }
1973
Amith Yamasani920ace02012-09-20 22:15:37 -07001974 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1975 String valueString = parser.getAttributeValue(null, attr);
1976 if (valueString == null) return defaultValue;
1977 try {
1978 return Integer.parseInt(valueString);
1979 } catch (NumberFormatException nfe) {
1980 return defaultValue;
1981 }
1982 }
1983
1984 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1985 String valueString = parser.getAttributeValue(null, attr);
1986 if (valueString == null) return defaultValue;
1987 try {
1988 return Long.parseLong(valueString);
1989 } catch (NumberFormatException nfe) {
1990 return defaultValue;
1991 }
1992 }
1993
Amith Yamasanib82add22013-07-09 11:24:44 -07001994 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001995 * Removes the app restrictions file for a specific package and user id, if it exists.
1996 */
1997 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1998 synchronized (mPackagesLock) {
1999 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002000 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002001 if (resFile.exists()) {
2002 resFile.delete();
2003 }
2004 }
2005 }
2006
Kenny Guya52dc3e2014-02-11 15:33:14 +00002007 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002008 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00002009 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01002010 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002011 }
2012
Amith Yamasani258848d2012-08-10 17:06:33 -07002013 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002014 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002015 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002016 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002017 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002018
Jessica Hummelbe81c802014-04-22 15:49:22 +01002019 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002020 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002021 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2022 return null;
2023 }
phweisse9c44062016-02-10 12:57:38 +01002024 return createUserInternalUnchecked(name, flags, parentId);
2025 }
2026
2027 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002028 if (ActivityManager.isLowRamDeviceStatic()) {
2029 return null;
2030 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002031 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002032 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002033 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002034 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002035 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002036 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002037 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002038 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002039 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002040 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002041 if (parentId != UserHandle.USER_NULL) {
2042 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002043 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002044 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002045 if (parent == null) return null;
2046 }
2047 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2048 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2049 return null;
2050 }
2051 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
2052 // If we're not adding a guest user or a managed profile and the limit has
2053 // been reached, cannot add a user.
2054 return null;
2055 }
2056 // If we're adding a guest and there already exists one, bail.
2057 if (isGuest && findCurrentGuestUser() != null) {
2058 return null;
2059 }
2060 // In legacy mode, restricted profile's parent can only be the owner user
2061 if (isRestricted && !UserManager.isSplitSystemUser()
2062 && (parentId != UserHandle.USER_SYSTEM)) {
2063 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2064 return null;
2065 }
2066 if (isRestricted && UserManager.isSplitSystemUser()) {
2067 if (parent == null) {
2068 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2069 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002070 return null;
2071 }
Amith Yamasani12747872015-12-07 14:19:49 -08002072 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002073 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2074 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002075 return null;
2076 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002077 }
Suprabh Shuklacc30b0e72016-05-20 14:41:22 -07002078 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0
2079 && (flags & UserInfo.FLAG_DEMO) == 0) {
Lenka Trochtova024f9792016-02-17 13:55:17 +01002080 Log.e(LOG_TAG,
2081 "Ephemeral users are supported on split-system-user systems only.");
2082 return null;
2083 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002084 // In split system user mode, we assign the first human user the primary flag.
2085 // And if there is no device owner, we also assign the admin flag to primary user.
2086 if (UserManager.isSplitSystemUser()
2087 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2088 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002089 synchronized (mUsersLock) {
2090 if (!mIsDeviceManaged) {
2091 flags |= UserInfo.FLAG_ADMIN;
2092 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002093 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002094 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002095
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002096 userId = getNextAvailableId();
2097 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002098 boolean ephemeralGuests = Resources.getSystem()
2099 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002100
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002101 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002102 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2103 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2104 || (parent != null && parent.info.isEphemeral())) {
2105 flags |= UserInfo.FLAG_EPHEMERAL;
2106 }
2107
2108 userInfo = new UserInfo(userId, name, null, flags);
2109 userInfo.serialNumber = mNextSerialNumber++;
2110 long now = System.currentTimeMillis();
2111 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2112 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002113 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002114 userData = new UserData();
2115 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002116 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002117 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002118 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002119 writeUserListLP();
2120 if (parent != null) {
2121 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002122 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2123 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002124 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002125 }
Amith Yamasani12747872015-12-07 14:19:49 -08002126 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002127 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002128 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2129 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002130 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002131 }
Amith Yamasani12747872015-12-07 14:19:49 -08002132 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002133 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002134 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002135 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002136 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002137 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002138 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002139 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002140 mPm.createNewUser(userId);
2141 userInfo.partial = false;
2142 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002143 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002144 }
2145 updateUserIds();
2146 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002147 if (isGuest) {
2148 synchronized (mGuestRestrictions) {
2149 restrictions.putAll(mGuestRestrictions);
2150 }
2151 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002152 synchronized (mRestrictionsLock) {
2153 mBaseUserRestrictions.append(userId, restrictions);
2154 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002155 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2156 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2157 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2158 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002159 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002160 } finally {
2161 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002162 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002163 return userInfo;
2164 }
2165
Amith Yamasani0b285492011-04-14 17:35:23 -07002166 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002167 * @hide
2168 */
Amith Yamasani12747872015-12-07 14:19:49 -08002169 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002170 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2171 checkManageUsersPermission("setupRestrictedProfile");
2172 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2173 if (user == null) {
2174 return null;
2175 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002176 long identity = Binder.clearCallingIdentity();
2177 try {
2178 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2179 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2180 // the putIntForUser() will fail.
2181 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2182 android.provider.Settings.Secure.LOCATION_MODE,
2183 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2184 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2185 } finally {
2186 Binder.restoreCallingIdentity(identity);
2187 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002188 return user;
2189 }
2190
2191 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002192 * Find the current guest user. If the Guest user is partial,
2193 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002194 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002195 private UserInfo findCurrentGuestUser() {
2196 synchronized (mUsersLock) {
2197 final int size = mUsers.size();
2198 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002199 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002200 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2201 return user;
2202 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002203 }
2204 }
2205 return null;
2206 }
2207
2208 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002209 * Mark this guest user for deletion to allow us to create another guest
2210 * and switch to that user before actually removing this guest.
2211 * @param userHandle the userid of the current guest
2212 * @return whether the user could be marked for deletion
2213 */
Amith Yamasani12747872015-12-07 14:19:49 -08002214 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002215 public boolean markGuestForDeletion(int userHandle) {
2216 checkManageUsersPermission("Only the system can remove users");
2217 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2218 UserManager.DISALLOW_REMOVE_USER, false)) {
2219 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2220 return false;
2221 }
2222
2223 long ident = Binder.clearCallingIdentity();
2224 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002225 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002226 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002227 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002228 userData = mUsers.get(userHandle);
2229 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002230 return false;
2231 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002232 }
Amith Yamasani12747872015-12-07 14:19:49 -08002233 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002234 return false;
2235 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002236 // We set this to a guest user that is to be removed. This is a temporary state
2237 // where we are allowed to add new Guest users, even if this one is still not
2238 // removed. This user will still show up in getUserInfo() calls.
2239 // If we don't get around to removing this Guest user, it will be purged on next
2240 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002241 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002242 // Mark it as disabled, so that it isn't returned any more when
2243 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002244 userData.info.flags |= UserInfo.FLAG_DISABLED;
2245 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002246 }
2247 } finally {
2248 Binder.restoreCallingIdentity(ident);
2249 }
2250 return true;
2251 }
2252
2253 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002254 * Removes a user and all data directories created for that user. This method should be called
2255 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002256 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002257 */
Amith Yamasani12747872015-12-07 14:19:49 -08002258 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002259 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002260 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002261 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2262 UserManager.DISALLOW_REMOVE_USER, false)) {
2263 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2264 return false;
2265 }
2266
Kenny Guyee58b4f2014-05-23 15:19:53 +01002267 long ident = Binder.clearCallingIdentity();
2268 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002269 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002270 int currentUser = ActivityManager.getCurrentUser();
2271 if (currentUser == userHandle) {
2272 Log.w(LOG_TAG, "Current user cannot be removed");
2273 return false;
2274 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002275 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002276 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002277 userData = mUsers.get(userHandle);
2278 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002279 return false;
2280 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002281
Fyodor Kupolov82402752015-10-28 14:54:51 -07002282 // We remember deleted user IDs to prevent them from being
2283 // reused during the current boot; they can still be reused
2284 // after a reboot.
2285 mRemovingUserIds.put(userHandle, true);
2286 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002287
Kenny Guyee58b4f2014-05-23 15:19:53 +01002288 try {
2289 mAppOpsService.removeUser(userHandle);
2290 } catch (RemoteException e) {
2291 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2292 }
2293 // Set this to a partially created user, so that the user will be purged
2294 // on next startup, in case the runtime stops now before stopping and
2295 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002296 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002297 // Mark it as disabled, so that it isn't returned any more when
2298 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002299 userData.info.flags |= UserInfo.FLAG_DISABLED;
2300 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002301 }
2302
Amith Yamasani12747872015-12-07 14:19:49 -08002303 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2304 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002305 // Send broadcast to notify system that the user removed was a
2306 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002307 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002308 }
2309
2310 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2311 int res;
2312 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002313 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2314 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002315 @Override
2316 public void userStopped(int userId) {
2317 finishRemoveUser(userId);
2318 }
2319 @Override
2320 public void userStopAborted(int userId) {
2321 }
2322 });
2323 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002324 return false;
2325 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002326 return res == ActivityManager.USER_OP_SUCCESS;
2327 } finally {
2328 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002329 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002330 }
2331
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002332 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002333 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002334 // Let other services shutdown any activity and clean up their state before completely
2335 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002336 long ident = Binder.clearCallingIdentity();
2337 try {
2338 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2339 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002340 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2341 android.Manifest.permission.MANAGE_USERS,
2342
2343 new BroadcastReceiver() {
2344 @Override
2345 public void onReceive(Context context, Intent intent) {
2346 if (DBG) {
2347 Slog.i(LOG_TAG,
2348 "USER_REMOVED broadcast sent, cleaning up user data "
2349 + userHandle);
2350 }
2351 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002352 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002353 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002354 // Clean up any ActivityManager state
2355 LocalServices.getService(ActivityManagerInternal.class)
2356 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002357 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002358 }
2359 }.start();
2360 }
2361 },
2362
2363 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002364 } finally {
2365 Binder.restoreCallingIdentity(ident);
2366 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002367 }
2368
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002369 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002370 try {
2371 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2372 } catch (IllegalStateException e) {
2373 // This may be simply because the user was partially created.
2374 Slog.i(LOG_TAG,
2375 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2376 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002377
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002378 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002379 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002380 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002381 synchronized (mUsersLock) {
2382 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002383 mIsUserManaged.delete(userHandle);
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00002384 }
2385 synchronized (mUserStates) {
2386 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002387 }
2388 synchronized (mRestrictionsLock) {
2389 mBaseUserRestrictions.remove(userHandle);
2390 mAppliedUserRestrictions.remove(userHandle);
2391 mCachedEffectiveUserRestrictions.remove(userHandle);
2392 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002393 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002394 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002395 synchronized (mPackagesLock) {
2396 writeUserListLP();
2397 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002398 // Remove user file
2399 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2400 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002401 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002402
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002403 // Now that we've purged all the metadata above, destroy the actual data
2404 // on disk; if we battery pull in here we'll finish cleaning up when
2405 // reconciling after reboot.
2406 mPm.destroyUserData(userHandle,
2407 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Amith Yamasani61f57372012-08-31 12:12:28 -07002408 }
2409
Kenny Guyf8d3a232014-05-15 16:09:52 +01002410 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002411 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002412 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2413 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002414 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002415 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002416 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002417 }
2418
Amith Yamasani2a003292012-08-14 18:25:45 -07002419 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002420 public Bundle getApplicationRestrictions(String packageName) {
2421 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2422 }
2423
2424 @Override
2425 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002426 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002427 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002428 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002429 }
2430 synchronized (mPackagesLock) {
2431 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002432 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002433 }
2434 }
2435
2436 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002437 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002438 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002439 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002440 if (restrictions != null) {
2441 restrictions.setDefusable(true);
2442 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002443 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002444 if (restrictions == null || restrictions.isEmpty()) {
2445 cleanAppRestrictionsForPackage(packageName, userId);
2446 } else {
2447 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002449 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002450 }
Robin Lee66e5d962014-04-09 16:44:21 +01002451
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002452 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2453 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2454 changeIntent.setPackage(packageName);
2455 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2456 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002457 }
2458
2459 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002460 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002461 try {
2462 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002463 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002464 } catch (NameNotFoundException nnfe) {
2465 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002466 } finally {
2467 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002468 }
2469 }
2470
Fyodor Kupolov82402752015-10-28 14:54:51 -07002471 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002472 AtomicFile restrictionsFile =
2473 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2474 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002475 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002476 }
2477
2478 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002479 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002480 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002481 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002482 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002483 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002484 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002485
2486 FileInputStream fis = null;
2487 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002488 fis = restrictionsFile.openRead();
2489 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002490 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002491 XmlUtils.nextElement(parser);
2492 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002493 Slog.e(LOG_TAG, "Unable to read restrictions file "
2494 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002495 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002496 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002497 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2498 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002499 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002500 } catch (IOException|XmlPullParserException e) {
2501 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002502 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002503 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002504 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002505 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002506 }
2507
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002508 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2509 XmlPullParser parser) throws XmlPullParserException, IOException {
2510 int type = parser.getEventType();
2511 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2512 String key = parser.getAttributeValue(null, ATTR_KEY);
2513 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2514 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2515 if (multiple != null) {
2516 values.clear();
2517 int count = Integer.parseInt(multiple);
2518 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2519 if (type == XmlPullParser.START_TAG
2520 && parser.getName().equals(TAG_VALUE)) {
2521 values.add(parser.nextText().trim());
2522 count--;
2523 }
2524 }
2525 String [] valueStrings = new String[values.size()];
2526 values.toArray(valueStrings);
2527 restrictions.putStringArray(key, valueStrings);
2528 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2529 restrictions.putBundle(key, readBundleEntry(parser, values));
2530 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2531 final int outerDepth = parser.getDepth();
2532 ArrayList<Bundle> bundleList = new ArrayList<>();
2533 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2534 Bundle childBundle = readBundleEntry(parser, values);
2535 bundleList.add(childBundle);
2536 }
2537 restrictions.putParcelableArray(key,
2538 bundleList.toArray(new Bundle[bundleList.size()]));
2539 } else {
2540 String value = parser.nextText().trim();
2541 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2542 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2543 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2544 restrictions.putInt(key, Integer.parseInt(value));
2545 } else {
2546 restrictions.putString(key, value);
2547 }
2548 }
2549 }
2550 }
2551
2552 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2553 throws IOException, XmlPullParserException {
2554 Bundle childBundle = new Bundle();
2555 final int outerDepth = parser.getDepth();
2556 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2557 readEntry(childBundle, values, parser);
2558 }
2559 return childBundle;
2560 }
2561
Fyodor Kupolov82402752015-10-28 14:54:51 -07002562 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002563 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002564 AtomicFile restrictionsFile = new AtomicFile(
2565 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002566 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002567 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002568 }
2569
2570 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002571 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002572 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002573 try {
2574 fos = restrictionsFile.startWrite();
2575 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2576
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002577 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002578 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002579 serializer.startDocument(null, true);
2580 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2581
2582 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002583 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002584 serializer.endTag(null, TAG_RESTRICTIONS);
2585
2586 serializer.endDocument();
2587 restrictionsFile.finishWrite(fos);
2588 } catch (Exception e) {
2589 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002590 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2591 }
2592 }
2593
2594 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2595 throws IOException {
2596 for (String key : restrictions.keySet()) {
2597 Object value = restrictions.get(key);
2598 serializer.startTag(null, TAG_ENTRY);
2599 serializer.attribute(null, ATTR_KEY, key);
2600
2601 if (value instanceof Boolean) {
2602 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2603 serializer.text(value.toString());
2604 } else if (value instanceof Integer) {
2605 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2606 serializer.text(value.toString());
2607 } else if (value == null || value instanceof String) {
2608 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2609 serializer.text(value != null ? (String) value : "");
2610 } else if (value instanceof Bundle) {
2611 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2612 writeBundle((Bundle) value, serializer);
2613 } else if (value instanceof Parcelable[]) {
2614 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2615 Parcelable[] array = (Parcelable[]) value;
2616 for (Parcelable parcelable : array) {
2617 if (!(parcelable instanceof Bundle)) {
2618 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2619 }
2620 serializer.startTag(null, TAG_ENTRY);
2621 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2622 writeBundle((Bundle) parcelable, serializer);
2623 serializer.endTag(null, TAG_ENTRY);
2624 }
2625 } else {
2626 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2627 String[] values = (String[]) value;
2628 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2629 for (String choice : values) {
2630 serializer.startTag(null, TAG_VALUE);
2631 serializer.text(choice != null ? choice : "");
2632 serializer.endTag(null, TAG_VALUE);
2633 }
2634 }
2635 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002636 }
2637 }
2638
2639 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002640 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002641 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002642 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002643 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002644 }
2645 }
2646
2647 @Override
2648 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002649 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002650 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002651 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002652 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002653 }
2654 // Not found
2655 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002656 }
2657 }
2658
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002659 @Override
2660 public long getUserCreationTime(int userHandle) {
2661 int callingUserId = UserHandle.getCallingUserId();
2662 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002663 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002664 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002665 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002666 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002667 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002668 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002669 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002670 }
2671 }
2672 }
2673 if (userInfo == null) {
2674 throw new SecurityException("userHandle can only be the calling user or a managed "
2675 + "profile associated with this user");
2676 }
2677 return userInfo.creationTime;
2678 }
2679
Amith Yamasani0b285492011-04-14 17:35:23 -07002680 /**
2681 * Caches the list of user ids in an array, adjusting the array size when necessary.
2682 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002683 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002684 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002685 synchronized (mUsersLock) {
2686 final int userSize = mUsers.size();
2687 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002688 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002689 num++;
2690 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002691 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002692 final int[] newUsers = new int[num];
2693 int n = 0;
2694 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002695 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002696 newUsers[n++] = mUsers.keyAt(i);
2697 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002698 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002699 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002700 }
2701 }
2702
2703 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002704 * Called right before a user is started. This gives us a chance to prepare
2705 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002706 */
2707 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002708 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002709 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002710 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002711
2712 if (userId != UserHandle.USER_SYSTEM) {
2713 synchronized (mRestrictionsLock) {
2714 applyUserRestrictionsLR(userId);
2715 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002716 UserInfo userInfo = getUserInfoNoChecks(userId);
2717 if (userInfo != null && !userInfo.isInitialized()) {
2718 mPm.onBeforeUserStartUninitialized(userId);
2719 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002720 }
Amith Yamasanieb437d42016-04-29 09:31:25 -07002721
2722 maybeInitializeDemoMode(userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002723 }
2724
2725 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002726 * Called right before a user is unlocked. This gives us a chance to prepare
2727 * app storage.
2728 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002729 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002730 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002731 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002732 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002733 }
2734
2735 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002736 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasanieb437d42016-04-29 09:31:25 -07002737 * This is called with ActivityManagerService lock held.
Amith Yamasani920ace02012-09-20 22:15:37 -07002738 * @param userId the user that was just foregrounded
2739 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002740 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002741 UserData userData = getUserDataNoChecks(userId);
2742 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002743 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2744 return;
2745 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002746
2747 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002748 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002749 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002750 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002751 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2752 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002753 }
2754
Amith Yamasanieb437d42016-04-29 09:31:25 -07002755 private void maybeInitializeDemoMode(int userId) {
2756 if (UserManager.isDeviceInDemoMode(mContext)) {
2757 String demoLauncher =
2758 mContext.getResources().getString(
2759 com.android.internal.R.string.config_demoModeLauncherComponent);
2760 if (!TextUtils.isEmpty(demoLauncher)) {
2761 ComponentName componentToEnable = ComponentName.unflattenFromString(demoLauncher);
2762 try {
2763 AppGlobals.getPackageManager().setComponentEnabledSetting(componentToEnable,
2764 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, /* flags= */ 0,
2765 /* userId= */ userId);
2766 } catch (RemoteException re) {
2767 // Internal, shouldn't happen
2768 }
2769 }
2770 }
2771 }
2772
Amith Yamasani920ace02012-09-20 22:15:37 -07002773 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002774 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002775 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2776 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002777 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002778 private int getNextAvailableId() {
2779 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002780 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002781 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002782 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002783 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002784 }
2785 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002786 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002787 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002788 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002789 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002790
Amith Yamasanifc95e702013-09-26 13:20:17 -07002791 private String packageToRestrictionsFileName(String packageName) {
2792 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2793 }
2794
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002795 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002796 * Enforce that serial number stored in user directory inode matches the
2797 * given expected value. Gracefully sets the serial number if currently
2798 * undefined.
2799 *
2800 * @throws IOException when problem extracting serial number, or serial
2801 * number is mismatched.
2802 */
2803 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2804 final int foundSerial = getSerialNumber(file);
2805 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2806
2807 if (foundSerial == -1) {
2808 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2809 try {
2810 setSerialNumber(file, serialNumber);
2811 } catch (IOException e) {
2812 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2813 }
2814
2815 } else if (foundSerial != serialNumber) {
2816 throw new IOException("Found serial number " + foundSerial
2817 + " doesn't match expected " + serialNumber);
2818 }
2819 }
2820
2821 /**
2822 * Set serial number stored in user directory inode.
2823 *
2824 * @throws IOException if serial number was already set
2825 */
2826 private static void setSerialNumber(File file, int serialNumber)
2827 throws IOException {
2828 try {
2829 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2830 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2831 } catch (ErrnoException e) {
2832 throw e.rethrowAsIOException();
2833 }
2834 }
2835
2836 /**
2837 * Return serial number stored in user directory inode.
2838 *
2839 * @return parsed serial number, or -1 if not set
2840 */
2841 private static int getSerialNumber(File file) throws IOException {
2842 try {
2843 final byte[] buf = new byte[256];
2844 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2845 final String serial = new String(buf, 0, len);
2846 try {
2847 return Integer.parseInt(serial);
2848 } catch (NumberFormatException e) {
2849 throw new IOException("Bad serial number: " + serial);
2850 }
2851 } catch (ErrnoException e) {
2852 if (e.errno == OsConstants.ENODATA) {
2853 return -1;
2854 } else {
2855 throw e.rethrowAsIOException();
2856 }
2857 }
2858 }
2859
Amith Yamasani920ace02012-09-20 22:15:37 -07002860 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002861 public void setSeedAccountData(int userId, String accountName, String accountType,
2862 PersistableBundle accountOptions, boolean persist) {
2863 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2864 synchronized (mPackagesLock) {
2865 final UserData userData;
2866 synchronized (mUsersLock) {
2867 userData = getUserDataLU(userId);
2868 if (userData == null) {
2869 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2870 return;
2871 }
2872 userData.seedAccountName = accountName;
2873 userData.seedAccountType = accountType;
2874 userData.seedAccountOptions = accountOptions;
2875 userData.persistSeedData = persist;
2876 }
2877 if (persist) {
2878 writeUserLP(userData);
2879 }
2880 }
2881 }
2882
2883 @Override
2884 public String getSeedAccountName() throws RemoteException {
2885 checkManageUsersPermission("Cannot get seed account information");
2886 synchronized (mUsersLock) {
2887 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2888 return userData.seedAccountName;
2889 }
2890 }
2891
2892 @Override
2893 public String getSeedAccountType() throws RemoteException {
2894 checkManageUsersPermission("Cannot get seed account information");
2895 synchronized (mUsersLock) {
2896 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2897 return userData.seedAccountType;
2898 }
2899 }
2900
2901 @Override
2902 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2903 checkManageUsersPermission("Cannot get seed account information");
2904 synchronized (mUsersLock) {
2905 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2906 return userData.seedAccountOptions;
2907 }
2908 }
2909
2910 @Override
2911 public void clearSeedAccountData() throws RemoteException {
2912 checkManageUsersPermission("Cannot clear seed account information");
2913 synchronized (mPackagesLock) {
2914 UserData userData;
2915 synchronized (mUsersLock) {
2916 userData = getUserDataLU(UserHandle.getCallingUserId());
2917 if (userData == null) return;
2918 userData.clearSeedAccountData();
2919 }
2920 writeUserLP(userData);
2921 }
2922 }
2923
2924 @Override
2925 public boolean someUserHasSeedAccount(String accountName, String accountType)
2926 throws RemoteException {
2927 checkManageUsersPermission("Cannot check seed account information");
2928 synchronized (mUsersLock) {
2929 final int userSize = mUsers.size();
2930 for (int i = 0; i < userSize; i++) {
2931 final UserData data = mUsers.valueAt(i);
2932 if (data.info.isInitialized()) continue;
2933 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2934 continue;
2935 }
2936 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2937 continue;
2938 }
2939 return true;
2940 }
2941 }
2942 return false;
2943 }
2944
2945 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002946 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2947 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2948 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2949 }
2950
2951 int onShellCommand(Shell shell, String cmd) {
2952 if (cmd == null) {
2953 return shell.handleDefaultCommands(cmd);
2954 }
2955
2956 final PrintWriter pw = shell.getOutPrintWriter();
2957 try {
2958 switch(cmd) {
2959 case "list":
2960 return runList(pw);
2961 }
2962 } catch (RemoteException e) {
2963 pw.println("Remote exception: " + e);
2964 }
2965 return -1;
2966 }
2967
2968 private int runList(PrintWriter pw) throws RemoteException {
2969 final IActivityManager am = ActivityManagerNative.getDefault();
2970 final List<UserInfo> users = getUsers(false);
2971 if (users == null) {
2972 pw.println("Error: couldn't get users");
2973 return 1;
2974 } else {
2975 pw.println("Users:");
2976 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002977 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002978 pw.println("\t" + users.get(i).toString() + running);
2979 }
2980 return 0;
2981 }
2982 }
2983
2984 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002985 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2986 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2987 != PackageManager.PERMISSION_GRANTED) {
2988 pw.println("Permission Denial: can't dump UserManager from from pid="
2989 + Binder.getCallingPid()
2990 + ", uid=" + Binder.getCallingUid()
2991 + " without permission "
2992 + android.Manifest.permission.DUMP);
2993 return;
2994 }
2995
2996 long now = System.currentTimeMillis();
2997 StringBuilder sb = new StringBuilder();
2998 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002999 synchronized (mUsersLock) {
3000 pw.println("Users:");
3001 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003002 UserData userData = mUsers.valueAt(i);
3003 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003004 continue;
3005 }
Amith Yamasani12747872015-12-07 14:19:49 -08003006 UserInfo userInfo = userData.info;
3007 final int userId = userInfo.id;
3008 pw.print(" "); pw.print(userInfo);
3009 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003010 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003011 pw.print(" <removing> ");
3012 }
Amith Yamasani12747872015-12-07 14:19:49 -08003013 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003014 pw.print(" <partial>");
3015 }
3016 pw.println();
3017 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003018 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003019 pw.println("<unknown>");
3020 } else {
3021 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003022 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003023 sb.append(" ago");
3024 pw.println(sb);
3025 }
3026 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003027 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003028 pw.println("<unknown>");
3029 } else {
3030 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003031 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003032 sb.append(" ago");
3033 pw.println(sb);
3034 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003035 pw.print(" Last logged in fingerprint: ");
3036 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003037 pw.print(" Has profile owner: ");
3038 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003039 pw.println(" Restrictions:");
3040 synchronized (mRestrictionsLock) {
3041 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003042 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003043 pw.println(" Device policy local restrictions:");
3044 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003045 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003046 pw.println(" Effective restrictions:");
3047 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003048 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003049 }
Amith Yamasani12747872015-12-07 14:19:49 -08003050
3051 if (userData.account != null) {
3052 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003053 pw.println();
3054 }
Amith Yamasani12747872015-12-07 14:19:49 -08003055
3056 if (userData.seedAccountName != null) {
3057 pw.print(" Seed account name: " + userData.seedAccountName);
3058 pw.println();
3059 if (userData.seedAccountType != null) {
3060 pw.print(" account type: " + userData.seedAccountType);
3061 pw.println();
3062 }
3063 if (userData.seedAccountOptions != null) {
3064 pw.print(" account options exist");
3065 pw.println();
3066 }
3067 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003068 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003069 }
Amith Yamasani12747872015-12-07 14:19:49 -08003070 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003071 pw.println(" Device policy global restrictions:");
3072 synchronized (mRestrictionsLock) {
3073 UserRestrictionsUtils
3074 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3075 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003076 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003077 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3078 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003079 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003080 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003081 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003082 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003083 synchronized (mUsersLock) {
3084 pw.println();
3085 pw.println(" Device managed: " + mIsDeviceManaged);
3086 }
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003087 synchronized (mUserStates) {
3088 pw.println(" Started users state: " + mUserStates);
3089 }
Amith Yamasani12747872015-12-07 14:19:49 -08003090 // Dump some capabilities
3091 pw.println();
3092 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3093 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003094 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3095 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003096 }
3097 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003098
3099 final class MainHandler extends Handler {
3100
3101 @Override
3102 public void handleMessage(Message msg) {
3103 switch (msg.what) {
3104 case WRITE_USER_MSG:
3105 removeMessages(WRITE_USER_MSG, msg.obj);
3106 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003107 int userId = ((UserData) msg.obj).info.id;
3108 UserData userData = getUserDataNoChecks(userId);
3109 if (userData != null) {
3110 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003111 }
3112 }
3113 }
3114 }
3115 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003116
3117 /**
3118 * @param userId
3119 * @return whether the user has been initialized yet
3120 */
3121 boolean isInitialized(int userId) {
3122 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3123 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003124
3125 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003126 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003127 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3128 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003129 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003130 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003131 }
3132
3133 @Override
3134 public Bundle getBaseUserRestrictions(int userId) {
3135 synchronized (mRestrictionsLock) {
3136 return mBaseUserRestrictions.get(userId);
3137 }
3138 }
3139
3140 @Override
3141 public void setBaseUserRestrictionsByDpmsForMigration(
3142 int userId, Bundle baseRestrictions) {
3143 synchronized (mRestrictionsLock) {
3144 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003145 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003146 }
3147
Amith Yamasani12747872015-12-07 14:19:49 -08003148 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003149 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003150 if (userData != null) {
3151 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003152 } else {
3153 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3154 }
3155 }
3156 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003157
3158 @Override
3159 public boolean getUserRestriction(int userId, String key) {
3160 return getUserRestrictions(userId).getBoolean(key);
3161 }
3162
3163 @Override
3164 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3165 synchronized (mUserRestrictionsListeners) {
3166 mUserRestrictionsListeners.add(listener);
3167 }
3168 }
3169
3170 @Override
3171 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3172 synchronized (mUserRestrictionsListeners) {
3173 mUserRestrictionsListeners.remove(listener);
3174 }
3175 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003176
3177 @Override
3178 public void setDeviceManaged(boolean isManaged) {
3179 synchronized (mUsersLock) {
3180 mIsDeviceManaged = isManaged;
3181 }
3182 }
3183
3184 @Override
3185 public void setUserManaged(int userId, boolean isManaged) {
3186 synchronized (mUsersLock) {
3187 mIsUserManaged.put(userId, isManaged);
3188 }
3189 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003190
3191 @Override
3192 public void setUserIcon(int userId, Bitmap bitmap) {
3193 long ident = Binder.clearCallingIdentity();
3194 try {
3195 synchronized (mPackagesLock) {
3196 UserData userData = getUserDataNoChecks(userId);
3197 if (userData == null || userData.info.partial) {
3198 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3199 return;
3200 }
3201 writeBitmapLP(userData.info, bitmap);
3202 writeUserLP(userData);
3203 }
3204 sendUserInfoChangedBroadcast(userId);
3205 } finally {
3206 Binder.restoreCallingIdentity(ident);
3207 }
3208 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003209
3210 @Override
3211 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3212 synchronized (mUsersLock) {
3213 mForceEphemeralUsers = forceEphemeralUsers;
3214 }
3215 }
3216
3217 @Override
3218 public void removeAllUsers() {
3219 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3220 // Remove the non-system users straight away.
3221 removeNonSystemUsers();
3222 } else {
3223 // Switch to the system user first and then remove the other users.
3224 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3225 @Override
3226 public void onReceive(Context context, Intent intent) {
3227 int userId =
3228 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3229 if (userId != UserHandle.USER_SYSTEM) {
3230 return;
3231 }
3232 mContext.unregisterReceiver(this);
3233 removeNonSystemUsers();
3234 }
3235 };
3236 IntentFilter userSwitchedFilter = new IntentFilter();
3237 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3238 mContext.registerReceiver(
3239 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3240
3241 // Switch to the system user.
3242 ActivityManager am =
3243 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3244 am.switchUser(UserHandle.USER_SYSTEM);
3245 }
3246 }
phweisse9c44062016-02-10 12:57:38 +01003247
3248 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003249 public void onEphemeralUserStop(int userId) {
3250 synchronized (mUsersLock) {
3251 UserInfo userInfo = getUserInfoLU(userId);
3252 if (userInfo != null && userInfo.isEphemeral()) {
3253 // Do not allow switching back to the ephemeral user again as the user is going
3254 // to be deleted.
3255 userInfo.flags |= UserInfo.FLAG_DISABLED;
3256 if (userInfo.isGuest()) {
3257 // Indicate that the guest will be deleted after it stops.
3258 userInfo.guestToRemove = true;
3259 }
3260 }
3261 }
3262 }
3263
3264 @Override
phweisse9c44062016-02-10 12:57:38 +01003265 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3266 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3267 // Keep this in sync with UserManager.createUser
3268 if (user != null && !user.isAdmin()) {
3269 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3270 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3271 }
3272 return user;
3273 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003274
3275 @Override
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003276 public boolean isUserRunning(int userId) {
3277 synchronized (mUserStates) {
3278 return mUserStates.get(userId, -1) >= 0;
3279 }
3280 }
3281
3282 @Override
3283 public void setUserState(int userId, int userState) {
3284 synchronized (mUserStates) {
3285 mUserStates.put(userId, userState);
3286 }
3287 }
3288
3289 @Override
3290 public void removeUserState(int userId) {
3291 synchronized (mUserStates) {
3292 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003293 }
3294 }
3295
3296 @Override
3297 public boolean isUserUnlockingOrUnlocked(int userId) {
Amith Yamasaniea1b9d72016-05-27 15:57:38 +00003298 synchronized (mUserStates) {
3299 int state = mUserStates.get(userId, -1);
3300 return (state == UserState.STATE_RUNNING_UNLOCKING)
3301 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003302 }
3303 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003304 }
3305
3306 /* Remove all the users except of the system one. */
3307 private void removeNonSystemUsers() {
3308 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3309 synchronized (mUsersLock) {
3310 final int userSize = mUsers.size();
3311 for (int i = 0; i < userSize; i++) {
3312 UserInfo ui = mUsers.valueAt(i).info;
3313 if (ui.id != UserHandle.USER_SYSTEM) {
3314 usersToRemove.add(ui);
3315 }
3316 }
3317 }
3318 for (UserInfo ui: usersToRemove) {
3319 removeUser(ui.id);
3320 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003321 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003322
3323 private class Shell extends ShellCommand {
3324 @Override
3325 public int onCommand(String cmd) {
3326 return onShellCommand(this, cmd);
3327 }
3328
3329 @Override
3330 public void onHelp() {
3331 final PrintWriter pw = getOutPrintWriter();
3332 pw.println("User manager (user) commands:");
3333 pw.println(" help");
3334 pw.println(" Print this help text.");
3335 pw.println("");
3336 pw.println(" list");
3337 pw.println(" Prints all users on the system.");
3338 }
3339 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003340
3341 private static void debug(String message) {
3342 Log.d(LOG_TAG, message +
3343 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3344 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003345}