blob: 5263c3707929067f76f49c1ce7c01dc0305c45e0 [file] [log] [blame]
Tony Mak8673b282016-03-21 21:10:59 +00001
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002/*
3 * Copyright (C) 2011 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.server.pm;
19
Xiaohui Chenb3b92582015-12-07 11:22:13 -080020import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070021import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070022import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060023import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070024import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070025import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070026import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070028import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070030import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070031import android.content.Context;
32import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010033import android.content.IntentFilter;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070034import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070035import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080036import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010038import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070039import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060041import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080042import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080043import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.os.Environment;
45import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080046import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080047import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070048import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080049import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010050import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070051import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080052import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070053import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070054import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070055import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010056import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040057import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070058import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070059import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070060import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070061import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080062import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010063import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070064import android.os.storage.VolumeInfo;
65import android.system.ErrnoException;
66import android.system.Os;
67import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070068import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070069import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070070import android.util.Slog;
71import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080072import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070073import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import android.util.Xml;
75
Makoto Onuki068c54a2015-10-13 14:34:03 -070076import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070077import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040078import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080079import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080080import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070081import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070082import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000083import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070084import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070085
86import libcore.io.IoUtils;
87import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080088
89import org.xmlpull.v1.XmlPullParser;
90import org.xmlpull.v1.XmlPullParserException;
91import org.xmlpull.v1.XmlSerializer;
92
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093import java.io.BufferedOutputStream;
94import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070095import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070097import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098import java.io.FileOutputStream;
99import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700100import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100101import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700102import java.util.ArrayList;
103import java.util.List;
104
Makoto Onuki068c54a2015-10-13 14:34:03 -0700105/**
106 * Service for {@link UserManager}.
107 *
108 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700109 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800110 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700111 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
112 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
113 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700114 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700115public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700116 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800117 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800118 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700119
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800121 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700123 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700125 private static final String ATTR_CREATION_TIME = "created";
126 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600127 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700128 private static final String ATTR_SERIAL_NO = "serialNumber";
129 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700130 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700131 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700132 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100133 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700134 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800135 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
136 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530137 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800140 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800141 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800142 private static final String TAG_ENTRY = "entry";
143 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800144 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800145 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700146 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800147 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700148
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700149 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
150 private static final String ATTR_TYPE_STRING = "s";
151 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700152 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700153 private static final String ATTR_TYPE_BUNDLE = "B";
154 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700155
Amith Yamasani0b285492011-04-14 17:35:23 -0700156 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700158 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100159 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700160
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800161 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700162 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800163
Amith Yamasani634cf312012-10-04 17:34:21 -0700164 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700165 // We need to keep process uid within Integer.MAX_VALUE.
166 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700167
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700168 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700169
Amith Yamasani920ace02012-09-20 22:15:37 -0700170 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
171
Nicolas Prevotb8186812015-08-06 15:00:03 +0100172 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700173 // without first making sure that the rest of the framework is prepared for it.
174 private static final int MAX_MANAGED_PROFILES = 1;
175
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800176 static final int WRITE_USER_MSG = 1;
177 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530178
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700179 private static final String XATTR_SERIAL = "user.serial";
180
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800181 // Tron counters
182 private static final String TRON_GUEST_CREATED = "users_guest_created";
183 private static final String TRON_USER_CREATED = "users_user_created";
184
Dianne Hackborn4428e172012-08-24 17:43:05 -0700185 private final Context mContext;
186 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700187 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700188 // Short-term lock for internal state, when interaction/sync with PM is not required
189 private final Object mUsersLock = new Object();
190 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800192 private final Handler mHandler;
193
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700194 private final File mUsersDir;
195 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800197 private static final IBinder mUserRestriconToken = new Binder();
198
Makoto Onuki068c54a2015-10-13 14:34:03 -0700199 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800200 * User-related information that is used for persisting to flash. Only UserInfo is
201 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800202 */
Amith Yamasani12747872015-12-07 14:19:49 -0800203 private static class UserData {
204 // Basic user information and properties
205 UserInfo info;
206 // Account name used when there is a strong association between a user and an account
207 String account;
208 // Account information for seeding into a newly created user. This could also be
209 // used for login validation for an existing user, for updating their credentials.
210 // In the latter case, data may not need to be persisted as it is only valid for the
211 // current login session.
212 String seedAccountName;
213 String seedAccountType;
214 PersistableBundle seedAccountOptions;
215 // Whether to perist the seed account information to be available after a boot
216 boolean persistSeedData;
217
218 void clearSeedAccountData() {
219 seedAccountName = null;
220 seedAccountType = null;
221 seedAccountOptions = null;
222 persistSeedData = false;
223 }
224 }
225
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800226 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800227 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800228
229 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700230 * User restrictions set via UserManager. This doesn't include restrictions set by
231 * device owner / profile owners.
232 *
233 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
234 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
235 * maybe shared between {@link #mBaseUserRestrictions} and
236 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
237 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700238 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700239 */
240 @GuardedBy("mRestrictionsLock")
241 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
242
243 /**
244 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
245 * with device / profile owner restrictions. We'll initialize it lazily; use
246 * {@link #getEffectiveUserRestrictions} to access it.
247 *
248 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
249 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
250 * maybe shared between {@link #mBaseUserRestrictions} and
251 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
252 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700253 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700254 */
255 @GuardedBy("mRestrictionsLock")
256 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
257
Makoto Onuki4f160732015-10-27 17:15:38 -0700258 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800259 * User restrictions that have already been applied in
260 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
261 * that have changed since the last
262 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700263 */
264 @GuardedBy("mRestrictionsLock")
265 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
266
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800267 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800268 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
269 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800270 */
271 @GuardedBy("mRestrictionsLock")
272 private Bundle mDevicePolicyGlobalUserRestrictions;
273
274 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800275 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
276 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800277 */
278 @GuardedBy("mRestrictionsLock")
279 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
280
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800281 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530282 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800283
284 /**
285 * Set of user IDs being actively removed. Removed IDs linger in this set
286 * for several seconds to work around a VFS caching issue.
287 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700288 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800289 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700290
Fyodor Kupolov82402752015-10-28 14:54:51 -0700291 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700292 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800293 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700294 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700295 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700296
Jason Monk62062992014-05-06 09:55:28 -0400297 private IAppOpsService mAppOpsService;
298
Makoto Onuki068c54a2015-10-13 14:34:03 -0700299 private final LocalService mLocalService;
300
Makoto Onukie7927da2015-11-25 10:05:17 -0800301 @GuardedBy("mUsersLock")
302 private boolean mIsDeviceManaged;
303
304 @GuardedBy("mUsersLock")
305 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
306
Makoto Onukid45a4a22015-11-02 17:17:38 -0800307 @GuardedBy("mUserRestrictionsListeners")
308 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
309 new ArrayList<>();
310
Clara Bayarria1771112015-12-18 16:29:18 +0000311 private final LockPatternUtils mLockPatternUtils;
312
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100313 /**
314 * Whether all users should be created ephemeral.
315 */
316 @GuardedBy("mUsersLock")
317 private boolean mForceEphemeralUsers;
318
Amith Yamasani258848d2012-08-10 17:06:33 -0700319 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700320
Dianne Hackborn4428e172012-08-24 17:43:05 -0700321 public static UserManagerService getInstance() {
322 synchronized (UserManagerService.class) {
323 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700324 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700325 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700326
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800327 @VisibleForTesting
328 UserManagerService(File dataDir) {
329 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700330 }
331
Dianne Hackborn4428e172012-08-24 17:43:05 -0700332 /**
333 * Called by package manager to create the service. This is closely
334 * associated with the package manager, and the given lock is the
335 * package manager's own lock.
336 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800337 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
338 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700339 }
340
Dianne Hackborn4428e172012-08-24 17:43:05 -0700341 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800342 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700343 mContext = context;
344 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700345 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800346 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800347 synchronized (mPackagesLock) {
348 mUsersDir = new File(dataDir, USER_INFO_DIR);
349 mUsersDir.mkdirs();
350 // Make zeroth user directory, for services to migrate their files to that location
351 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
352 userZeroDir.mkdirs();
353 FileUtils.setPermissions(mUsersDir.toString(),
354 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
355 -1, -1);
356 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
357 initDefaultGuestRestrictions();
358 readUserListLP();
359 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700360 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700361 mLocalService = new LocalService();
362 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000363 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700364 }
365
366 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100367 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800368 ArrayList<UserInfo> partials = new ArrayList<>();
369 synchronized (mUsersLock) {
370 final int userSize = mUsers.size();
371 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800372 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100373 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800374 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700375 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700376 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700377 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800378 final int partialsSize = partials.size();
379 for (int i = 0; i < partialsSize; i++) {
380 UserInfo ui = partials.get(i);
381 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
382 + " (name=" + ui.name + ")");
383 removeUserState(ui.id);
384 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800385
Jason Monk62062992014-05-06 09:55:28 -0400386 mAppOpsService = IAppOpsService.Stub.asInterface(
387 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800388
389 synchronized (mRestrictionsLock) {
390 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400391 }
Samuel Tand9453b82016-03-14 15:57:02 -0700392
393 UserInfo currentGuestUser = findCurrentGuestUser();
394 if (currentGuestUser != null && !hasUserRestriction(
395 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
396 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
397 // to it, in case this guest was created in a previous version where this
398 // user restriction was not a default guest restriction.
399 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
400 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700401 }
402
403 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800404 public String getUserAccount(int userId) {
405 checkManageUserAndAcrossUsersFullPermission("get user account");
406 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800407 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800408 }
409 }
410
411 @Override
412 public void setUserAccount(int userId, String accountName) {
413 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800414 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800415 synchronized (mPackagesLock) {
416 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800417 final UserData userData = mUsers.get(userId);
418 if (userData == null) {
419 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
420 return;
421 }
422 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800423 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800424 userData.account = accountName;
425 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800426 }
427 }
428
429 if (userToUpdate != null) {
430 writeUserLP(userToUpdate);
431 }
432 }
433 }
434
435 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700436 public UserInfo getPrimaryUser() {
437 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700438 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700439 final int userSize = mUsers.size();
440 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800441 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800442 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700443 return ui;
444 }
445 }
446 }
447 return null;
448 }
449
450 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700451 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700452 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700453 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700454 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700455 final int userSize = mUsers.size();
456 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800457 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700458 if (ui.partial) {
459 continue;
460 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800461 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700462 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700463 }
Amith Yamasani13593602012-03-22 16:16:17 -0700464 }
465 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700466 }
Amith Yamasani13593602012-03-22 16:16:17 -0700467 }
468
Amith Yamasani258848d2012-08-10 17:06:33 -0700469 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100470 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800471 if (userId != UserHandle.getCallingUserId()) {
472 checkManageUsersPermission("getting profiles related to user " + userId);
473 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700474 final long ident = Binder.clearCallingIdentity();
475 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700476 synchronized (mUsersLock) {
477 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100478 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700479 } finally {
480 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000481 }
482 }
483
Amith Yamasanibe465322014-04-24 13:45:17 -0700484 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700485 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
486 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700487 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700488 if (user == null) {
489 // Probably a dying user
490 return users;
491 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700492 final int userSize = mUsers.size();
493 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800494 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700495 if (!isProfileOf(user, profile)) {
496 continue;
497 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100498 if (enabledOnly && !profile.isEnabled()) {
499 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700500 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700501 if (mRemovingUserIds.get(profile.id)) {
502 continue;
503 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700504 users.add(userWithName(profile));
Amith Yamasanibe465322014-04-24 13:45:17 -0700505 }
506 return users;
507 }
508
Jessica Hummelbe81c802014-04-22 15:49:22 +0100509 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700510 public int getCredentialOwnerProfile(int userHandle) {
511 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000512 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700513 synchronized (mUsersLock) {
514 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700515 if (profileParent != null) {
516 return profileParent.id;
517 }
518 }
519 }
520
521 return userHandle;
522 }
523
524 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700525 public boolean isSameProfileGroup(int userId, int otherUserId) {
526 if (userId == otherUserId) return true;
527 checkManageUsersPermission("check if in the same profile group");
528 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700529 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700530 }
531 }
532
Fyodor Kupolov82402752015-10-28 14:54:51 -0700533 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
534 synchronized (mUsersLock) {
535 UserInfo userInfo = getUserInfoLU(userId);
536 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
537 return false;
538 }
539 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
540 if (otherUserInfo == null
541 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
542 return false;
543 }
544 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700545 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700546 }
547
548 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100549 public UserInfo getProfileParent(int userHandle) {
550 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700551 synchronized (mUsersLock) {
552 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700553 }
554 }
555
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 private UserInfo getProfileParentLU(int userHandle) {
557 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700558 if (profile == null) {
559 return null;
560 }
561 int parentUserId = profile.profileGroupId;
562 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
563 return null;
564 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700565 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100566 }
567 }
568
Fyodor Kupolov82402752015-10-28 14:54:51 -0700569 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100570 return user.id == profile.id ||
571 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
572 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000573 }
574
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000575 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000576 UserHandle parentHandle, boolean inQuietMode) {
577 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
578 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
579 intent.putExtra(Intent.EXTRA_USER, profileHandle);
580 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000581 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000582 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000583 }
584
585 @Override
586 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
587 checkManageUsersPermission("silence profile");
588 boolean changed = false;
589 UserInfo profile, parent;
590 synchronized (mPackagesLock) {
591 synchronized (mUsersLock) {
592 profile = getUserInfoLU(userHandle);
593 parent = getProfileParentLU(userHandle);
594
595 }
596 if (profile == null || !profile.isManagedProfile()) {
597 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
598 }
599 if (profile.isQuietModeEnabled() != enableQuietMode) {
600 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800601 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000602 changed = true;
603 }
604 }
605 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000606 long identity = Binder.clearCallingIdentity();
607 try {
608 if (enableQuietMode) {
609 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
610 } else {
611 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
612 }
613 } catch (RemoteException e) {
614 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
615 } finally {
616 Binder.restoreCallingIdentity(identity);
617 }
618
619 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
620 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000621 }
622 }
623
624 @Override
625 public boolean isQuietModeEnabled(int userHandle) {
626 synchronized (mPackagesLock) {
627 UserInfo info;
628 synchronized (mUsersLock) {
629 info = getUserInfoLU(userHandle);
630 }
631 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000632 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000633 }
634 return info.isQuietModeEnabled();
635 }
636 }
637
Kenny Guya52dc3e2014-02-11 15:33:14 +0000638 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100639 public void setUserEnabled(int userId) {
640 checkManageUsersPermission("enable user");
641 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700642 UserInfo info;
643 synchronized (mUsersLock) {
644 info = getUserInfoLU(userId);
645 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100646 if (info != null && !info.isEnabled()) {
647 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800648 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100649 }
650 }
651 }
652
653 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700654 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000655 checkManageUsersPermission("query user");
656 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700657 return userWithName(getUserInfoLU(userId));
658 }
659 }
660
661 /**
662 * Returns a UserInfo object with the name filled in, for Owner, or the original
663 * if the name is already set.
664 */
665 private UserInfo userWithName(UserInfo orig) {
666 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
667 UserInfo withName = new UserInfo(orig);
668 withName.name = getOwnerName();
669 return withName;
670 } else {
671 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000672 }
673 }
674
675 @Override
676 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000677 int callingUserId = UserHandle.getCallingUserId();
678 if (callingUserId != userId && !hasManageUsersPermission()) {
679 synchronized (mPackagesLock) {
680 if (!isSameProfileGroupLP(callingUserId, userId)) {
681 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000682 "You need MANAGE_USERS permission to: check if specified user a " +
683 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000684 }
685 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000686 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700687 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000688 UserInfo userInfo = getUserInfoLU(userId);
689 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700690 }
691 }
692
Amith Yamasani71e6c692013-03-24 17:39:28 -0700693 @Override
694 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700695 synchronized (mUsersLock) {
696 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700697 }
698 }
699
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700700 @Override
701 public boolean canHaveRestrictedProfile(int userId) {
702 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700703 synchronized (mUsersLock) {
704 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700705 if (userInfo == null || !userInfo.canHaveProfile()) {
706 return false;
707 }
708 if (!userInfo.isAdmin()) {
709 return false;
710 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800711 // restricted profile can be created if there is no DO set and the admin user has no PO;
712 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700713 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700714 }
715
Amith Yamasani195263742012-08-21 15:40:12 -0700716 /*
717 * Should be locked on mUsers before calling this.
718 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700719 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800720 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700721 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800722 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700723 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
724 return null;
725 }
Amith Yamasani12747872015-12-07 14:19:49 -0800726 return userData != null ? userData.info : null;
727 }
728
729 private UserData getUserDataLU(int userId) {
730 final UserData userData = mUsers.get(userId);
731 // If it is partial and not in the process of being removed, return as unknown user.
732 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
733 return null;
734 }
735 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700736 }
737
Fyodor Kupolov82402752015-10-28 14:54:51 -0700738 /**
739 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
740 * <p>No permissions checking or any addition checks are made</p>
741 */
742 private UserInfo getUserInfoNoChecks(int userId) {
743 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800744 final UserData userData = mUsers.get(userId);
745 return userData != null ? userData.info : null;
746 }
747 }
748
749 /**
750 * Obtains {@link #mUsersLock} and return UserData from mUsers.
751 * <p>No permissions checking or any addition checks are made</p>
752 */
753 private UserData getUserDataNoChecks(int userId) {
754 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700755 return mUsers.get(userId);
756 }
757 }
758
Amith Yamasani236b2b52015-08-18 14:32:14 -0700759 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700760 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700761 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700762 }
763
Amith Yamasani258848d2012-08-10 17:06:33 -0700764 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700765 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700766 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700767 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700768 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800769 UserData userData = getUserDataNoChecks(userId);
770 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700771 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
772 return;
773 }
Amith Yamasani12747872015-12-07 14:19:49 -0800774 if (name != null && !name.equals(userData.info.name)) {
775 userData.info.name = name;
776 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700777 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700778 }
779 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700780 if (changed) {
781 sendUserInfoChangedBroadcast(userId);
782 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700783 }
784
Amith Yamasani258848d2012-08-10 17:06:33 -0700785 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700786 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700787 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100788 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
789 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
790 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700791 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100792 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700793 }
794
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100795
796
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700797 private void sendUserInfoChangedBroadcast(int userId) {
798 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
799 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
800 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700801 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700802 }
803
Amith Yamasani258848d2012-08-10 17:06:33 -0700804 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100805 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100806 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700807 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100808 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
809 if (targetUserInfo == null || targetUserInfo.partial) {
810 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700811 return null;
812 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100813
814 final int callingUserId = UserHandle.getCallingUserId();
815 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
816 final int targetGroupId = targetUserInfo.profileGroupId;
817 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
818 && callingGroupId == targetGroupId);
819 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100820 checkManageUsersPermission("get the icon of a user who is not related");
821 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100822
823 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700824 return null;
825 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100826 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700827 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100828
829 try {
830 return ParcelFileDescriptor.open(
831 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
832 } catch (FileNotFoundException e) {
833 Log.e(LOG_TAG, "Couldn't find icon file", e);
834 }
835 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700836 }
837
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700838 public void makeInitialized(int userId) {
839 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800840 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800841 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800842 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800843 userData = mUsers.get(userId);
844 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700845 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800846 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700847 }
Amith Yamasani12747872015-12-07 14:19:49 -0800848 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
849 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800850 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700851 }
852 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800853 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800854 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800855 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700856 }
857
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700858 /**
859 * If default guest restrictions haven't been initialized yet, add the basic
860 * restrictions.
861 */
862 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800863 synchronized (mGuestRestrictions) {
864 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700865 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800866 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800867 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
868 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
869 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700870 }
871 }
872
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800873 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530874 public Bundle getDefaultGuestRestrictions() {
875 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800876 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530877 return new Bundle(mGuestRestrictions);
878 }
879 }
880
881 @Override
882 public void setDefaultGuestRestrictions(Bundle restrictions) {
883 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800884 synchronized (mGuestRestrictions) {
885 mGuestRestrictions.clear();
886 mGuestRestrictions.putAll(restrictions);
887 }
888 synchronized (mPackagesLock) {
889 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530890 }
891 }
892
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800893 /**
894 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
895 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800896 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800897 @Nullable Bundle global) {
898 Preconditions.checkNotNull(local);
899 boolean globalChanged = false;
900 boolean localChanged;
901 synchronized (mRestrictionsLock) {
902 if (global != null) {
903 // Update global.
904 globalChanged = !UserRestrictionsUtils.areEqual(
905 mDevicePolicyGlobalUserRestrictions, global);
906 if (globalChanged) {
907 mDevicePolicyGlobalUserRestrictions = global;
908 }
909 }
910 {
911 // Update local.
912 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
913 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
914 if (localChanged) {
915 mDevicePolicyLocalUserRestrictions.put(userId, local);
916 }
917 }
918 }
919 if (DBG) {
920 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
921 + " global=" + global + (globalChanged ? " (changed)" : "")
922 + " local=" + local + (localChanged ? " (changed)" : "")
923 );
924 }
925 // Don't call them within the mRestrictionsLock.
926 synchronized (mPackagesLock) {
927 if (globalChanged) {
928 writeUserListLP();
929 }
930 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800931 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800932 }
933 }
934
935 synchronized (mRestrictionsLock) {
936 if (globalChanged) {
937 applyUserRestrictionsForAllUsersLR();
938 } else if (localChanged) {
939 applyUserRestrictionsLR(userId);
940 }
941 }
942 }
943
Makoto Onuki068c54a2015-10-13 14:34:03 -0700944 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700945 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800946 final Bundle baseRestrictions =
947 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
948 final Bundle global = mDevicePolicyGlobalUserRestrictions;
949 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700950
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800951 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
952 // Common case first.
953 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700954 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800955 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
956 UserRestrictionsUtils.merge(effective, global);
957 UserRestrictionsUtils.merge(effective, local);
958
Makoto Onuki068c54a2015-10-13 14:34:03 -0700959 return effective;
960 }
961
962 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700963 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700964 if (DBG) {
965 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
966 }
967 mCachedEffectiveUserRestrictions.remove(userId);
968 }
969
970 private Bundle getEffectiveUserRestrictions(int userId) {
971 synchronized (mRestrictionsLock) {
972 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
973 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700974 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700975 mCachedEffectiveUserRestrictions.put(userId, restrictions);
976 }
977 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700978 }
979 }
980
Makoto Onuki068c54a2015-10-13 14:34:03 -0700981 /** @return a specific user restriction that's in effect currently. */
982 @Override
983 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800984 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
985 return false;
986 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700987 Bundle restrictions = getEffectiveUserRestrictions(userId);
988 return restrictions != null && restrictions.getBoolean(restrictionKey);
989 }
990
991 /**
992 * @return UserRestrictions that are in effect currently. This always returns a new
993 * {@link Bundle}.
994 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700995 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800996 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800997 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800998 }
999
1000 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001001 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1002 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001003 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1004 return false;
1005 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001006 synchronized (mRestrictionsLock) {
1007 Bundle bundle = mBaseUserRestrictions.get(userId);
1008 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1009 }
1010 }
1011
1012 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001013 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001014 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001015 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1016 return;
1017 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001018 synchronized (mRestrictionsLock) {
1019 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1020 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001021 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1022 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001023 newRestrictions.putBoolean(key, value);
1024
Fyodor Kupolov82402752015-10-28 14:54:51 -07001025 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001026 }
1027 }
1028
Makoto Onuki068c54a2015-10-13 14:34:03 -07001029 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001030 * Optionally updating user restrictions, calculate the effective user restrictions and also
1031 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001032 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001033 * @param newRestrictions User restrictions to set.
1034 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001035 * @param userId target user ID.
1036 */
1037 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001038 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001039 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001040
1041 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1042 mAppliedUserRestrictions.get(userId));
1043
1044 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001045 if (newRestrictions != null) {
1046 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001047 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1048
1049 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001050 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1051 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001052
1053 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1054 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001055 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001056 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001057 }
1058
Fyodor Kupolov82402752015-10-28 14:54:51 -07001059 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001060
Makoto Onuki759a7632015-10-28 16:43:10 -07001061 mCachedEffectiveUserRestrictions.put(userId, effective);
1062
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001063 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001064 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001065 debug("Applying user restrictions: userId=" + userId
1066 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001067 }
1068
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001069 if (mAppOpsService != null) { // We skip it until system-ready.
1070 final long token = Binder.clearCallingIdentity();
1071 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001072 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001073 } catch (RemoteException e) {
1074 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1075 } finally {
1076 Binder.restoreCallingIdentity(token);
1077 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001078 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001079
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001080 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001081
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001082 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001083 }
1084
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001085 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001086 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001087 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1088 // actually, but we still need some kind of synchronization otherwise we might end up
1089 // calling listeners out-of-order, thus "LR".
1090
1091 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1092 return;
1093 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001094
1095 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1096 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1097
1098 mHandler.post(new Runnable() {
1099 @Override
1100 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001101 UserRestrictionsUtils.applyUserRestrictions(
1102 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001103
Makoto Onukid45a4a22015-11-02 17:17:38 -08001104 final UserRestrictionsListener[] listeners;
1105 synchronized (mUserRestrictionsListeners) {
1106 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1107 mUserRestrictionsListeners.toArray(listeners);
1108 }
1109 for (int i = 0; i < listeners.length; i++) {
1110 listeners[i].onUserRestrictionsChanged(userId,
1111 newRestrictionsFinal, prevRestrictionsFinal);
1112 }
1113 }
1114 });
1115 }
1116
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001117 // Package private for the inner class.
1118 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001119 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001120 }
1121
1122 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001123 // Package private for the inner class.
1124 void applyUserRestrictionsForAllUsersLR() {
1125 if (DBG) {
1126 debug("applyUserRestrictionsForAllUsersLR");
1127 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001128 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001129 mCachedEffectiveUserRestrictions.clear();
1130
Makoto Onuki068c54a2015-10-13 14:34:03 -07001131 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1132 // it on a handler.
1133 final Runnable r = new Runnable() {
1134 @Override
1135 public void run() {
1136 // Then get the list of running users.
1137 final int[] runningUsers;
1138 try {
1139 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1140 } catch (RemoteException e) {
1141 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1142 return;
1143 }
1144 // Then re-calculate the effective restrictions and apply, only for running users.
1145 // It's okay if a new user has started after the getRunningUserIds() call,
1146 // because we'll do the same thing (re-calculate the restrictions and apply)
1147 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001148 synchronized (mRestrictionsLock) {
1149 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001150 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001151 }
1152 }
1153 }
1154 };
1155 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001156 }
1157
Amith Yamasani258848d2012-08-10 17:06:33 -07001158 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001159 * Check if we've hit the limit of how many users can be created.
1160 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001161 private boolean isUserLimitReached() {
1162 int count;
1163 synchronized (mUsersLock) {
1164 count = getAliveUsersExcludingGuestsCountLU();
1165 }
1166 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001167 }
1168
1169 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001170 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001171 checkManageUsersPermission("check if more managed profiles can be added.");
1172 if (ActivityManager.isLowRamDeviceStatic()) {
1173 return false;
1174 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001175 if (!mContext.getPackageManager().hasSystemFeature(
1176 PackageManager.FEATURE_MANAGED_USERS)) {
1177 return false;
1178 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001179 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001180 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1181 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1182 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001183 return false;
1184 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001185 synchronized(mUsersLock) {
1186 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001187 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001188 return false;
1189 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001190 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1191 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001192 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001193 return usersCountAfterRemoving == 1
1194 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001195 }
1196 }
1197
Fyodor Kupolov82402752015-10-28 14:54:51 -07001198 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001199 int aliveUserCount = 0;
1200 final int totalUserCount = mUsers.size();
1201 // Skip over users being removed
1202 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001203 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001204 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001205 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001206 aliveUserCount++;
1207 }
1208 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001209 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001210 }
1211
1212 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001213 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001214 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1215 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1216 * permissions can make certain calls to the UserManager.
1217 *
1218 * @param message used as message if SecurityException is thrown
1219 * @throws SecurityException if the caller does not have enough privilege.
1220 */
1221 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1222 final int uid = Binder.getCallingUid();
1223 if (uid != Process.SYSTEM_UID && uid != 0
1224 && ActivityManager.checkComponentPermission(
1225 Manifest.permission.MANAGE_USERS,
1226 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1227 && ActivityManager.checkComponentPermission(
1228 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1229 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1230 throw new SecurityException(
1231 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1232 + message);
1233 }
1234 }
1235
1236 /**
1237 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001238 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001239 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001240 *
1241 * @param message used as message if SecurityException is thrown
1242 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001243 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001244 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001245 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001246 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001247 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1248 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001249 }
1250
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001251 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001252 * @return whether the calling UID is system UID or root's UID or the calling app has the
1253 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1254 */
1255 private static final boolean hasManageUsersPermission() {
1256 final int callingUid = Binder.getCallingUid();
1257 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1258 || callingUid == Process.ROOT_UID
1259 || ActivityManager.checkComponentPermission(
1260 android.Manifest.permission.MANAGE_USERS,
1261 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1262 }
1263
1264 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001265 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1266 * UserManager.
1267 *
1268 * @param message used as message if SecurityException is thrown
1269 * @throws SecurityException if the caller is not system or root
1270 */
1271 private static void checkSystemOrRoot(String message) {
1272 final int uid = Binder.getCallingUid();
1273 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1274 throw new SecurityException("Only system may: " + message);
1275 }
1276 }
1277
Fyodor Kupolov82402752015-10-28 14:54:51 -07001278 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001279 try {
1280 File dir = new File(mUsersDir, Integer.toString(info.id));
1281 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001282 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001283 if (!dir.exists()) {
1284 dir.mkdir();
1285 FileUtils.setPermissions(
1286 dir.getPath(),
1287 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1288 -1, -1);
1289 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001290 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001291 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001292 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001293 info.iconPath = file.getAbsolutePath();
1294 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001295 try {
1296 os.close();
1297 } catch (IOException ioe) {
1298 // What the ... !
1299 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001300 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001301 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001302 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001303 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001304 }
1305
Amith Yamasani0b285492011-04-14 17:35:23 -07001306 /**
1307 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1308 * cache it elsewhere.
1309 * @return the array of user ids.
1310 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001311 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001312 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001313 return mUserIds;
1314 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001315 }
1316
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001317 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001318 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001319 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001320 return;
1321 }
1322 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001323 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001324 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001325 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001326 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001327 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001328 int type;
1329 while ((type = parser.next()) != XmlPullParser.START_TAG
1330 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001331 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001332 }
1333
1334 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001335 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001336 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001337 return;
1338 }
1339
Amith Yamasani2a003292012-08-14 18:25:45 -07001340 mNextSerialNumber = -1;
1341 if (parser.getName().equals(TAG_USERS)) {
1342 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1343 if (lastSerialNumber != null) {
1344 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1345 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001346 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1347 if (versionNumber != null) {
1348 mUserVersion = Integer.parseInt(versionNumber);
1349 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001350 }
1351
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001352 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1353
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001354 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301355 if (type == XmlPullParser.START_TAG) {
1356 final String name = parser.getName();
1357 if (name.equals(TAG_USER)) {
1358 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001359
Amith Yamasani12747872015-12-07 14:19:49 -08001360 UserData userData = readUserLP(Integer.parseInt(id));
1361
1362 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001363 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001364 mUsers.put(userData.info.id, userData);
1365 if (mNextSerialNumber < 0
1366 || mNextSerialNumber <= userData.info.id) {
1367 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001368 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301369 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001370 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301371 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001372 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1373 && type != XmlPullParser.END_TAG) {
1374 if (type == XmlPullParser.START_TAG) {
1375 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001376 synchronized (mGuestRestrictions) {
1377 UserRestrictionsUtils
1378 .readRestrictions(parser, mGuestRestrictions);
1379 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001380 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1381 ) {
1382 UserRestrictionsUtils.readRestrictions(parser,
1383 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001384 }
1385 break;
1386 }
1387 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001388 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001389 }
1390 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001391 synchronized (mRestrictionsLock) {
1392 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1393 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001394 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001395 upgradeIfNecessaryLP();
1396 } catch (IOException | XmlPullParserException e) {
1397 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001398 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001399 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001400 }
1401 }
1402
Amith Yamasani6f34b412012-10-22 18:19:27 -07001403 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001404 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001405 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001406 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001407 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001408 int userVersion = mUserVersion;
1409 if (userVersion < 1) {
1410 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001411 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1412 if ("Primary".equals(userData.info.name)) {
1413 userData.info.name =
1414 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1415 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001416 }
1417 userVersion = 1;
1418 }
1419
Amith Yamasanibc9625052012-11-15 14:39:18 -08001420 if (userVersion < 2) {
1421 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001422 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1423 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1424 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1425 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001426 }
1427 userVersion = 2;
1428 }
1429
Amith Yamasani350962c2013-08-06 11:18:53 -07001430
Amith Yamasani5e486f52013-08-07 11:06:44 -07001431 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001432 userVersion = 4;
1433 }
1434
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001435 if (userVersion < 5) {
1436 initDefaultGuestRestrictions();
1437 userVersion = 5;
1438 }
1439
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001440 if (userVersion < 6) {
1441 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001442 synchronized (mUsersLock) {
1443 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001444 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001445 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001446 if (!splitSystemUser && userData.info.isRestricted()
1447 && (userData.info.restrictedProfileParentId
1448 == UserInfo.NO_PROFILE_GROUP_ID)) {
1449 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1450 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001451 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001452 }
1453 }
1454 userVersion = 6;
1455 }
1456
Amith Yamasani6f34b412012-10-22 18:19:27 -07001457 if (userVersion < USER_VERSION) {
1458 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1459 + USER_VERSION);
1460 } else {
1461 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462
1463 if (originalVersion < mUserVersion) {
1464 writeUserListLP();
1465 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001466 }
1467 }
1468
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001469 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001470 int flags = UserInfo.FLAG_INITIALIZED;
1471 // In split system user mode, the admin and primary flags are assigned to the first human
1472 // user.
1473 if (!UserManager.isSplitSystemUser()) {
1474 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1475 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001476 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001477 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001478 UserData userData = new UserData();
1479 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001480 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001481 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001482 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001483 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001484 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001485
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001486 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001487 synchronized (mRestrictionsLock) {
1488 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1489 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001490
Fyodor Kupolov82402752015-10-28 14:54:51 -07001491 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001492 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001493
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001494 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001495 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001496 }
1497
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001498 private String getOwnerName() {
1499 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1500 }
1501
Amith Yamasani12747872015-12-07 14:19:49 -08001502 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001503 if (DBG) {
1504 debug("scheduleWriteUser");
1505 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001506 // No need to wrap it within a lock -- worst case, we'll just post the same message
1507 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001508 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1509 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001510 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1511 }
1512 }
1513
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001514 /*
1515 * Writes the user file in this format:
1516 *
1517 * <user flags="20039023" id="0">
1518 * <name>Primary</name>
1519 * </user>
1520 */
Amith Yamasani12747872015-12-07 14:19:49 -08001521 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001522 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001523 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001524 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001525 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001526 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001527 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001528 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001529 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1530
1531 // XmlSerializer serializer = XmlUtils.serializerInstance();
1532 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001533 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001534 serializer.startDocument(null, true);
1535 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1536
Amith Yamasani12747872015-12-07 14:19:49 -08001537 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001538 serializer.startTag(null, TAG_USER);
1539 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001540 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001541 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001542 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1543 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1544 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001545 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1546 userInfo.lastLoggedInFingerprint);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001547 if (userInfo.iconPath != null) {
1548 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1549 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001550 if (userInfo.partial) {
1551 serializer.attribute(null, ATTR_PARTIAL, "true");
1552 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001553 if (userInfo.guestToRemove) {
1554 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1555 }
Kenny Guy2a764942014-04-02 13:29:20 +01001556 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1557 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1558 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001559 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001560 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1561 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1562 Integer.toString(userInfo.restrictedProfileParentId));
1563 }
Amith Yamasani12747872015-12-07 14:19:49 -08001564 // Write seed data
1565 if (userData.persistSeedData) {
1566 if (userData.seedAccountName != null) {
1567 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1568 }
1569 if (userData.seedAccountType != null) {
1570 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1571 }
1572 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001573 if (userInfo.name != null) {
1574 serializer.startTag(null, TAG_NAME);
1575 serializer.text(userInfo.name);
1576 serializer.endTag(null, TAG_NAME);
1577 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001578 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001579 UserRestrictionsUtils.writeRestrictions(serializer,
1580 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1581 UserRestrictionsUtils.writeRestrictions(serializer,
1582 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1583 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001584 }
Amith Yamasani12747872015-12-07 14:19:49 -08001585
1586 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001587 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001588 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001589 serializer.endTag(null, TAG_ACCOUNT);
1590 }
1591
Amith Yamasani12747872015-12-07 14:19:49 -08001592 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1593 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1594 userData.seedAccountOptions.saveToXml(serializer);
1595 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1596 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001597 serializer.endTag(null, TAG_USER);
1598
1599 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001600 userFile.finishWrite(fos);
1601 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001602 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001603 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001604 }
1605 }
1606
1607 /*
1608 * Writes the user list file in this format:
1609 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001610 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001611 * <user id="0"></user>
1612 * <user id="2"></user>
1613 * </users>
1614 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001615 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001616 if (DBG) {
1617 debug("writeUserList");
1618 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001619 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001620 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001621 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001622 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001623 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1624
1625 // XmlSerializer serializer = XmlUtils.serializerInstance();
1626 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001627 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001628 serializer.startDocument(null, true);
1629 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1630
1631 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001632 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001633 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001634
Adam Lesinskieddeb492014-09-08 17:50:03 -07001635 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001636 synchronized (mGuestRestrictions) {
1637 UserRestrictionsUtils
1638 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1639 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301640 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 synchronized (mRestrictionsLock) {
1642 UserRestrictionsUtils.writeRestrictions(serializer,
1643 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1644 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001645 int[] userIdsToWrite;
1646 synchronized (mUsersLock) {
1647 userIdsToWrite = new int[mUsers.size()];
1648 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001649 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001650 userIdsToWrite[i] = user.id;
1651 }
1652 }
1653 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001654 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001655 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001657 }
1658
1659 serializer.endTag(null, TAG_USERS);
1660
1661 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001662 userListFile.finishWrite(fos);
1663 } catch (Exception e) {
1664 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001665 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001666 }
1667 }
1668
Amith Yamasani12747872015-12-07 14:19:49 -08001669 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001670 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001671 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001672 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001673 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001674 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001675 long creationTime = 0L;
1676 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001677 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001678 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001679 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001680 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001681 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001682 boolean persistSeedData = false;
1683 String seedAccountName = null;
1684 String seedAccountType = null;
1685 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 Bundle baseRestrictions = new Bundle();
1687 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001688
1689 FileInputStream fis = null;
1690 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001691 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001692 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001693 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001694 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001695 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001696 int type;
1697 while ((type = parser.next()) != XmlPullParser.START_TAG
1698 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001699 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001700 }
1701
1702 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001703 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001704 return null;
1705 }
1706
1707 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001708 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1709 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001710 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001711 return null;
1712 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001713 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1714 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001715 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001716 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1717 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001718 lastLoggedInFingerprint = parser.getAttributeValue(null,
1719 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001720 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1721 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001722 restrictedProfileParentId = readIntAttribute(parser,
1723 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001724 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1725 if ("true".equals(valueString)) {
1726 partial = true;
1727 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001728 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1729 if ("true".equals(valueString)) {
1730 guestToRemove = true;
1731 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001732
Amith Yamasani12747872015-12-07 14:19:49 -08001733 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1734 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1735 if (seedAccountName != null || seedAccountType != null) {
1736 persistSeedData = true;
1737 }
1738
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001739 int outerDepth = parser.getDepth();
1740 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1741 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1742 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1743 continue;
1744 }
1745 String tag = parser.getName();
1746 if (TAG_NAME.equals(tag)) {
1747 type = parser.next();
1748 if (type == XmlPullParser.TEXT) {
1749 name = parser.getText();
1750 }
1751 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001752 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1753 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1754 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001755 } else if (TAG_ACCOUNT.equals(tag)) {
1756 type = parser.next();
1757 if (type == XmlPullParser.TEXT) {
1758 account = parser.getText();
1759 }
Amith Yamasani12747872015-12-07 14:19:49 -08001760 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1761 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1762 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001763 }
1764 }
1765 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001766
Amith Yamasani12747872015-12-07 14:19:49 -08001767 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001768 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001769 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001770 userInfo.creationTime = creationTime;
1771 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001772 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001773 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001774 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001775 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001776 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001777
1778 // Create the UserData object that's internal to this class
1779 UserData userData = new UserData();
1780 userData.info = userInfo;
1781 userData.account = account;
1782 userData.seedAccountName = seedAccountName;
1783 userData.seedAccountType = seedAccountType;
1784 userData.persistSeedData = persistSeedData;
1785 userData.seedAccountOptions = seedAccountOptions;
1786
Makoto Onuki068c54a2015-10-13 14:34:03 -07001787 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 mBaseUserRestrictions.put(id, baseRestrictions);
1789 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001790 }
Amith Yamasani12747872015-12-07 14:19:49 -08001791 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001792 } catch (IOException ioe) {
1793 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001794 } finally {
1795 if (fis != null) {
1796 try {
1797 fis.close();
1798 } catch (IOException e) {
1799 }
1800 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001801 }
1802 return null;
1803 }
1804
Amith Yamasani920ace02012-09-20 22:15:37 -07001805 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1806 String valueString = parser.getAttributeValue(null, attr);
1807 if (valueString == null) return defaultValue;
1808 try {
1809 return Integer.parseInt(valueString);
1810 } catch (NumberFormatException nfe) {
1811 return defaultValue;
1812 }
1813 }
1814
1815 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1816 String valueString = parser.getAttributeValue(null, attr);
1817 if (valueString == null) return defaultValue;
1818 try {
1819 return Long.parseLong(valueString);
1820 } catch (NumberFormatException nfe) {
1821 return defaultValue;
1822 }
1823 }
1824
Amith Yamasanib82add22013-07-09 11:24:44 -07001825 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001826 * Removes the app restrictions file for a specific package and user id, if it exists.
1827 */
1828 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1829 synchronized (mPackagesLock) {
1830 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001831 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001832 if (resFile.exists()) {
1833 resFile.delete();
1834 }
1835 }
1836 }
1837
Kenny Guya52dc3e2014-02-11 15:33:14 +00001838 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001839 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001840 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001841 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001842 }
1843
Amith Yamasani258848d2012-08-10 17:06:33 -07001844 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001845 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001846 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001847 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001848 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001849
Jessica Hummelbe81c802014-04-22 15:49:22 +01001850 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001851 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001852 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1853 return null;
1854 }
phweisse9c44062016-02-10 12:57:38 +01001855 return createUserInternalUnchecked(name, flags, parentId);
1856 }
1857
1858 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001859 if (ActivityManager.isLowRamDeviceStatic()) {
1860 return null;
1861 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001862 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001863 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001864 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001865 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001866 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001867 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001868 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001869 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001870 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001871 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001872 if (parentId != UserHandle.USER_NULL) {
1873 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001874 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001875 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001876 if (parent == null) return null;
1877 }
1878 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1879 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1880 return null;
1881 }
1882 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1883 // If we're not adding a guest user or a managed profile and the limit has
1884 // been reached, cannot add a user.
1885 return null;
1886 }
1887 // If we're adding a guest and there already exists one, bail.
1888 if (isGuest && findCurrentGuestUser() != null) {
1889 return null;
1890 }
1891 // In legacy mode, restricted profile's parent can only be the owner user
1892 if (isRestricted && !UserManager.isSplitSystemUser()
1893 && (parentId != UserHandle.USER_SYSTEM)) {
1894 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1895 return null;
1896 }
1897 if (isRestricted && UserManager.isSplitSystemUser()) {
1898 if (parent == null) {
1899 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1900 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001901 return null;
1902 }
Amith Yamasani12747872015-12-07 14:19:49 -08001903 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001904 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1905 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001906 return null;
1907 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001908 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001909 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1910 Log.e(LOG_TAG,
1911 "Ephemeral users are supported on split-system-user systems only.");
1912 return null;
1913 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001914 // In split system user mode, we assign the first human user the primary flag.
1915 // And if there is no device owner, we also assign the admin flag to primary user.
1916 if (UserManager.isSplitSystemUser()
1917 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1918 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001919 synchronized (mUsersLock) {
1920 if (!mIsDeviceManaged) {
1921 flags |= UserInfo.FLAG_ADMIN;
1922 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001923 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001924 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001925
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001926 userId = getNextAvailableId();
1927 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001928 boolean ephemeralGuests = Resources.getSystem()
1929 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001930
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001931 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001932 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1933 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1934 || (parent != null && parent.info.isEphemeral())) {
1935 flags |= UserInfo.FLAG_EPHEMERAL;
1936 }
1937
1938 userInfo = new UserInfo(userId, name, null, flags);
1939 userInfo.serialNumber = mNextSerialNumber++;
1940 long now = System.currentTimeMillis();
1941 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1942 userInfo.partial = true;
1943 userData = new UserData();
1944 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001945 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001946 }
1947 writeUserListLP();
1948 if (parent != null) {
1949 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001950 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1951 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001952 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001953 }
Amith Yamasani12747872015-12-07 14:19:49 -08001954 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001955 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001956 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1957 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001958 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001959 }
Amith Yamasani12747872015-12-07 14:19:49 -08001960 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001961 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001962 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001963 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001964 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001965 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07001966 prepareUserStorage(userId, userInfo.serialNumber,
1967 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001968 mPm.createNewUser(userId);
1969 userInfo.partial = false;
1970 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001971 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001972 }
1973 updateUserIds();
1974 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001975 if (isGuest) {
1976 synchronized (mGuestRestrictions) {
1977 restrictions.putAll(mGuestRestrictions);
1978 }
1979 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001980 synchronized (mRestrictionsLock) {
1981 mBaseUserRestrictions.append(userId, restrictions);
1982 }
1983 mPm.newUserCreated(userId);
1984 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1985 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1986 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1987 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001988 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001989 } finally {
1990 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001991 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001992 return userInfo;
1993 }
1994
Amith Yamasani0b285492011-04-14 17:35:23 -07001995 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001996 * @hide
1997 */
Amith Yamasani12747872015-12-07 14:19:49 -08001998 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001999 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2000 checkManageUsersPermission("setupRestrictedProfile");
2001 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2002 if (user == null) {
2003 return null;
2004 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002005 long identity = Binder.clearCallingIdentity();
2006 try {
2007 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2008 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2009 // the putIntForUser() will fail.
2010 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2011 android.provider.Settings.Secure.LOCATION_MODE,
2012 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2013 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2014 } finally {
2015 Binder.restoreCallingIdentity(identity);
2016 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002017 return user;
2018 }
2019
2020 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002021 * Find the current guest user. If the Guest user is partial,
2022 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002023 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002024 private UserInfo findCurrentGuestUser() {
2025 synchronized (mUsersLock) {
2026 final int size = mUsers.size();
2027 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002028 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002029 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2030 return user;
2031 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002032 }
2033 }
2034 return null;
2035 }
2036
2037 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002038 * Mark this guest user for deletion to allow us to create another guest
2039 * and switch to that user before actually removing this guest.
2040 * @param userHandle the userid of the current guest
2041 * @return whether the user could be marked for deletion
2042 */
Amith Yamasani12747872015-12-07 14:19:49 -08002043 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002044 public boolean markGuestForDeletion(int userHandle) {
2045 checkManageUsersPermission("Only the system can remove users");
2046 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2047 UserManager.DISALLOW_REMOVE_USER, false)) {
2048 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2049 return false;
2050 }
2051
2052 long ident = Binder.clearCallingIdentity();
2053 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002054 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002055 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002056 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002057 userData = mUsers.get(userHandle);
2058 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002059 return false;
2060 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002061 }
Amith Yamasani12747872015-12-07 14:19:49 -08002062 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002063 return false;
2064 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002065 // We set this to a guest user that is to be removed. This is a temporary state
2066 // where we are allowed to add new Guest users, even if this one is still not
2067 // removed. This user will still show up in getUserInfo() calls.
2068 // If we don't get around to removing this Guest user, it will be purged on next
2069 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002070 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002071 // Mark it as disabled, so that it isn't returned any more when
2072 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002073 userData.info.flags |= UserInfo.FLAG_DISABLED;
2074 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002075 }
2076 } finally {
2077 Binder.restoreCallingIdentity(ident);
2078 }
2079 return true;
2080 }
2081
2082 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002083 * Removes a user and all data directories created for that user. This method should be called
2084 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002085 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002086 */
Amith Yamasani12747872015-12-07 14:19:49 -08002087 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002088 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002089 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002090 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2091 UserManager.DISALLOW_REMOVE_USER, false)) {
2092 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2093 return false;
2094 }
2095
Kenny Guyee58b4f2014-05-23 15:19:53 +01002096 long ident = Binder.clearCallingIdentity();
2097 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002098 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002099 int currentUser = ActivityManager.getCurrentUser();
2100 if (currentUser == userHandle) {
2101 Log.w(LOG_TAG, "Current user cannot be removed");
2102 return false;
2103 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002104 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002105 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002106 userData = mUsers.get(userHandle);
2107 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002108 return false;
2109 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002110
Fyodor Kupolov82402752015-10-28 14:54:51 -07002111 // We remember deleted user IDs to prevent them from being
2112 // reused during the current boot; they can still be reused
2113 // after a reboot.
2114 mRemovingUserIds.put(userHandle, true);
2115 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002116
Kenny Guyee58b4f2014-05-23 15:19:53 +01002117 try {
2118 mAppOpsService.removeUser(userHandle);
2119 } catch (RemoteException e) {
2120 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2121 }
2122 // Set this to a partially created user, so that the user will be purged
2123 // on next startup, in case the runtime stops now before stopping and
2124 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002125 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002126 // Mark it as disabled, so that it isn't returned any more when
2127 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002128 userData.info.flags |= UserInfo.FLAG_DISABLED;
2129 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002130 }
2131
Amith Yamasani12747872015-12-07 14:19:49 -08002132 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2133 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002134 // Send broadcast to notify system that the user removed was a
2135 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002136 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002137 }
2138
2139 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2140 int res;
2141 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002142 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2143 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002144 @Override
2145 public void userStopped(int userId) {
2146 finishRemoveUser(userId);
2147 }
2148 @Override
2149 public void userStopAborted(int userId) {
2150 }
2151 });
2152 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002153 return false;
2154 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002155 return res == ActivityManager.USER_OP_SUCCESS;
2156 } finally {
2157 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002158 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002159 }
2160
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002161 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002162 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002163 // Let other services shutdown any activity and clean up their state before completely
2164 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002165 long ident = Binder.clearCallingIdentity();
2166 try {
2167 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2168 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002169 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2170 android.Manifest.permission.MANAGE_USERS,
2171
2172 new BroadcastReceiver() {
2173 @Override
2174 public void onReceive(Context context, Intent intent) {
2175 if (DBG) {
2176 Slog.i(LOG_TAG,
2177 "USER_REMOVED broadcast sent, cleaning up user data "
2178 + userHandle);
2179 }
2180 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002181 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002182 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002183 // Clean up any ActivityManager state
2184 LocalServices.getService(ActivityManagerInternal.class)
2185 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002186 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002187 }
2188 }.start();
2189 }
2190 },
2191
2192 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002193 } finally {
2194 Binder.restoreCallingIdentity(ident);
2195 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002196 }
2197
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002198 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002199 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002200 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002201 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002202
2203 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002204 synchronized (mUsersLock) {
2205 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002206 mIsUserManaged.delete(userHandle);
2207 }
2208 synchronized (mRestrictionsLock) {
2209 mBaseUserRestrictions.remove(userHandle);
2210 mAppliedUserRestrictions.remove(userHandle);
2211 mCachedEffectiveUserRestrictions.remove(userHandle);
2212 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002213 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002214 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002215 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002216 userFile.delete();
2217 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002218 synchronized (mPackagesLock) {
2219 writeUserListLP();
2220 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002221 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002222 File userDir = Environment.getUserSystemDirectory(userHandle);
2223 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2224 if (userDir.renameTo(renamedUserDir)) {
2225 removeDirectoryRecursive(renamedUserDir);
2226 } else {
2227 removeDirectoryRecursive(userDir);
2228 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002229 }
2230
Amith Yamasani61f57372012-08-31 12:12:28 -07002231 private void removeDirectoryRecursive(File parent) {
2232 if (parent.isDirectory()) {
2233 String[] files = parent.list();
2234 for (String filename : files) {
2235 File child = new File(parent, filename);
2236 removeDirectoryRecursive(child);
2237 }
2238 }
2239 parent.delete();
2240 }
2241
Kenny Guyf8d3a232014-05-15 16:09:52 +01002242 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002243 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002244 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2245 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002246 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002247 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002248 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002249 }
2250
Amith Yamasani2a003292012-08-14 18:25:45 -07002251 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002252 public Bundle getApplicationRestrictions(String packageName) {
2253 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2254 }
2255
2256 @Override
2257 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002258 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002259 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002260 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002261 }
2262 synchronized (mPackagesLock) {
2263 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002264 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002265 }
2266 }
2267
2268 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002269 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002270 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002271 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002272 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002273 if (restrictions == null || restrictions.isEmpty()) {
2274 cleanAppRestrictionsForPackage(packageName, userId);
2275 } else {
2276 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002277 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002278 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002279 }
Robin Lee66e5d962014-04-09 16:44:21 +01002280
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002281 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2282 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2283 changeIntent.setPackage(packageName);
2284 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2285 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002286 }
2287
2288 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002289 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002290 try {
2291 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002292 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002293 } catch (NameNotFoundException nnfe) {
2294 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002295 } finally {
2296 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002297 }
2298 }
2299
Fyodor Kupolov82402752015-10-28 14:54:51 -07002300 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002301 AtomicFile restrictionsFile =
2302 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2303 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002304 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002305 }
2306
2307 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002308 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002309 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002310 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002311 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002312 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002313 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002314
2315 FileInputStream fis = null;
2316 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002317 fis = restrictionsFile.openRead();
2318 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002319 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002320 XmlUtils.nextElement(parser);
2321 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002322 Slog.e(LOG_TAG, "Unable to read restrictions file "
2323 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002324 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002325 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002326 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2327 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002328 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002329 } catch (IOException|XmlPullParserException e) {
2330 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002331 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002332 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002333 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002334 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002335 }
2336
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002337 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2338 XmlPullParser parser) throws XmlPullParserException, IOException {
2339 int type = parser.getEventType();
2340 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2341 String key = parser.getAttributeValue(null, ATTR_KEY);
2342 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2343 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2344 if (multiple != null) {
2345 values.clear();
2346 int count = Integer.parseInt(multiple);
2347 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2348 if (type == XmlPullParser.START_TAG
2349 && parser.getName().equals(TAG_VALUE)) {
2350 values.add(parser.nextText().trim());
2351 count--;
2352 }
2353 }
2354 String [] valueStrings = new String[values.size()];
2355 values.toArray(valueStrings);
2356 restrictions.putStringArray(key, valueStrings);
2357 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2358 restrictions.putBundle(key, readBundleEntry(parser, values));
2359 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2360 final int outerDepth = parser.getDepth();
2361 ArrayList<Bundle> bundleList = new ArrayList<>();
2362 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2363 Bundle childBundle = readBundleEntry(parser, values);
2364 bundleList.add(childBundle);
2365 }
2366 restrictions.putParcelableArray(key,
2367 bundleList.toArray(new Bundle[bundleList.size()]));
2368 } else {
2369 String value = parser.nextText().trim();
2370 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2371 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2372 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2373 restrictions.putInt(key, Integer.parseInt(value));
2374 } else {
2375 restrictions.putString(key, value);
2376 }
2377 }
2378 }
2379 }
2380
2381 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2382 throws IOException, XmlPullParserException {
2383 Bundle childBundle = new Bundle();
2384 final int outerDepth = parser.getDepth();
2385 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2386 readEntry(childBundle, values, parser);
2387 }
2388 return childBundle;
2389 }
2390
Fyodor Kupolov82402752015-10-28 14:54:51 -07002391 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002392 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002393 AtomicFile restrictionsFile = new AtomicFile(
2394 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002395 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002396 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002397 }
2398
2399 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002400 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002401 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002402 try {
2403 fos = restrictionsFile.startWrite();
2404 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2405
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002406 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002407 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002408 serializer.startDocument(null, true);
2409 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2410
2411 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002412 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002413 serializer.endTag(null, TAG_RESTRICTIONS);
2414
2415 serializer.endDocument();
2416 restrictionsFile.finishWrite(fos);
2417 } catch (Exception e) {
2418 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002419 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2420 }
2421 }
2422
2423 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2424 throws IOException {
2425 for (String key : restrictions.keySet()) {
2426 Object value = restrictions.get(key);
2427 serializer.startTag(null, TAG_ENTRY);
2428 serializer.attribute(null, ATTR_KEY, key);
2429
2430 if (value instanceof Boolean) {
2431 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2432 serializer.text(value.toString());
2433 } else if (value instanceof Integer) {
2434 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2435 serializer.text(value.toString());
2436 } else if (value == null || value instanceof String) {
2437 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2438 serializer.text(value != null ? (String) value : "");
2439 } else if (value instanceof Bundle) {
2440 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2441 writeBundle((Bundle) value, serializer);
2442 } else if (value instanceof Parcelable[]) {
2443 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2444 Parcelable[] array = (Parcelable[]) value;
2445 for (Parcelable parcelable : array) {
2446 if (!(parcelable instanceof Bundle)) {
2447 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2448 }
2449 serializer.startTag(null, TAG_ENTRY);
2450 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2451 writeBundle((Bundle) parcelable, serializer);
2452 serializer.endTag(null, TAG_ENTRY);
2453 }
2454 } else {
2455 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2456 String[] values = (String[]) value;
2457 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2458 for (String choice : values) {
2459 serializer.startTag(null, TAG_VALUE);
2460 serializer.text(choice != null ? choice : "");
2461 serializer.endTag(null, TAG_VALUE);
2462 }
2463 }
2464 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002465 }
2466 }
2467
2468 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002469 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002470 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002471 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002472 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002473 }
2474 }
2475
2476 @Override
2477 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002478 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002479 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002480 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002481 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002482 }
2483 // Not found
2484 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002485 }
2486 }
2487
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002488 @Override
2489 public long getUserCreationTime(int userHandle) {
2490 int callingUserId = UserHandle.getCallingUserId();
2491 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002492 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002493 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002494 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002495 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002496 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002497 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002498 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002499 }
2500 }
2501 }
2502 if (userInfo == null) {
2503 throw new SecurityException("userHandle can only be the calling user or a managed "
2504 + "profile associated with this user");
2505 }
2506 return userInfo.creationTime;
2507 }
2508
Amith Yamasani0b285492011-04-14 17:35:23 -07002509 /**
2510 * Caches the list of user ids in an array, adjusting the array size when necessary.
2511 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002512 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002513 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002514 synchronized (mUsersLock) {
2515 final int userSize = mUsers.size();
2516 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002517 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002518 num++;
2519 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002520 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002521 final int[] newUsers = new int[num];
2522 int n = 0;
2523 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002524 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002525 newUsers[n++] = mUsers.keyAt(i);
2526 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002527 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002528 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002529 }
2530 }
2531
2532 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002533 * Prepare storage areas for given user on all mounted devices.
2534 */
2535 private void prepareUserStorage(int userId, int userSerial, int flags) {
2536 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2537 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2538 final String volumeUuid = vol.getFsUuid();
2539 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2540 }
2541 }
2542
2543 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002544 * Called right before a user is started. This gives us a chance to prepare
2545 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002546 */
2547 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002548 final int userSerial = getUserSerialNumber(userId);
2549 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2550 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002551
2552 if (userId != UserHandle.USER_SYSTEM) {
2553 synchronized (mRestrictionsLock) {
2554 applyUserRestrictionsLR(userId);
2555 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002556 }
2557 }
2558
2559 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002560 * Called right before a user is unlocked. This gives us a chance to prepare
2561 * app storage.
2562 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002563 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002564 final int userSerial = getUserSerialNumber(userId);
2565 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2566 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002567 }
2568
2569 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002570 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002571 * @param userId the user that was just foregrounded
2572 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002573 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002574 UserData userData = getUserDataNoChecks(userId);
2575 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002576 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2577 return;
2578 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002579
2580 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002581 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002582 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002583 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002584 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2585 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002586 }
2587
2588 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002589 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002590 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2591 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002592 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002593 private int getNextAvailableId() {
2594 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002595 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002596 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002597 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002598 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002599 }
2600 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002601 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002602 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002603 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002604 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002605
Amith Yamasanifc95e702013-09-26 13:20:17 -07002606 private String packageToRestrictionsFileName(String packageName) {
2607 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2608 }
2609
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002610 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002611 * Enforce that serial number stored in user directory inode matches the
2612 * given expected value. Gracefully sets the serial number if currently
2613 * undefined.
2614 *
2615 * @throws IOException when problem extracting serial number, or serial
2616 * number is mismatched.
2617 */
2618 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2619 final int foundSerial = getSerialNumber(file);
2620 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2621
2622 if (foundSerial == -1) {
2623 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2624 try {
2625 setSerialNumber(file, serialNumber);
2626 } catch (IOException e) {
2627 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2628 }
2629
2630 } else if (foundSerial != serialNumber) {
2631 throw new IOException("Found serial number " + foundSerial
2632 + " doesn't match expected " + serialNumber);
2633 }
2634 }
2635
2636 /**
2637 * Set serial number stored in user directory inode.
2638 *
2639 * @throws IOException if serial number was already set
2640 */
2641 private static void setSerialNumber(File file, int serialNumber)
2642 throws IOException {
2643 try {
2644 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2645 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2646 } catch (ErrnoException e) {
2647 throw e.rethrowAsIOException();
2648 }
2649 }
2650
2651 /**
2652 * Return serial number stored in user directory inode.
2653 *
2654 * @return parsed serial number, or -1 if not set
2655 */
2656 private static int getSerialNumber(File file) throws IOException {
2657 try {
2658 final byte[] buf = new byte[256];
2659 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2660 final String serial = new String(buf, 0, len);
2661 try {
2662 return Integer.parseInt(serial);
2663 } catch (NumberFormatException e) {
2664 throw new IOException("Bad serial number: " + serial);
2665 }
2666 } catch (ErrnoException e) {
2667 if (e.errno == OsConstants.ENODATA) {
2668 return -1;
2669 } else {
2670 throw e.rethrowAsIOException();
2671 }
2672 }
2673 }
2674
Amith Yamasani920ace02012-09-20 22:15:37 -07002675 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002676 public void setSeedAccountData(int userId, String accountName, String accountType,
2677 PersistableBundle accountOptions, boolean persist) {
2678 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2679 synchronized (mPackagesLock) {
2680 final UserData userData;
2681 synchronized (mUsersLock) {
2682 userData = getUserDataLU(userId);
2683 if (userData == null) {
2684 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2685 return;
2686 }
2687 userData.seedAccountName = accountName;
2688 userData.seedAccountType = accountType;
2689 userData.seedAccountOptions = accountOptions;
2690 userData.persistSeedData = persist;
2691 }
2692 if (persist) {
2693 writeUserLP(userData);
2694 }
2695 }
2696 }
2697
2698 @Override
2699 public String getSeedAccountName() throws RemoteException {
2700 checkManageUsersPermission("Cannot get seed account information");
2701 synchronized (mUsersLock) {
2702 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2703 return userData.seedAccountName;
2704 }
2705 }
2706
2707 @Override
2708 public String getSeedAccountType() throws RemoteException {
2709 checkManageUsersPermission("Cannot get seed account information");
2710 synchronized (mUsersLock) {
2711 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2712 return userData.seedAccountType;
2713 }
2714 }
2715
2716 @Override
2717 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2718 checkManageUsersPermission("Cannot get seed account information");
2719 synchronized (mUsersLock) {
2720 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2721 return userData.seedAccountOptions;
2722 }
2723 }
2724
2725 @Override
2726 public void clearSeedAccountData() throws RemoteException {
2727 checkManageUsersPermission("Cannot clear seed account information");
2728 synchronized (mPackagesLock) {
2729 UserData userData;
2730 synchronized (mUsersLock) {
2731 userData = getUserDataLU(UserHandle.getCallingUserId());
2732 if (userData == null) return;
2733 userData.clearSeedAccountData();
2734 }
2735 writeUserLP(userData);
2736 }
2737 }
2738
2739 @Override
2740 public boolean someUserHasSeedAccount(String accountName, String accountType)
2741 throws RemoteException {
2742 checkManageUsersPermission("Cannot check seed account information");
2743 synchronized (mUsersLock) {
2744 final int userSize = mUsers.size();
2745 for (int i = 0; i < userSize; i++) {
2746 final UserData data = mUsers.valueAt(i);
2747 if (data.info.isInitialized()) continue;
2748 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2749 continue;
2750 }
2751 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2752 continue;
2753 }
2754 return true;
2755 }
2756 }
2757 return false;
2758 }
2759
2760 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002761 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2762 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2763 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2764 }
2765
2766 int onShellCommand(Shell shell, String cmd) {
2767 if (cmd == null) {
2768 return shell.handleDefaultCommands(cmd);
2769 }
2770
2771 final PrintWriter pw = shell.getOutPrintWriter();
2772 try {
2773 switch(cmd) {
2774 case "list":
2775 return runList(pw);
2776 }
2777 } catch (RemoteException e) {
2778 pw.println("Remote exception: " + e);
2779 }
2780 return -1;
2781 }
2782
2783 private int runList(PrintWriter pw) throws RemoteException {
2784 final IActivityManager am = ActivityManagerNative.getDefault();
2785 final List<UserInfo> users = getUsers(false);
2786 if (users == null) {
2787 pw.println("Error: couldn't get users");
2788 return 1;
2789 } else {
2790 pw.println("Users:");
2791 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002792 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002793 pw.println("\t" + users.get(i).toString() + running);
2794 }
2795 return 0;
2796 }
2797 }
2798
2799 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002800 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2801 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2802 != PackageManager.PERMISSION_GRANTED) {
2803 pw.println("Permission Denial: can't dump UserManager from from pid="
2804 + Binder.getCallingPid()
2805 + ", uid=" + Binder.getCallingUid()
2806 + " without permission "
2807 + android.Manifest.permission.DUMP);
2808 return;
2809 }
2810
2811 long now = System.currentTimeMillis();
2812 StringBuilder sb = new StringBuilder();
2813 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002814 synchronized (mUsersLock) {
2815 pw.println("Users:");
2816 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002817 UserData userData = mUsers.valueAt(i);
2818 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002819 continue;
2820 }
Amith Yamasani12747872015-12-07 14:19:49 -08002821 UserInfo userInfo = userData.info;
2822 final int userId = userInfo.id;
2823 pw.print(" "); pw.print(userInfo);
2824 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002825 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002826 pw.print(" <removing> ");
2827 }
Amith Yamasani12747872015-12-07 14:19:49 -08002828 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002829 pw.print(" <partial>");
2830 }
2831 pw.println();
2832 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002833 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002834 pw.println("<unknown>");
2835 } else {
2836 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002837 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002838 sb.append(" ago");
2839 pw.println(sb);
2840 }
2841 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002842 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002843 pw.println("<unknown>");
2844 } else {
2845 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002846 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002847 sb.append(" ago");
2848 pw.println(sb);
2849 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002850 pw.print(" Last logged in fingerprint: ");
2851 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08002852 pw.print(" Has profile owner: ");
2853 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002854 pw.println(" Restrictions:");
2855 synchronized (mRestrictionsLock) {
2856 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002857 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002858 pw.println(" Device policy local restrictions:");
2859 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002860 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002861 pw.println(" Effective restrictions:");
2862 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002863 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002864 }
Amith Yamasani12747872015-12-07 14:19:49 -08002865
2866 if (userData.account != null) {
2867 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002868 pw.println();
2869 }
Amith Yamasani12747872015-12-07 14:19:49 -08002870
2871 if (userData.seedAccountName != null) {
2872 pw.print(" Seed account name: " + userData.seedAccountName);
2873 pw.println();
2874 if (userData.seedAccountType != null) {
2875 pw.print(" account type: " + userData.seedAccountType);
2876 pw.println();
2877 }
2878 if (userData.seedAccountOptions != null) {
2879 pw.print(" account options exist");
2880 pw.println();
2881 }
2882 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002883 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002884 }
Amith Yamasani12747872015-12-07 14:19:49 -08002885 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002886 pw.println(" Device policy global restrictions:");
2887 synchronized (mRestrictionsLock) {
2888 UserRestrictionsUtils
2889 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2890 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002891 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002892 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002893 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002894 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002895 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002896 synchronized (mUsersLock) {
2897 pw.println();
2898 pw.println(" Device managed: " + mIsDeviceManaged);
2899 }
Amith Yamasani12747872015-12-07 14:19:49 -08002900 // Dump some capabilities
2901 pw.println();
2902 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2903 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002904 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2905 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002906 }
2907 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002908
2909 final class MainHandler extends Handler {
2910
2911 @Override
2912 public void handleMessage(Message msg) {
2913 switch (msg.what) {
2914 case WRITE_USER_MSG:
2915 removeMessages(WRITE_USER_MSG, msg.obj);
2916 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002917 int userId = ((UserData) msg.obj).info.id;
2918 UserData userData = getUserDataNoChecks(userId);
2919 if (userData != null) {
2920 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002921 }
2922 }
2923 }
2924 }
2925 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002926
2927 /**
2928 * @param userId
2929 * @return whether the user has been initialized yet
2930 */
2931 boolean isInitialized(int userId) {
2932 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2933 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002934
2935 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002936 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002937 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2938 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002939 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002940 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002941 }
2942
2943 @Override
2944 public Bundle getBaseUserRestrictions(int userId) {
2945 synchronized (mRestrictionsLock) {
2946 return mBaseUserRestrictions.get(userId);
2947 }
2948 }
2949
2950 @Override
2951 public void setBaseUserRestrictionsByDpmsForMigration(
2952 int userId, Bundle baseRestrictions) {
2953 synchronized (mRestrictionsLock) {
2954 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002955 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002956 }
2957
Amith Yamasani12747872015-12-07 14:19:49 -08002958 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002959 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002960 if (userData != null) {
2961 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002962 } else {
2963 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2964 }
2965 }
2966 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002967
2968 @Override
2969 public boolean getUserRestriction(int userId, String key) {
2970 return getUserRestrictions(userId).getBoolean(key);
2971 }
2972
2973 @Override
2974 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2975 synchronized (mUserRestrictionsListeners) {
2976 mUserRestrictionsListeners.add(listener);
2977 }
2978 }
2979
2980 @Override
2981 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2982 synchronized (mUserRestrictionsListeners) {
2983 mUserRestrictionsListeners.remove(listener);
2984 }
2985 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002986
2987 @Override
2988 public void setDeviceManaged(boolean isManaged) {
2989 synchronized (mUsersLock) {
2990 mIsDeviceManaged = isManaged;
2991 }
2992 }
2993
2994 @Override
2995 public void setUserManaged(int userId, boolean isManaged) {
2996 synchronized (mUsersLock) {
2997 mIsUserManaged.put(userId, isManaged);
2998 }
2999 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003000
3001 @Override
3002 public void setUserIcon(int userId, Bitmap bitmap) {
3003 long ident = Binder.clearCallingIdentity();
3004 try {
3005 synchronized (mPackagesLock) {
3006 UserData userData = getUserDataNoChecks(userId);
3007 if (userData == null || userData.info.partial) {
3008 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3009 return;
3010 }
3011 writeBitmapLP(userData.info, bitmap);
3012 writeUserLP(userData);
3013 }
3014 sendUserInfoChangedBroadcast(userId);
3015 } finally {
3016 Binder.restoreCallingIdentity(ident);
3017 }
3018 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003019
3020 @Override
3021 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3022 synchronized (mUsersLock) {
3023 mForceEphemeralUsers = forceEphemeralUsers;
3024 }
3025 }
3026
3027 @Override
3028 public void removeAllUsers() {
3029 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3030 // Remove the non-system users straight away.
3031 removeNonSystemUsers();
3032 } else {
3033 // Switch to the system user first and then remove the other users.
3034 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3035 @Override
3036 public void onReceive(Context context, Intent intent) {
3037 int userId =
3038 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3039 if (userId != UserHandle.USER_SYSTEM) {
3040 return;
3041 }
3042 mContext.unregisterReceiver(this);
3043 removeNonSystemUsers();
3044 }
3045 };
3046 IntentFilter userSwitchedFilter = new IntentFilter();
3047 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3048 mContext.registerReceiver(
3049 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3050
3051 // Switch to the system user.
3052 ActivityManager am =
3053 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3054 am.switchUser(UserHandle.USER_SYSTEM);
3055 }
3056 }
phweisse9c44062016-02-10 12:57:38 +01003057
3058 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003059 public void onEphemeralUserStop(int userId) {
3060 synchronized (mUsersLock) {
3061 UserInfo userInfo = getUserInfoLU(userId);
3062 if (userInfo != null && userInfo.isEphemeral()) {
3063 // Do not allow switching back to the ephemeral user again as the user is going
3064 // to be deleted.
3065 userInfo.flags |= UserInfo.FLAG_DISABLED;
3066 if (userInfo.isGuest()) {
3067 // Indicate that the guest will be deleted after it stops.
3068 userInfo.guestToRemove = true;
3069 }
3070 }
3071 }
3072 }
3073
3074 @Override
phweisse9c44062016-02-10 12:57:38 +01003075 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3076 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3077 // Keep this in sync with UserManager.createUser
3078 if (user != null && !user.isAdmin()) {
3079 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3080 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3081 }
3082 return user;
3083 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003084 }
3085
3086 /* Remove all the users except of the system one. */
3087 private void removeNonSystemUsers() {
3088 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3089 synchronized (mUsersLock) {
3090 final int userSize = mUsers.size();
3091 for (int i = 0; i < userSize; i++) {
3092 UserInfo ui = mUsers.valueAt(i).info;
3093 if (ui.id != UserHandle.USER_SYSTEM) {
3094 usersToRemove.add(ui);
3095 }
3096 }
3097 }
3098 for (UserInfo ui: usersToRemove) {
3099 removeUser(ui.id);
3100 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003101 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003102
3103 private class Shell extends ShellCommand {
3104 @Override
3105 public int onCommand(String cmd) {
3106 return onShellCommand(this, cmd);
3107 }
3108
3109 @Override
3110 public void onHelp() {
3111 final PrintWriter pw = getOutPrintWriter();
3112 pw.println("User manager (user) commands:");
3113 pw.println(" help");
3114 pw.println(" Print this help text.");
3115 pw.println("");
3116 pw.println(" list");
3117 pw.println(" Prints all users on the system.");
3118 }
3119 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003120
3121 private static void debug(String message) {
3122 Log.d(LOG_TAG, message +
3123 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3124 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003125}