blob: 60ea2544cadc4335dcb2c5b5fe3d7f82d95a7afa [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 Yamasani0b285492011-04-14 17:35:23 -070034import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080035import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010037import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070038import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060040import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080041import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080042import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.os.Environment;
44import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080045import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080046import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070047import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080048import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010049import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070050import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080051import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070052import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070053import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070054import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010055import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040056import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070057import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070058import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070059import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070060import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080061import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010062import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070063import android.os.storage.VolumeInfo;
64import android.system.ErrnoException;
65import android.system.Os;
66import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070067import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070068import android.util.IntArray;
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) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700471 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800472 if (userId != UserHandle.getCallingUserId()) {
473 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700474 } else {
475 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800476 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700477 final long ident = Binder.clearCallingIdentity();
478 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700479 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700480 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100481 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700482 } finally {
483 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000484 }
485 }
486
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700487 @Override
488 public int[] getProfileIds(int userId, boolean enabledOnly) {
489 if (userId != UserHandle.getCallingUserId()) {
490 checkManageUsersPermission("getting profiles related to user " + userId);
491 }
492 final long ident = Binder.clearCallingIdentity();
493 try {
494 synchronized (mUsersLock) {
495 return getProfileIdsLU(userId, enabledOnly).toArray();
496 }
497 } finally {
498 Binder.restoreCallingIdentity(ident);
499 }
500 }
501
Amith Yamasanibe465322014-04-24 13:45:17 -0700502 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700503 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700504 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
505 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
506 for (int i = 0; i < profileIds.size(); i++) {
507 int profileId = profileIds.get(i);
508 UserInfo userInfo = mUsers.get(profileId).info;
509 // If full info is not required - clear PII data to prevent 3P apps from reading it
510 if (!fullInfo) {
511 userInfo = new UserInfo(userInfo);
512 userInfo.name = null;
513 userInfo.iconPath = null;
514 } else {
515 userInfo = userWithName(userInfo);
516 }
517 users.add(userInfo);
518 }
519 return users;
520 }
521
522 /**
523 * Assume permissions already checked and caller's identity cleared
524 */
525 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700526 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700527 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700528 if (user == null) {
529 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700530 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700531 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700532 final int userSize = mUsers.size();
533 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800534 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700535 if (!isProfileOf(user, profile)) {
536 continue;
537 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100538 if (enabledOnly && !profile.isEnabled()) {
539 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700540 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700541 if (mRemovingUserIds.get(profile.id)) {
542 continue;
543 }
Tony Mak80189cd2016-04-05 17:21:42 +0100544 if (profile.partial) {
545 continue;
546 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700547 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700548 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700549 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700550 }
551
Jessica Hummelbe81c802014-04-22 15:49:22 +0100552 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700553 public int getCredentialOwnerProfile(int userHandle) {
554 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000555 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 synchronized (mUsersLock) {
557 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700558 if (profileParent != null) {
559 return profileParent.id;
560 }
561 }
562 }
563
564 return userHandle;
565 }
566
567 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700568 public boolean isSameProfileGroup(int userId, int otherUserId) {
569 if (userId == otherUserId) return true;
570 checkManageUsersPermission("check if in the same profile group");
571 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700572 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700573 }
574 }
575
Fyodor Kupolov82402752015-10-28 14:54:51 -0700576 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
577 synchronized (mUsersLock) {
578 UserInfo userInfo = getUserInfoLU(userId);
579 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
580 return false;
581 }
582 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
583 if (otherUserInfo == null
584 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
585 return false;
586 }
587 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700588 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700589 }
590
591 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100592 public UserInfo getProfileParent(int userHandle) {
593 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700594 synchronized (mUsersLock) {
595 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700596 }
597 }
598
Fyodor Kupolov82402752015-10-28 14:54:51 -0700599 private UserInfo getProfileParentLU(int userHandle) {
600 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700601 if (profile == null) {
602 return null;
603 }
604 int parentUserId = profile.profileGroupId;
605 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
606 return null;
607 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700608 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100609 }
610 }
611
Fyodor Kupolov82402752015-10-28 14:54:51 -0700612 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100613 return user.id == profile.id ||
614 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
615 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000616 }
617
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000618 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000619 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100620 Intent intent = new Intent();
621 if (inQuietMode) {
622 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
623 } else {
624 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
625 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000626 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
627 intent.putExtra(Intent.EXTRA_USER, profileHandle);
628 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000629 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000630 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xue95057a2016-04-01 16:49:25 +0100631
632 //TODO: remove once Launcher3 is updated.
633 Intent oldIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
634 oldIntent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
635 oldIntent.putExtra(Intent.EXTRA_USER, profileHandle);
636 oldIntent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
637 oldIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
638 mContext.sendBroadcastAsUser(oldIntent, parentHandle);
639
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000640 }
641
642 @Override
643 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
644 checkManageUsersPermission("silence profile");
645 boolean changed = false;
646 UserInfo profile, parent;
647 synchronized (mPackagesLock) {
648 synchronized (mUsersLock) {
649 profile = getUserInfoLU(userHandle);
650 parent = getProfileParentLU(userHandle);
651
652 }
653 if (profile == null || !profile.isManagedProfile()) {
654 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
655 }
656 if (profile.isQuietModeEnabled() != enableQuietMode) {
657 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800658 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000659 changed = true;
660 }
661 }
662 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000663 long identity = Binder.clearCallingIdentity();
664 try {
665 if (enableQuietMode) {
666 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
667 } else {
668 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
669 }
670 } catch (RemoteException e) {
671 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
672 } finally {
673 Binder.restoreCallingIdentity(identity);
674 }
675
676 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
677 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000678 }
679 }
680
681 @Override
682 public boolean isQuietModeEnabled(int userHandle) {
683 synchronized (mPackagesLock) {
684 UserInfo info;
685 synchronized (mUsersLock) {
686 info = getUserInfoLU(userHandle);
687 }
688 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000689 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000690 }
691 return info.isQuietModeEnabled();
692 }
693 }
694
Kenny Guya52dc3e2014-02-11 15:33:14 +0000695 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100696 public void setUserEnabled(int userId) {
697 checkManageUsersPermission("enable user");
698 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700699 UserInfo info;
700 synchronized (mUsersLock) {
701 info = getUserInfoLU(userId);
702 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100703 if (info != null && !info.isEnabled()) {
704 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800705 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100706 }
707 }
708 }
709
710 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700711 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000712 checkManageUsersPermission("query user");
713 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700714 return userWithName(getUserInfoLU(userId));
715 }
716 }
717
718 /**
719 * Returns a UserInfo object with the name filled in, for Owner, or the original
720 * if the name is already set.
721 */
722 private UserInfo userWithName(UserInfo orig) {
723 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
724 UserInfo withName = new UserInfo(orig);
725 withName.name = getOwnerName();
726 return withName;
727 } else {
728 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000729 }
730 }
731
732 @Override
733 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000734 int callingUserId = UserHandle.getCallingUserId();
735 if (callingUserId != userId && !hasManageUsersPermission()) {
736 synchronized (mPackagesLock) {
737 if (!isSameProfileGroupLP(callingUserId, userId)) {
738 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000739 "You need MANAGE_USERS permission to: check if specified user a " +
740 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000741 }
742 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000743 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700744 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000745 UserInfo userInfo = getUserInfoLU(userId);
746 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700747 }
748 }
749
Amith Yamasani71e6c692013-03-24 17:39:28 -0700750 @Override
751 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700752 synchronized (mUsersLock) {
753 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700754 }
755 }
756
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700757 @Override
758 public boolean canHaveRestrictedProfile(int userId) {
759 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700760 synchronized (mUsersLock) {
761 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700762 if (userInfo == null || !userInfo.canHaveProfile()) {
763 return false;
764 }
765 if (!userInfo.isAdmin()) {
766 return false;
767 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800768 // restricted profile can be created if there is no DO set and the admin user has no PO;
769 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700770 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700771 }
772
Amith Yamasani195263742012-08-21 15:40:12 -0700773 /*
774 * Should be locked on mUsers before calling this.
775 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700776 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800777 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700778 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800779 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700780 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
781 return null;
782 }
Amith Yamasani12747872015-12-07 14:19:49 -0800783 return userData != null ? userData.info : null;
784 }
785
786 private UserData getUserDataLU(int userId) {
787 final UserData userData = mUsers.get(userId);
788 // If it is partial and not in the process of being removed, return as unknown user.
789 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
790 return null;
791 }
792 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700793 }
794
Fyodor Kupolov82402752015-10-28 14:54:51 -0700795 /**
796 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
797 * <p>No permissions checking or any addition checks are made</p>
798 */
799 private UserInfo getUserInfoNoChecks(int userId) {
800 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800801 final UserData userData = mUsers.get(userId);
802 return userData != null ? userData.info : null;
803 }
804 }
805
806 /**
807 * Obtains {@link #mUsersLock} and return UserData from mUsers.
808 * <p>No permissions checking or any addition checks are made</p>
809 */
810 private UserData getUserDataNoChecks(int userId) {
811 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700812 return mUsers.get(userId);
813 }
814 }
815
Amith Yamasani236b2b52015-08-18 14:32:14 -0700816 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700817 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700818 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700819 }
820
Amith Yamasani258848d2012-08-10 17:06:33 -0700821 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700822 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700823 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700824 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700825 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800826 UserData userData = getUserDataNoChecks(userId);
827 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700828 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
829 return;
830 }
Amith Yamasani12747872015-12-07 14:19:49 -0800831 if (name != null && !name.equals(userData.info.name)) {
832 userData.info.name = name;
833 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700834 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700835 }
836 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700837 if (changed) {
838 sendUserInfoChangedBroadcast(userId);
839 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700840 }
841
Amith Yamasani258848d2012-08-10 17:06:33 -0700842 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700843 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700844 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100845 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
846 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
847 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700848 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100849 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700850 }
851
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100852
853
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700854 private void sendUserInfoChangedBroadcast(int userId) {
855 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
856 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
857 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700858 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700859 }
860
Amith Yamasani258848d2012-08-10 17:06:33 -0700861 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100862 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100863 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700864 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100865 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
866 if (targetUserInfo == null || targetUserInfo.partial) {
867 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700868 return null;
869 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100870
871 final int callingUserId = UserHandle.getCallingUserId();
872 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
873 final int targetGroupId = targetUserInfo.profileGroupId;
874 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
875 && callingGroupId == targetGroupId);
876 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100877 checkManageUsersPermission("get the icon of a user who is not related");
878 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100879
880 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700881 return null;
882 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100883 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700884 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100885
886 try {
887 return ParcelFileDescriptor.open(
888 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
889 } catch (FileNotFoundException e) {
890 Log.e(LOG_TAG, "Couldn't find icon file", e);
891 }
892 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700893 }
894
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700895 public void makeInitialized(int userId) {
896 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800897 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800898 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800899 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800900 userData = mUsers.get(userId);
901 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700902 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800903 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700904 }
Amith Yamasani12747872015-12-07 14:19:49 -0800905 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
906 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800907 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700908 }
909 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800910 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800911 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800912 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700913 }
914
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700915 /**
916 * If default guest restrictions haven't been initialized yet, add the basic
917 * restrictions.
918 */
919 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800920 synchronized (mGuestRestrictions) {
921 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -0700922 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800923 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800924 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
925 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
926 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700927 }
928 }
929
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800930 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530931 public Bundle getDefaultGuestRestrictions() {
932 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800933 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530934 return new Bundle(mGuestRestrictions);
935 }
936 }
937
938 @Override
939 public void setDefaultGuestRestrictions(Bundle restrictions) {
940 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800941 synchronized (mGuestRestrictions) {
942 mGuestRestrictions.clear();
943 mGuestRestrictions.putAll(restrictions);
944 }
945 synchronized (mPackagesLock) {
946 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530947 }
948 }
949
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800950 /**
951 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
952 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800953 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800954 @Nullable Bundle global) {
955 Preconditions.checkNotNull(local);
956 boolean globalChanged = false;
957 boolean localChanged;
958 synchronized (mRestrictionsLock) {
959 if (global != null) {
960 // Update global.
961 globalChanged = !UserRestrictionsUtils.areEqual(
962 mDevicePolicyGlobalUserRestrictions, global);
963 if (globalChanged) {
964 mDevicePolicyGlobalUserRestrictions = global;
965 }
966 }
967 {
968 // Update local.
969 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
970 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
971 if (localChanged) {
972 mDevicePolicyLocalUserRestrictions.put(userId, local);
973 }
974 }
975 }
976 if (DBG) {
977 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
978 + " global=" + global + (globalChanged ? " (changed)" : "")
979 + " local=" + local + (localChanged ? " (changed)" : "")
980 );
981 }
982 // Don't call them within the mRestrictionsLock.
983 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800984 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800985 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800986 }
Jeff Sharkeycd575992016-03-29 14:12:49 -0600987 if (globalChanged) {
988 writeUserListLP();
989 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800990 }
991
992 synchronized (mRestrictionsLock) {
993 if (globalChanged) {
994 applyUserRestrictionsForAllUsersLR();
995 } else if (localChanged) {
996 applyUserRestrictionsLR(userId);
997 }
998 }
999 }
1000
Makoto Onuki068c54a2015-10-13 14:34:03 -07001001 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001002 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001003 final Bundle baseRestrictions =
1004 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1005 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1006 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001007
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001008 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1009 // Common case first.
1010 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001011 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001012 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1013 UserRestrictionsUtils.merge(effective, global);
1014 UserRestrictionsUtils.merge(effective, local);
1015
Makoto Onuki068c54a2015-10-13 14:34:03 -07001016 return effective;
1017 }
1018
1019 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001020 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001021 if (DBG) {
1022 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1023 }
1024 mCachedEffectiveUserRestrictions.remove(userId);
1025 }
1026
1027 private Bundle getEffectiveUserRestrictions(int userId) {
1028 synchronized (mRestrictionsLock) {
1029 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1030 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001031 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001032 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1033 }
1034 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001035 }
1036 }
1037
Makoto Onuki068c54a2015-10-13 14:34:03 -07001038 /** @return a specific user restriction that's in effect currently. */
1039 @Override
1040 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001041 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1042 return false;
1043 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001044 Bundle restrictions = getEffectiveUserRestrictions(userId);
1045 return restrictions != null && restrictions.getBoolean(restrictionKey);
1046 }
1047
1048 /**
1049 * @return UserRestrictions that are in effect currently. This always returns a new
1050 * {@link Bundle}.
1051 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001052 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001053 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001054 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001055 }
1056
1057 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001058 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1059 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001060 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1061 return false;
1062 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001063 synchronized (mRestrictionsLock) {
1064 Bundle bundle = mBaseUserRestrictions.get(userId);
1065 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1066 }
1067 }
1068
1069 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001070 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001071 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001072 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1073 return;
1074 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001075 synchronized (mRestrictionsLock) {
1076 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1077 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001078 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1079 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001080 newRestrictions.putBoolean(key, value);
1081
Fyodor Kupolov82402752015-10-28 14:54:51 -07001082 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001083 }
1084 }
1085
Makoto Onuki068c54a2015-10-13 14:34:03 -07001086 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001087 * Optionally updating user restrictions, calculate the effective user restrictions and also
1088 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001089 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001090 * @param newRestrictions User restrictions to set.
1091 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001092 * @param userId target user ID.
1093 */
1094 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001095 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001096 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001097
1098 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1099 mAppliedUserRestrictions.get(userId));
1100
1101 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001102 if (newRestrictions != null) {
1103 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001104 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1105
1106 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001107 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1108 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001109
1110 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1111 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001112 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001113 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001114 }
1115
Fyodor Kupolov82402752015-10-28 14:54:51 -07001116 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001117
Makoto Onuki759a7632015-10-28 16:43:10 -07001118 mCachedEffectiveUserRestrictions.put(userId, effective);
1119
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001120 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001121 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001122 debug("Applying user restrictions: userId=" + userId
1123 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001124 }
1125
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001126 if (mAppOpsService != null) { // We skip it until system-ready.
1127 final long token = Binder.clearCallingIdentity();
1128 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001129 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001130 } catch (RemoteException e) {
1131 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1132 } finally {
1133 Binder.restoreCallingIdentity(token);
1134 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001135 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001136
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001137 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001138
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001139 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001140 }
1141
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001142 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001143 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001144 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1145 // actually, but we still need some kind of synchronization otherwise we might end up
1146 // calling listeners out-of-order, thus "LR".
1147
1148 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1149 return;
1150 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001151
1152 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1153 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1154
1155 mHandler.post(new Runnable() {
1156 @Override
1157 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001158 UserRestrictionsUtils.applyUserRestrictions(
1159 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001160
Makoto Onukid45a4a22015-11-02 17:17:38 -08001161 final UserRestrictionsListener[] listeners;
1162 synchronized (mUserRestrictionsListeners) {
1163 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1164 mUserRestrictionsListeners.toArray(listeners);
1165 }
1166 for (int i = 0; i < listeners.length; i++) {
1167 listeners[i].onUserRestrictionsChanged(userId,
1168 newRestrictionsFinal, prevRestrictionsFinal);
1169 }
1170 }
1171 });
1172 }
1173
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001174 // Package private for the inner class.
1175 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001176 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001177 }
1178
1179 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001180 // Package private for the inner class.
1181 void applyUserRestrictionsForAllUsersLR() {
1182 if (DBG) {
1183 debug("applyUserRestrictionsForAllUsersLR");
1184 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001185 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001186 mCachedEffectiveUserRestrictions.clear();
1187
Makoto Onuki068c54a2015-10-13 14:34:03 -07001188 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1189 // it on a handler.
1190 final Runnable r = new Runnable() {
1191 @Override
1192 public void run() {
1193 // Then get the list of running users.
1194 final int[] runningUsers;
1195 try {
1196 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1197 } catch (RemoteException e) {
1198 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1199 return;
1200 }
1201 // Then re-calculate the effective restrictions and apply, only for running users.
1202 // It's okay if a new user has started after the getRunningUserIds() call,
1203 // because we'll do the same thing (re-calculate the restrictions and apply)
1204 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001205 synchronized (mRestrictionsLock) {
1206 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001207 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001208 }
1209 }
1210 }
1211 };
1212 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001213 }
1214
Amith Yamasani258848d2012-08-10 17:06:33 -07001215 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001216 * Check if we've hit the limit of how many users can be created.
1217 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001218 private boolean isUserLimitReached() {
1219 int count;
1220 synchronized (mUsersLock) {
1221 count = getAliveUsersExcludingGuestsCountLU();
1222 }
1223 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001224 }
1225
1226 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001227 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001228 checkManageUsersPermission("check if more managed profiles can be added.");
1229 if (ActivityManager.isLowRamDeviceStatic()) {
1230 return false;
1231 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001232 if (!mContext.getPackageManager().hasSystemFeature(
1233 PackageManager.FEATURE_MANAGED_USERS)) {
1234 return false;
1235 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001236 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001237 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1238 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1239 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001240 return false;
1241 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001242 synchronized(mUsersLock) {
1243 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001244 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001245 return false;
1246 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001247 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1248 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001249 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001250 return usersCountAfterRemoving == 1
1251 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001252 }
1253 }
1254
Fyodor Kupolov82402752015-10-28 14:54:51 -07001255 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001256 int aliveUserCount = 0;
1257 final int totalUserCount = mUsers.size();
1258 // Skip over users being removed
1259 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001260 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001261 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001262 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001263 aliveUserCount++;
1264 }
1265 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001266 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001267 }
1268
1269 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001270 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001271 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1272 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1273 * permissions can make certain calls to the UserManager.
1274 *
1275 * @param message used as message if SecurityException is thrown
1276 * @throws SecurityException if the caller does not have enough privilege.
1277 */
1278 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1279 final int uid = Binder.getCallingUid();
1280 if (uid != Process.SYSTEM_UID && uid != 0
1281 && ActivityManager.checkComponentPermission(
1282 Manifest.permission.MANAGE_USERS,
1283 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1284 && ActivityManager.checkComponentPermission(
1285 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1286 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1287 throw new SecurityException(
1288 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1289 + message);
1290 }
1291 }
1292
1293 /**
1294 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001295 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001296 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001297 *
1298 * @param message used as message if SecurityException is thrown
1299 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001300 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001301 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001302 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001303 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001304 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1305 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001306 }
1307
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001308 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001309 * @return whether the calling UID is system UID or root's UID or the calling app has the
1310 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1311 */
1312 private static final boolean hasManageUsersPermission() {
1313 final int callingUid = Binder.getCallingUid();
1314 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1315 || callingUid == Process.ROOT_UID
1316 || ActivityManager.checkComponentPermission(
1317 android.Manifest.permission.MANAGE_USERS,
1318 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1319 }
1320
1321 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001322 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1323 * UserManager.
1324 *
1325 * @param message used as message if SecurityException is thrown
1326 * @throws SecurityException if the caller is not system or root
1327 */
1328 private static void checkSystemOrRoot(String message) {
1329 final int uid = Binder.getCallingUid();
1330 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1331 throw new SecurityException("Only system may: " + message);
1332 }
1333 }
1334
Fyodor Kupolov82402752015-10-28 14:54:51 -07001335 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001336 try {
1337 File dir = new File(mUsersDir, Integer.toString(info.id));
1338 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001339 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001340 if (!dir.exists()) {
1341 dir.mkdir();
1342 FileUtils.setPermissions(
1343 dir.getPath(),
1344 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1345 -1, -1);
1346 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001347 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001348 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001349 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001350 info.iconPath = file.getAbsolutePath();
1351 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001352 try {
1353 os.close();
1354 } catch (IOException ioe) {
1355 // What the ... !
1356 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001357 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001358 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001359 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001360 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001361 }
1362
Amith Yamasani0b285492011-04-14 17:35:23 -07001363 /**
1364 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1365 * cache it elsewhere.
1366 * @return the array of user ids.
1367 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001368 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001369 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001370 return mUserIds;
1371 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001372 }
1373
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001374 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001375 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001376 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001377 return;
1378 }
1379 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001380 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001381 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001382 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001383 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001384 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001385 int type;
1386 while ((type = parser.next()) != XmlPullParser.START_TAG
1387 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001388 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001389 }
1390
1391 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001392 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001393 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001394 return;
1395 }
1396
Amith Yamasani2a003292012-08-14 18:25:45 -07001397 mNextSerialNumber = -1;
1398 if (parser.getName().equals(TAG_USERS)) {
1399 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1400 if (lastSerialNumber != null) {
1401 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1402 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001403 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1404 if (versionNumber != null) {
1405 mUserVersion = Integer.parseInt(versionNumber);
1406 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001407 }
1408
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001409 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1410
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001411 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301412 if (type == XmlPullParser.START_TAG) {
1413 final String name = parser.getName();
1414 if (name.equals(TAG_USER)) {
1415 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001416
Amith Yamasani12747872015-12-07 14:19:49 -08001417 UserData userData = readUserLP(Integer.parseInt(id));
1418
1419 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001420 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001421 mUsers.put(userData.info.id, userData);
1422 if (mNextSerialNumber < 0
1423 || mNextSerialNumber <= userData.info.id) {
1424 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001425 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301426 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001427 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301428 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001429 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1430 && type != XmlPullParser.END_TAG) {
1431 if (type == XmlPullParser.START_TAG) {
1432 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001433 synchronized (mGuestRestrictions) {
1434 UserRestrictionsUtils
1435 .readRestrictions(parser, mGuestRestrictions);
1436 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001437 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1438 ) {
1439 UserRestrictionsUtils.readRestrictions(parser,
1440 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001441 }
1442 break;
1443 }
1444 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001445 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001446 }
1447 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001448 synchronized (mRestrictionsLock) {
1449 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1450 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001451 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001452 upgradeIfNecessaryLP();
1453 } catch (IOException | XmlPullParserException e) {
1454 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001455 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001456 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001457 }
1458 }
1459
Amith Yamasani6f34b412012-10-22 18:19:27 -07001460 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001461 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001462 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001463 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001464 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001465 int userVersion = mUserVersion;
1466 if (userVersion < 1) {
1467 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001468 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1469 if ("Primary".equals(userData.info.name)) {
1470 userData.info.name =
1471 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1472 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001473 }
1474 userVersion = 1;
1475 }
1476
Amith Yamasanibc9625052012-11-15 14:39:18 -08001477 if (userVersion < 2) {
1478 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001479 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1480 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1481 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1482 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001483 }
1484 userVersion = 2;
1485 }
1486
Amith Yamasani350962c2013-08-06 11:18:53 -07001487
Amith Yamasani5e486f52013-08-07 11:06:44 -07001488 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001489 userVersion = 4;
1490 }
1491
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001492 if (userVersion < 5) {
1493 initDefaultGuestRestrictions();
1494 userVersion = 5;
1495 }
1496
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001497 if (userVersion < 6) {
1498 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001499 synchronized (mUsersLock) {
1500 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001501 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001502 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001503 if (!splitSystemUser && userData.info.isRestricted()
1504 && (userData.info.restrictedProfileParentId
1505 == UserInfo.NO_PROFILE_GROUP_ID)) {
1506 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1507 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001508 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001509 }
1510 }
1511 userVersion = 6;
1512 }
1513
Amith Yamasani6f34b412012-10-22 18:19:27 -07001514 if (userVersion < USER_VERSION) {
1515 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1516 + USER_VERSION);
1517 } else {
1518 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001519
1520 if (originalVersion < mUserVersion) {
1521 writeUserListLP();
1522 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001523 }
1524 }
1525
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001526 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001527 int flags = UserInfo.FLAG_INITIALIZED;
1528 // In split system user mode, the admin and primary flags are assigned to the first human
1529 // user.
1530 if (!UserManager.isSplitSystemUser()) {
1531 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1532 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001533 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001534 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001535 UserData userData = new UserData();
1536 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001537 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001538 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001539 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001540 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001541 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001542
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001543 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001544 synchronized (mRestrictionsLock) {
1545 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1546 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001547
Fyodor Kupolov82402752015-10-28 14:54:51 -07001548 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001549 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001550
Amith Yamasani12747872015-12-07 14:19:49 -08001551 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001552 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001553 }
1554
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001555 private String getOwnerName() {
1556 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1557 }
1558
Amith Yamasani12747872015-12-07 14:19:49 -08001559 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001560 if (DBG) {
1561 debug("scheduleWriteUser");
1562 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001563 // No need to wrap it within a lock -- worst case, we'll just post the same message
1564 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001565 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1566 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001567 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1568 }
1569 }
1570
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001571 /*
1572 * Writes the user file in this format:
1573 *
1574 * <user flags="20039023" id="0">
1575 * <name>Primary</name>
1576 * </user>
1577 */
Amith Yamasani12747872015-12-07 14:19:49 -08001578 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001579 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001580 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001581 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001582 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001583 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001584 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001585 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001586 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1587
1588 // XmlSerializer serializer = XmlUtils.serializerInstance();
1589 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001590 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001591 serializer.startDocument(null, true);
1592 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1593
Amith Yamasani12747872015-12-07 14:19:49 -08001594 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001595 serializer.startTag(null, TAG_USER);
1596 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001597 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001598 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001599 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1600 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1601 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001602 if (userInfo.lastLoggedInFingerprint != null) {
1603 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1604 userInfo.lastLoggedInFingerprint);
1605 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001606 if (userInfo.iconPath != null) {
1607 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1608 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001609 if (userInfo.partial) {
1610 serializer.attribute(null, ATTR_PARTIAL, "true");
1611 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001612 if (userInfo.guestToRemove) {
1613 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1614 }
Kenny Guy2a764942014-04-02 13:29:20 +01001615 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1616 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1617 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001618 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001619 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1620 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1621 Integer.toString(userInfo.restrictedProfileParentId));
1622 }
Amith Yamasani12747872015-12-07 14:19:49 -08001623 // Write seed data
1624 if (userData.persistSeedData) {
1625 if (userData.seedAccountName != null) {
1626 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1627 }
1628 if (userData.seedAccountType != null) {
1629 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1630 }
1631 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001632 if (userInfo.name != null) {
1633 serializer.startTag(null, TAG_NAME);
1634 serializer.text(userInfo.name);
1635 serializer.endTag(null, TAG_NAME);
1636 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001637 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001638 UserRestrictionsUtils.writeRestrictions(serializer,
1639 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1640 UserRestrictionsUtils.writeRestrictions(serializer,
1641 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1642 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001643 }
Amith Yamasani12747872015-12-07 14:19:49 -08001644
1645 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001646 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001647 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001648 serializer.endTag(null, TAG_ACCOUNT);
1649 }
1650
Amith Yamasani12747872015-12-07 14:19:49 -08001651 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1652 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1653 userData.seedAccountOptions.saveToXml(serializer);
1654 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1655 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001656 serializer.endTag(null, TAG_USER);
1657
1658 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001659 userFile.finishWrite(fos);
1660 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001661 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001662 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001663 }
1664 }
1665
1666 /*
1667 * Writes the user list file in this format:
1668 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001669 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001670 * <user id="0"></user>
1671 * <user id="2"></user>
1672 * </users>
1673 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001674 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001675 if (DBG) {
1676 debug("writeUserList");
1677 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001678 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001679 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001680 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001681 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001682 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1683
1684 // XmlSerializer serializer = XmlUtils.serializerInstance();
1685 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001686 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001687 serializer.startDocument(null, true);
1688 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1689
1690 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001691 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001692 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001693
Adam Lesinskieddeb492014-09-08 17:50:03 -07001694 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001695 synchronized (mGuestRestrictions) {
1696 UserRestrictionsUtils
1697 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1698 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301699 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 synchronized (mRestrictionsLock) {
1701 UserRestrictionsUtils.writeRestrictions(serializer,
1702 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1703 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001704 int[] userIdsToWrite;
1705 synchronized (mUsersLock) {
1706 userIdsToWrite = new int[mUsers.size()];
1707 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001708 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001709 userIdsToWrite[i] = user.id;
1710 }
1711 }
1712 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001713 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001714 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001715 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001716 }
1717
1718 serializer.endTag(null, TAG_USERS);
1719
1720 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001721 userListFile.finishWrite(fos);
1722 } catch (Exception e) {
1723 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001724 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001725 }
1726 }
1727
Amith Yamasani12747872015-12-07 14:19:49 -08001728 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001729 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001730 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001731 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001732 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001733 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001734 long creationTime = 0L;
1735 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001736 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001737 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001738 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001739 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001740 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001741 boolean persistSeedData = false;
1742 String seedAccountName = null;
1743 String seedAccountType = null;
1744 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001745 Bundle baseRestrictions = new Bundle();
1746 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001747
1748 FileInputStream fis = null;
1749 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001750 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001751 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001752 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001753 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001754 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001755 int type;
1756 while ((type = parser.next()) != XmlPullParser.START_TAG
1757 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001758 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001759 }
1760
1761 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001762 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001763 return null;
1764 }
1765
1766 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001767 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1768 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001769 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001770 return null;
1771 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001772 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1773 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001774 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001775 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1776 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001777 lastLoggedInFingerprint = parser.getAttributeValue(null,
1778 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001779 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1780 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001781 restrictedProfileParentId = readIntAttribute(parser,
1782 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001783 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1784 if ("true".equals(valueString)) {
1785 partial = true;
1786 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001787 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1788 if ("true".equals(valueString)) {
1789 guestToRemove = true;
1790 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001791
Amith Yamasani12747872015-12-07 14:19:49 -08001792 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1793 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1794 if (seedAccountName != null || seedAccountType != null) {
1795 persistSeedData = true;
1796 }
1797
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001798 int outerDepth = parser.getDepth();
1799 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1800 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1801 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1802 continue;
1803 }
1804 String tag = parser.getName();
1805 if (TAG_NAME.equals(tag)) {
1806 type = parser.next();
1807 if (type == XmlPullParser.TEXT) {
1808 name = parser.getText();
1809 }
1810 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001811 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1812 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1813 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001814 } else if (TAG_ACCOUNT.equals(tag)) {
1815 type = parser.next();
1816 if (type == XmlPullParser.TEXT) {
1817 account = parser.getText();
1818 }
Amith Yamasani12747872015-12-07 14:19:49 -08001819 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1820 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1821 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001822 }
1823 }
1824 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001825
Amith Yamasani12747872015-12-07 14:19:49 -08001826 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001827 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001828 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001829 userInfo.creationTime = creationTime;
1830 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001831 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001832 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001833 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001834 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001835 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001836
1837 // Create the UserData object that's internal to this class
1838 UserData userData = new UserData();
1839 userData.info = userInfo;
1840 userData.account = account;
1841 userData.seedAccountName = seedAccountName;
1842 userData.seedAccountType = seedAccountType;
1843 userData.persistSeedData = persistSeedData;
1844 userData.seedAccountOptions = seedAccountOptions;
1845
Makoto Onuki068c54a2015-10-13 14:34:03 -07001846 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001847 mBaseUserRestrictions.put(id, baseRestrictions);
1848 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001849 }
Amith Yamasani12747872015-12-07 14:19:49 -08001850 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001851 } catch (IOException ioe) {
1852 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001853 } finally {
1854 if (fis != null) {
1855 try {
1856 fis.close();
1857 } catch (IOException e) {
1858 }
1859 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001860 }
1861 return null;
1862 }
1863
Amith Yamasani920ace02012-09-20 22:15:37 -07001864 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1865 String valueString = parser.getAttributeValue(null, attr);
1866 if (valueString == null) return defaultValue;
1867 try {
1868 return Integer.parseInt(valueString);
1869 } catch (NumberFormatException nfe) {
1870 return defaultValue;
1871 }
1872 }
1873
1874 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1875 String valueString = parser.getAttributeValue(null, attr);
1876 if (valueString == null) return defaultValue;
1877 try {
1878 return Long.parseLong(valueString);
1879 } catch (NumberFormatException nfe) {
1880 return defaultValue;
1881 }
1882 }
1883
Amith Yamasanib82add22013-07-09 11:24:44 -07001884 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001885 * Removes the app restrictions file for a specific package and user id, if it exists.
1886 */
1887 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1888 synchronized (mPackagesLock) {
1889 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001890 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001891 if (resFile.exists()) {
1892 resFile.delete();
1893 }
1894 }
1895 }
1896
Kenny Guya52dc3e2014-02-11 15:33:14 +00001897 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001898 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001899 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001900 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001901 }
1902
Amith Yamasani258848d2012-08-10 17:06:33 -07001903 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001904 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001905 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001906 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001907 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001908
Jessica Hummelbe81c802014-04-22 15:49:22 +01001909 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001910 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001911 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1912 return null;
1913 }
phweisse9c44062016-02-10 12:57:38 +01001914 return createUserInternalUnchecked(name, flags, parentId);
1915 }
1916
1917 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001918 if (ActivityManager.isLowRamDeviceStatic()) {
1919 return null;
1920 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001921 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001922 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001923 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001924 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001925 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001926 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001927 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001928 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001929 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001930 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001931 if (parentId != UserHandle.USER_NULL) {
1932 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001933 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001934 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001935 if (parent == null) return null;
1936 }
1937 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1938 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1939 return null;
1940 }
1941 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1942 // If we're not adding a guest user or a managed profile and the limit has
1943 // been reached, cannot add a user.
1944 return null;
1945 }
1946 // If we're adding a guest and there already exists one, bail.
1947 if (isGuest && findCurrentGuestUser() != null) {
1948 return null;
1949 }
1950 // In legacy mode, restricted profile's parent can only be the owner user
1951 if (isRestricted && !UserManager.isSplitSystemUser()
1952 && (parentId != UserHandle.USER_SYSTEM)) {
1953 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1954 return null;
1955 }
1956 if (isRestricted && UserManager.isSplitSystemUser()) {
1957 if (parent == null) {
1958 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1959 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001960 return null;
1961 }
Amith Yamasani12747872015-12-07 14:19:49 -08001962 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001963 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1964 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001965 return null;
1966 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001967 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001968 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1969 Log.e(LOG_TAG,
1970 "Ephemeral users are supported on split-system-user systems only.");
1971 return null;
1972 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001973 // In split system user mode, we assign the first human user the primary flag.
1974 // And if there is no device owner, we also assign the admin flag to primary user.
1975 if (UserManager.isSplitSystemUser()
1976 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1977 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001978 synchronized (mUsersLock) {
1979 if (!mIsDeviceManaged) {
1980 flags |= UserInfo.FLAG_ADMIN;
1981 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001982 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001983 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001984
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001985 userId = getNextAvailableId();
1986 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001987 boolean ephemeralGuests = Resources.getSystem()
1988 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001989
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001990 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001991 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1992 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1993 || (parent != null && parent.info.isEphemeral())) {
1994 flags |= UserInfo.FLAG_EPHEMERAL;
1995 }
1996
1997 userInfo = new UserInfo(userId, name, null, flags);
1998 userInfo.serialNumber = mNextSerialNumber++;
1999 long now = System.currentTimeMillis();
2000 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2001 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002002 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002003 userData = new UserData();
2004 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002005 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002006 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002007 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002008 writeUserListLP();
2009 if (parent != null) {
2010 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002011 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2012 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002013 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002014 }
Amith Yamasani12747872015-12-07 14:19:49 -08002015 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002016 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002017 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2018 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002019 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002020 }
Amith Yamasani12747872015-12-07 14:19:49 -08002021 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002022 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002023 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002024 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002025 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002026 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07002027 prepareUserStorage(userId, userInfo.serialNumber,
2028 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002029 mPm.createNewUser(userId);
2030 userInfo.partial = false;
2031 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002032 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002033 }
2034 updateUserIds();
2035 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002036 if (isGuest) {
2037 synchronized (mGuestRestrictions) {
2038 restrictions.putAll(mGuestRestrictions);
2039 }
2040 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002041 synchronized (mRestrictionsLock) {
2042 mBaseUserRestrictions.append(userId, restrictions);
2043 }
2044 mPm.newUserCreated(userId);
2045 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2046 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2047 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2048 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002049 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002050 } finally {
2051 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002052 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002053 return userInfo;
2054 }
2055
Amith Yamasani0b285492011-04-14 17:35:23 -07002056 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002057 * @hide
2058 */
Amith Yamasani12747872015-12-07 14:19:49 -08002059 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002060 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2061 checkManageUsersPermission("setupRestrictedProfile");
2062 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2063 if (user == null) {
2064 return null;
2065 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002066 long identity = Binder.clearCallingIdentity();
2067 try {
2068 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2069 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2070 // the putIntForUser() will fail.
2071 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2072 android.provider.Settings.Secure.LOCATION_MODE,
2073 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2074 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2075 } finally {
2076 Binder.restoreCallingIdentity(identity);
2077 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002078 return user;
2079 }
2080
2081 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002082 * Find the current guest user. If the Guest user is partial,
2083 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002084 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002085 private UserInfo findCurrentGuestUser() {
2086 synchronized (mUsersLock) {
2087 final int size = mUsers.size();
2088 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002089 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002090 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2091 return user;
2092 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002093 }
2094 }
2095 return null;
2096 }
2097
2098 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002099 * Mark this guest user for deletion to allow us to create another guest
2100 * and switch to that user before actually removing this guest.
2101 * @param userHandle the userid of the current guest
2102 * @return whether the user could be marked for deletion
2103 */
Amith Yamasani12747872015-12-07 14:19:49 -08002104 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002105 public boolean markGuestForDeletion(int userHandle) {
2106 checkManageUsersPermission("Only the system can remove users");
2107 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2108 UserManager.DISALLOW_REMOVE_USER, false)) {
2109 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2110 return false;
2111 }
2112
2113 long ident = Binder.clearCallingIdentity();
2114 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002115 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002116 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002117 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002118 userData = mUsers.get(userHandle);
2119 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002120 return false;
2121 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002122 }
Amith Yamasani12747872015-12-07 14:19:49 -08002123 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002124 return false;
2125 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002126 // We set this to a guest user that is to be removed. This is a temporary state
2127 // where we are allowed to add new Guest users, even if this one is still not
2128 // removed. This user will still show up in getUserInfo() calls.
2129 // If we don't get around to removing this Guest user, it will be purged on next
2130 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002131 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002132 // Mark it as disabled, so that it isn't returned any more when
2133 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002134 userData.info.flags |= UserInfo.FLAG_DISABLED;
2135 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002136 }
2137 } finally {
2138 Binder.restoreCallingIdentity(ident);
2139 }
2140 return true;
2141 }
2142
2143 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002144 * Removes a user and all data directories created for that user. This method should be called
2145 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002146 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002147 */
Amith Yamasani12747872015-12-07 14:19:49 -08002148 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002149 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002150 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002151 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2152 UserManager.DISALLOW_REMOVE_USER, false)) {
2153 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2154 return false;
2155 }
2156
Kenny Guyee58b4f2014-05-23 15:19:53 +01002157 long ident = Binder.clearCallingIdentity();
2158 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002159 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002160 int currentUser = ActivityManager.getCurrentUser();
2161 if (currentUser == userHandle) {
2162 Log.w(LOG_TAG, "Current user cannot be removed");
2163 return false;
2164 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002165 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002166 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002167 userData = mUsers.get(userHandle);
2168 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002169 return false;
2170 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002171
Fyodor Kupolov82402752015-10-28 14:54:51 -07002172 // We remember deleted user IDs to prevent them from being
2173 // reused during the current boot; they can still be reused
2174 // after a reboot.
2175 mRemovingUserIds.put(userHandle, true);
2176 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002177
Kenny Guyee58b4f2014-05-23 15:19:53 +01002178 try {
2179 mAppOpsService.removeUser(userHandle);
2180 } catch (RemoteException e) {
2181 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2182 }
2183 // Set this to a partially created user, so that the user will be purged
2184 // on next startup, in case the runtime stops now before stopping and
2185 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002186 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002187 // Mark it as disabled, so that it isn't returned any more when
2188 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002189 userData.info.flags |= UserInfo.FLAG_DISABLED;
2190 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002191 }
2192
Amith Yamasani12747872015-12-07 14:19:49 -08002193 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2194 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002195 // Send broadcast to notify system that the user removed was a
2196 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002197 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002198 }
2199
2200 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2201 int res;
2202 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002203 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2204 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002205 @Override
2206 public void userStopped(int userId) {
2207 finishRemoveUser(userId);
2208 }
2209 @Override
2210 public void userStopAborted(int userId) {
2211 }
2212 });
2213 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002214 return false;
2215 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002216 return res == ActivityManager.USER_OP_SUCCESS;
2217 } finally {
2218 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002219 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002220 }
2221
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002222 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002223 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002224 // Let other services shutdown any activity and clean up their state before completely
2225 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002226 long ident = Binder.clearCallingIdentity();
2227 try {
2228 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2229 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002230 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2231 android.Manifest.permission.MANAGE_USERS,
2232
2233 new BroadcastReceiver() {
2234 @Override
2235 public void onReceive(Context context, Intent intent) {
2236 if (DBG) {
2237 Slog.i(LOG_TAG,
2238 "USER_REMOVED broadcast sent, cleaning up user data "
2239 + userHandle);
2240 }
2241 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002242 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002243 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002244 // Clean up any ActivityManager state
2245 LocalServices.getService(ActivityManagerInternal.class)
2246 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002247 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002248 }
2249 }.start();
2250 }
2251 },
2252
2253 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002254 } finally {
2255 Binder.restoreCallingIdentity(ident);
2256 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002257 }
2258
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002259 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002260 try {
2261 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2262 } catch (IllegalStateException e) {
2263 // This may be simply because the user was partially created.
2264 Slog.i(LOG_TAG,
2265 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2266 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002267 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002268 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002269
2270 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002271 synchronized (mUsersLock) {
2272 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002273 mIsUserManaged.delete(userHandle);
2274 }
2275 synchronized (mRestrictionsLock) {
2276 mBaseUserRestrictions.remove(userHandle);
2277 mAppliedUserRestrictions.remove(userHandle);
2278 mCachedEffectiveUserRestrictions.remove(userHandle);
2279 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002280 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002281 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002282 synchronized (mPackagesLock) {
2283 writeUserListLP();
2284 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002285 // Remove user file
2286 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2287 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002288 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002289 File userDir = Environment.getUserSystemDirectory(userHandle);
2290 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2291 if (userDir.renameTo(renamedUserDir)) {
2292 removeDirectoryRecursive(renamedUserDir);
2293 } else {
2294 removeDirectoryRecursive(userDir);
2295 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002296 }
2297
Amith Yamasani61f57372012-08-31 12:12:28 -07002298 private void removeDirectoryRecursive(File parent) {
2299 if (parent.isDirectory()) {
2300 String[] files = parent.list();
2301 for (String filename : files) {
2302 File child = new File(parent, filename);
2303 removeDirectoryRecursive(child);
2304 }
2305 }
2306 parent.delete();
2307 }
2308
Kenny Guyf8d3a232014-05-15 16:09:52 +01002309 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002310 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002311 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2312 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002313 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002314 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002315 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002316 }
2317
Amith Yamasani2a003292012-08-14 18:25:45 -07002318 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002319 public Bundle getApplicationRestrictions(String packageName) {
2320 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2321 }
2322
2323 @Override
2324 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002325 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002326 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002327 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002328 }
2329 synchronized (mPackagesLock) {
2330 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002331 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002332 }
2333 }
2334
2335 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002336 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002337 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002338 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002339 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002340 if (restrictions == null || restrictions.isEmpty()) {
2341 cleanAppRestrictionsForPackage(packageName, userId);
2342 } else {
Amith Yamasani23879322016-03-30 16:51:26 -07002343 restrictions.setDefusable(true);
Kenny Guyd21b2182014-07-17 16:38:55 +01002344 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002345 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002346 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002347 }
Robin Lee66e5d962014-04-09 16:44:21 +01002348
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002349 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2350 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2351 changeIntent.setPackage(packageName);
2352 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2353 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002354 }
2355
2356 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002357 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002358 try {
2359 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002360 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002361 } catch (NameNotFoundException nnfe) {
2362 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002363 } finally {
2364 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002365 }
2366 }
2367
Fyodor Kupolov82402752015-10-28 14:54:51 -07002368 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002369 AtomicFile restrictionsFile =
2370 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2371 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002372 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002373 }
2374
2375 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002376 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002377 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002378 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002379 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002380 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002381 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002382
2383 FileInputStream fis = null;
2384 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002385 fis = restrictionsFile.openRead();
2386 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002387 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002388 XmlUtils.nextElement(parser);
2389 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002390 Slog.e(LOG_TAG, "Unable to read restrictions file "
2391 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002392 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002393 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002394 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2395 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002396 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002397 } catch (IOException|XmlPullParserException e) {
2398 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002399 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002400 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002401 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002402 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002403 }
2404
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002405 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2406 XmlPullParser parser) throws XmlPullParserException, IOException {
2407 int type = parser.getEventType();
2408 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2409 String key = parser.getAttributeValue(null, ATTR_KEY);
2410 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2411 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2412 if (multiple != null) {
2413 values.clear();
2414 int count = Integer.parseInt(multiple);
2415 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2416 if (type == XmlPullParser.START_TAG
2417 && parser.getName().equals(TAG_VALUE)) {
2418 values.add(parser.nextText().trim());
2419 count--;
2420 }
2421 }
2422 String [] valueStrings = new String[values.size()];
2423 values.toArray(valueStrings);
2424 restrictions.putStringArray(key, valueStrings);
2425 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2426 restrictions.putBundle(key, readBundleEntry(parser, values));
2427 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2428 final int outerDepth = parser.getDepth();
2429 ArrayList<Bundle> bundleList = new ArrayList<>();
2430 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2431 Bundle childBundle = readBundleEntry(parser, values);
2432 bundleList.add(childBundle);
2433 }
2434 restrictions.putParcelableArray(key,
2435 bundleList.toArray(new Bundle[bundleList.size()]));
2436 } else {
2437 String value = parser.nextText().trim();
2438 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2439 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2440 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2441 restrictions.putInt(key, Integer.parseInt(value));
2442 } else {
2443 restrictions.putString(key, value);
2444 }
2445 }
2446 }
2447 }
2448
2449 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2450 throws IOException, XmlPullParserException {
2451 Bundle childBundle = new Bundle();
2452 final int outerDepth = parser.getDepth();
2453 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2454 readEntry(childBundle, values, parser);
2455 }
2456 return childBundle;
2457 }
2458
Fyodor Kupolov82402752015-10-28 14:54:51 -07002459 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002460 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002461 AtomicFile restrictionsFile = new AtomicFile(
2462 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002463 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002464 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002465 }
2466
2467 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002468 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002469 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002470 try {
2471 fos = restrictionsFile.startWrite();
2472 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2473
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002474 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002475 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002476 serializer.startDocument(null, true);
2477 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2478
2479 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002480 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002481 serializer.endTag(null, TAG_RESTRICTIONS);
2482
2483 serializer.endDocument();
2484 restrictionsFile.finishWrite(fos);
2485 } catch (Exception e) {
2486 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002487 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2488 }
2489 }
2490
2491 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2492 throws IOException {
2493 for (String key : restrictions.keySet()) {
2494 Object value = restrictions.get(key);
2495 serializer.startTag(null, TAG_ENTRY);
2496 serializer.attribute(null, ATTR_KEY, key);
2497
2498 if (value instanceof Boolean) {
2499 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2500 serializer.text(value.toString());
2501 } else if (value instanceof Integer) {
2502 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2503 serializer.text(value.toString());
2504 } else if (value == null || value instanceof String) {
2505 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2506 serializer.text(value != null ? (String) value : "");
2507 } else if (value instanceof Bundle) {
2508 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2509 writeBundle((Bundle) value, serializer);
2510 } else if (value instanceof Parcelable[]) {
2511 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2512 Parcelable[] array = (Parcelable[]) value;
2513 for (Parcelable parcelable : array) {
2514 if (!(parcelable instanceof Bundle)) {
2515 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2516 }
2517 serializer.startTag(null, TAG_ENTRY);
2518 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2519 writeBundle((Bundle) parcelable, serializer);
2520 serializer.endTag(null, TAG_ENTRY);
2521 }
2522 } else {
2523 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2524 String[] values = (String[]) value;
2525 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2526 for (String choice : values) {
2527 serializer.startTag(null, TAG_VALUE);
2528 serializer.text(choice != null ? choice : "");
2529 serializer.endTag(null, TAG_VALUE);
2530 }
2531 }
2532 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002533 }
2534 }
2535
2536 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002537 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002538 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002539 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002540 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002541 }
2542 }
2543
2544 @Override
2545 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002546 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002547 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002548 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002549 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002550 }
2551 // Not found
2552 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002553 }
2554 }
2555
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002556 @Override
2557 public long getUserCreationTime(int userHandle) {
2558 int callingUserId = UserHandle.getCallingUserId();
2559 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002560 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002561 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002562 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002563 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002564 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002565 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002566 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002567 }
2568 }
2569 }
2570 if (userInfo == null) {
2571 throw new SecurityException("userHandle can only be the calling user or a managed "
2572 + "profile associated with this user");
2573 }
2574 return userInfo.creationTime;
2575 }
2576
Amith Yamasani0b285492011-04-14 17:35:23 -07002577 /**
2578 * Caches the list of user ids in an array, adjusting the array size when necessary.
2579 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002580 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002581 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002582 synchronized (mUsersLock) {
2583 final int userSize = mUsers.size();
2584 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002585 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002586 num++;
2587 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002588 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002589 final int[] newUsers = new int[num];
2590 int n = 0;
2591 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002592 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002593 newUsers[n++] = mUsers.keyAt(i);
2594 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002595 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002596 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002597 }
2598 }
2599
2600 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002601 * Prepare storage areas for given user on all mounted devices.
2602 */
2603 private void prepareUserStorage(int userId, int userSerial, int flags) {
2604 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2605 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2606 final String volumeUuid = vol.getFsUuid();
2607 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2608 }
2609 }
2610
2611 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002612 * Called right before a user is started. This gives us a chance to prepare
2613 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002614 */
2615 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002616 final int userSerial = getUserSerialNumber(userId);
2617 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2618 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002619
2620 if (userId != UserHandle.USER_SYSTEM) {
2621 synchronized (mRestrictionsLock) {
2622 applyUserRestrictionsLR(userId);
2623 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002624 }
2625 }
2626
2627 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002628 * Called right before a user is unlocked. This gives us a chance to prepare
2629 * app storage.
2630 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002631 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002632 final int userSerial = getUserSerialNumber(userId);
2633 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2634 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002635 }
2636
2637 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002638 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002639 * @param userId the user that was just foregrounded
2640 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002641 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002642 UserData userData = getUserDataNoChecks(userId);
2643 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002644 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2645 return;
2646 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002647
2648 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002649 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002650 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002651 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002652 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2653 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002654 }
2655
2656 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002657 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002658 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2659 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002660 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002661 private int getNextAvailableId() {
2662 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002663 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002664 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002665 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002666 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002667 }
2668 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002669 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002670 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002671 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002672 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002673
Amith Yamasanifc95e702013-09-26 13:20:17 -07002674 private String packageToRestrictionsFileName(String packageName) {
2675 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2676 }
2677
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002678 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002679 * Enforce that serial number stored in user directory inode matches the
2680 * given expected value. Gracefully sets the serial number if currently
2681 * undefined.
2682 *
2683 * @throws IOException when problem extracting serial number, or serial
2684 * number is mismatched.
2685 */
2686 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2687 final int foundSerial = getSerialNumber(file);
2688 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2689
2690 if (foundSerial == -1) {
2691 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2692 try {
2693 setSerialNumber(file, serialNumber);
2694 } catch (IOException e) {
2695 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2696 }
2697
2698 } else if (foundSerial != serialNumber) {
2699 throw new IOException("Found serial number " + foundSerial
2700 + " doesn't match expected " + serialNumber);
2701 }
2702 }
2703
2704 /**
2705 * Set serial number stored in user directory inode.
2706 *
2707 * @throws IOException if serial number was already set
2708 */
2709 private static void setSerialNumber(File file, int serialNumber)
2710 throws IOException {
2711 try {
2712 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2713 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2714 } catch (ErrnoException e) {
2715 throw e.rethrowAsIOException();
2716 }
2717 }
2718
2719 /**
2720 * Return serial number stored in user directory inode.
2721 *
2722 * @return parsed serial number, or -1 if not set
2723 */
2724 private static int getSerialNumber(File file) throws IOException {
2725 try {
2726 final byte[] buf = new byte[256];
2727 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2728 final String serial = new String(buf, 0, len);
2729 try {
2730 return Integer.parseInt(serial);
2731 } catch (NumberFormatException e) {
2732 throw new IOException("Bad serial number: " + serial);
2733 }
2734 } catch (ErrnoException e) {
2735 if (e.errno == OsConstants.ENODATA) {
2736 return -1;
2737 } else {
2738 throw e.rethrowAsIOException();
2739 }
2740 }
2741 }
2742
Amith Yamasani920ace02012-09-20 22:15:37 -07002743 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002744 public void setSeedAccountData(int userId, String accountName, String accountType,
2745 PersistableBundle accountOptions, boolean persist) {
2746 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2747 synchronized (mPackagesLock) {
2748 final UserData userData;
2749 synchronized (mUsersLock) {
2750 userData = getUserDataLU(userId);
2751 if (userData == null) {
2752 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2753 return;
2754 }
2755 userData.seedAccountName = accountName;
2756 userData.seedAccountType = accountType;
2757 userData.seedAccountOptions = accountOptions;
2758 userData.persistSeedData = persist;
2759 }
2760 if (persist) {
2761 writeUserLP(userData);
2762 }
2763 }
2764 }
2765
2766 @Override
2767 public String getSeedAccountName() throws RemoteException {
2768 checkManageUsersPermission("Cannot get seed account information");
2769 synchronized (mUsersLock) {
2770 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2771 return userData.seedAccountName;
2772 }
2773 }
2774
2775 @Override
2776 public String getSeedAccountType() throws RemoteException {
2777 checkManageUsersPermission("Cannot get seed account information");
2778 synchronized (mUsersLock) {
2779 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2780 return userData.seedAccountType;
2781 }
2782 }
2783
2784 @Override
2785 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2786 checkManageUsersPermission("Cannot get seed account information");
2787 synchronized (mUsersLock) {
2788 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2789 return userData.seedAccountOptions;
2790 }
2791 }
2792
2793 @Override
2794 public void clearSeedAccountData() throws RemoteException {
2795 checkManageUsersPermission("Cannot clear seed account information");
2796 synchronized (mPackagesLock) {
2797 UserData userData;
2798 synchronized (mUsersLock) {
2799 userData = getUserDataLU(UserHandle.getCallingUserId());
2800 if (userData == null) return;
2801 userData.clearSeedAccountData();
2802 }
2803 writeUserLP(userData);
2804 }
2805 }
2806
2807 @Override
2808 public boolean someUserHasSeedAccount(String accountName, String accountType)
2809 throws RemoteException {
2810 checkManageUsersPermission("Cannot check seed account information");
2811 synchronized (mUsersLock) {
2812 final int userSize = mUsers.size();
2813 for (int i = 0; i < userSize; i++) {
2814 final UserData data = mUsers.valueAt(i);
2815 if (data.info.isInitialized()) continue;
2816 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2817 continue;
2818 }
2819 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2820 continue;
2821 }
2822 return true;
2823 }
2824 }
2825 return false;
2826 }
2827
2828 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002829 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2830 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2831 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2832 }
2833
2834 int onShellCommand(Shell shell, String cmd) {
2835 if (cmd == null) {
2836 return shell.handleDefaultCommands(cmd);
2837 }
2838
2839 final PrintWriter pw = shell.getOutPrintWriter();
2840 try {
2841 switch(cmd) {
2842 case "list":
2843 return runList(pw);
2844 }
2845 } catch (RemoteException e) {
2846 pw.println("Remote exception: " + e);
2847 }
2848 return -1;
2849 }
2850
2851 private int runList(PrintWriter pw) throws RemoteException {
2852 final IActivityManager am = ActivityManagerNative.getDefault();
2853 final List<UserInfo> users = getUsers(false);
2854 if (users == null) {
2855 pw.println("Error: couldn't get users");
2856 return 1;
2857 } else {
2858 pw.println("Users:");
2859 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002860 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002861 pw.println("\t" + users.get(i).toString() + running);
2862 }
2863 return 0;
2864 }
2865 }
2866
2867 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002868 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2869 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2870 != PackageManager.PERMISSION_GRANTED) {
2871 pw.println("Permission Denial: can't dump UserManager from from pid="
2872 + Binder.getCallingPid()
2873 + ", uid=" + Binder.getCallingUid()
2874 + " without permission "
2875 + android.Manifest.permission.DUMP);
2876 return;
2877 }
2878
2879 long now = System.currentTimeMillis();
2880 StringBuilder sb = new StringBuilder();
2881 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002882 synchronized (mUsersLock) {
2883 pw.println("Users:");
2884 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002885 UserData userData = mUsers.valueAt(i);
2886 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002887 continue;
2888 }
Amith Yamasani12747872015-12-07 14:19:49 -08002889 UserInfo userInfo = userData.info;
2890 final int userId = userInfo.id;
2891 pw.print(" "); pw.print(userInfo);
2892 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002893 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002894 pw.print(" <removing> ");
2895 }
Amith Yamasani12747872015-12-07 14:19:49 -08002896 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002897 pw.print(" <partial>");
2898 }
2899 pw.println();
2900 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002901 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002902 pw.println("<unknown>");
2903 } else {
2904 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002905 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002906 sb.append(" ago");
2907 pw.println(sb);
2908 }
2909 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002910 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002911 pw.println("<unknown>");
2912 } else {
2913 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002914 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002915 sb.append(" ago");
2916 pw.println(sb);
2917 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002918 pw.print(" Last logged in fingerprint: ");
2919 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08002920 pw.print(" Has profile owner: ");
2921 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002922 pw.println(" Restrictions:");
2923 synchronized (mRestrictionsLock) {
2924 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002925 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002926 pw.println(" Device policy local restrictions:");
2927 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002928 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002929 pw.println(" Effective restrictions:");
2930 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002931 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002932 }
Amith Yamasani12747872015-12-07 14:19:49 -08002933
2934 if (userData.account != null) {
2935 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002936 pw.println();
2937 }
Amith Yamasani12747872015-12-07 14:19:49 -08002938
2939 if (userData.seedAccountName != null) {
2940 pw.print(" Seed account name: " + userData.seedAccountName);
2941 pw.println();
2942 if (userData.seedAccountType != null) {
2943 pw.print(" account type: " + userData.seedAccountType);
2944 pw.println();
2945 }
2946 if (userData.seedAccountOptions != null) {
2947 pw.print(" account options exist");
2948 pw.println();
2949 }
2950 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002951 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002952 }
Amith Yamasani12747872015-12-07 14:19:49 -08002953 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002954 pw.println(" Device policy global restrictions:");
2955 synchronized (mRestrictionsLock) {
2956 UserRestrictionsUtils
2957 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2958 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002959 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002960 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002961 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002962 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002963 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002964 synchronized (mUsersLock) {
2965 pw.println();
2966 pw.println(" Device managed: " + mIsDeviceManaged);
2967 }
Amith Yamasani12747872015-12-07 14:19:49 -08002968 // Dump some capabilities
2969 pw.println();
2970 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2971 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002972 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2973 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002974 }
2975 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002976
2977 final class MainHandler extends Handler {
2978
2979 @Override
2980 public void handleMessage(Message msg) {
2981 switch (msg.what) {
2982 case WRITE_USER_MSG:
2983 removeMessages(WRITE_USER_MSG, msg.obj);
2984 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002985 int userId = ((UserData) msg.obj).info.id;
2986 UserData userData = getUserDataNoChecks(userId);
2987 if (userData != null) {
2988 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002989 }
2990 }
2991 }
2992 }
2993 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002994
2995 /**
2996 * @param userId
2997 * @return whether the user has been initialized yet
2998 */
2999 boolean isInitialized(int userId) {
3000 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3001 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003002
3003 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003004 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003005 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3006 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003007 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003008 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003009 }
3010
3011 @Override
3012 public Bundle getBaseUserRestrictions(int userId) {
3013 synchronized (mRestrictionsLock) {
3014 return mBaseUserRestrictions.get(userId);
3015 }
3016 }
3017
3018 @Override
3019 public void setBaseUserRestrictionsByDpmsForMigration(
3020 int userId, Bundle baseRestrictions) {
3021 synchronized (mRestrictionsLock) {
3022 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003023 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003024 }
3025
Amith Yamasani12747872015-12-07 14:19:49 -08003026 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003027 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003028 if (userData != null) {
3029 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003030 } else {
3031 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3032 }
3033 }
3034 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003035
3036 @Override
3037 public boolean getUserRestriction(int userId, String key) {
3038 return getUserRestrictions(userId).getBoolean(key);
3039 }
3040
3041 @Override
3042 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3043 synchronized (mUserRestrictionsListeners) {
3044 mUserRestrictionsListeners.add(listener);
3045 }
3046 }
3047
3048 @Override
3049 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3050 synchronized (mUserRestrictionsListeners) {
3051 mUserRestrictionsListeners.remove(listener);
3052 }
3053 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003054
3055 @Override
3056 public void setDeviceManaged(boolean isManaged) {
3057 synchronized (mUsersLock) {
3058 mIsDeviceManaged = isManaged;
3059 }
3060 }
3061
3062 @Override
3063 public void setUserManaged(int userId, boolean isManaged) {
3064 synchronized (mUsersLock) {
3065 mIsUserManaged.put(userId, isManaged);
3066 }
3067 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003068
3069 @Override
3070 public void setUserIcon(int userId, Bitmap bitmap) {
3071 long ident = Binder.clearCallingIdentity();
3072 try {
3073 synchronized (mPackagesLock) {
3074 UserData userData = getUserDataNoChecks(userId);
3075 if (userData == null || userData.info.partial) {
3076 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3077 return;
3078 }
3079 writeBitmapLP(userData.info, bitmap);
3080 writeUserLP(userData);
3081 }
3082 sendUserInfoChangedBroadcast(userId);
3083 } finally {
3084 Binder.restoreCallingIdentity(ident);
3085 }
3086 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003087
3088 @Override
3089 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3090 synchronized (mUsersLock) {
3091 mForceEphemeralUsers = forceEphemeralUsers;
3092 }
3093 }
3094
3095 @Override
3096 public void removeAllUsers() {
3097 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3098 // Remove the non-system users straight away.
3099 removeNonSystemUsers();
3100 } else {
3101 // Switch to the system user first and then remove the other users.
3102 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3103 @Override
3104 public void onReceive(Context context, Intent intent) {
3105 int userId =
3106 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3107 if (userId != UserHandle.USER_SYSTEM) {
3108 return;
3109 }
3110 mContext.unregisterReceiver(this);
3111 removeNonSystemUsers();
3112 }
3113 };
3114 IntentFilter userSwitchedFilter = new IntentFilter();
3115 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3116 mContext.registerReceiver(
3117 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3118
3119 // Switch to the system user.
3120 ActivityManager am =
3121 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3122 am.switchUser(UserHandle.USER_SYSTEM);
3123 }
3124 }
phweisse9c44062016-02-10 12:57:38 +01003125
3126 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003127 public void onEphemeralUserStop(int userId) {
3128 synchronized (mUsersLock) {
3129 UserInfo userInfo = getUserInfoLU(userId);
3130 if (userInfo != null && userInfo.isEphemeral()) {
3131 // Do not allow switching back to the ephemeral user again as the user is going
3132 // to be deleted.
3133 userInfo.flags |= UserInfo.FLAG_DISABLED;
3134 if (userInfo.isGuest()) {
3135 // Indicate that the guest will be deleted after it stops.
3136 userInfo.guestToRemove = true;
3137 }
3138 }
3139 }
3140 }
3141
3142 @Override
phweisse9c44062016-02-10 12:57:38 +01003143 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3144 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3145 // Keep this in sync with UserManager.createUser
3146 if (user != null && !user.isAdmin()) {
3147 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3148 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3149 }
3150 return user;
3151 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003152 }
3153
3154 /* Remove all the users except of the system one. */
3155 private void removeNonSystemUsers() {
3156 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3157 synchronized (mUsersLock) {
3158 final int userSize = mUsers.size();
3159 for (int i = 0; i < userSize; i++) {
3160 UserInfo ui = mUsers.valueAt(i).info;
3161 if (ui.id != UserHandle.USER_SYSTEM) {
3162 usersToRemove.add(ui);
3163 }
3164 }
3165 }
3166 for (UserInfo ui: usersToRemove) {
3167 removeUser(ui.id);
3168 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003169 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003170
3171 private class Shell extends ShellCommand {
3172 @Override
3173 public int onCommand(String cmd) {
3174 return onShellCommand(this, cmd);
3175 }
3176
3177 @Override
3178 public void onHelp() {
3179 final PrintWriter pw = getOutPrintWriter();
3180 pw.println("User manager (user) commands:");
3181 pw.println(" help");
3182 pw.println(" Print this help text.");
3183 pw.println("");
3184 pw.println(" list");
3185 pw.println(" Prints all users on the system.");
3186 }
3187 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003188
3189 private static void debug(String message) {
3190 Log.d(LOG_TAG, message +
3191 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3192 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003193}