blob: d5ed04a94f378a0ac522025aadd1295b193a93af [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010031import android.content.IntentFilter;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070032import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070033import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080034import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010036import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070037import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070038import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080039import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080040import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.os.Environment;
42import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080043import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080044import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080046import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010047import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070048import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080049import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070050import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070051import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070052import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040053import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070054import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070055import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070056import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070057import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080058import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010059import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070060import android.os.storage.VolumeInfo;
61import android.system.ErrnoException;
62import android.system.Os;
63import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070064import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070065import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import android.util.Slog;
67import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080068import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070069import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070070import android.util.Xml;
71
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070073import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040074import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080075import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080076import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070077import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070078import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000079import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070080import com.android.server.LocalServices;
Jeff Sharkey47f71082016-02-01 17:03:54 -070081
82import libcore.io.IoUtils;
83import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080084
85import org.xmlpull.v1.XmlPullParser;
86import org.xmlpull.v1.XmlPullParserException;
87import org.xmlpull.v1.XmlSerializer;
88
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import java.io.BufferedOutputStream;
90import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070091import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070093import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070094import java.io.FileOutputStream;
95import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070096import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010097import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098import java.util.ArrayList;
99import java.util.List;
100
Makoto Onuki068c54a2015-10-13 14:34:03 -0700101/**
102 * Service for {@link UserManager}.
103 *
104 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700105 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800106 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700107 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
108 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
109 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700110 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700111public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700112 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800113 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800114 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700115
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800117 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700118 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700119 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700121 private static final String ATTR_CREATION_TIME = "created";
122 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700123 private static final String ATTR_SERIAL_NO = "serialNumber";
124 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700125 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700126 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700127 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100128 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700129 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800130 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
131 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530132 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700133 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800135 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800136 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800137 private static final String TAG_ENTRY = "entry";
138 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800139 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800140 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700141 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800142 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700143
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700144 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
145 private static final String ATTR_TYPE_STRING = "s";
146 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700147 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700148 private static final String ATTR_TYPE_BUNDLE = "B";
149 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700150
Amith Yamasani0b285492011-04-14 17:35:23 -0700151 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700152 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700153 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100154 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700155
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800156 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700157 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800158
Amith Yamasani634cf312012-10-04 17:34:21 -0700159 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700160 // We need to keep process uid within Integer.MAX_VALUE.
161 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700162
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700163 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700164
Amith Yamasani920ace02012-09-20 22:15:37 -0700165 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
166
Nicolas Prevotb8186812015-08-06 15:00:03 +0100167 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700168 // without first making sure that the rest of the framework is prepared for it.
169 private static final int MAX_MANAGED_PROFILES = 1;
170
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800171 static final int WRITE_USER_MSG = 1;
172 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530173
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700174 private static final String XATTR_SERIAL = "user.serial";
175
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800176 // Tron counters
177 private static final String TRON_GUEST_CREATED = "users_guest_created";
178 private static final String TRON_USER_CREATED = "users_user_created";
179
Dianne Hackborn4428e172012-08-24 17:43:05 -0700180 private final Context mContext;
181 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700182 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700183 // Short-term lock for internal state, when interaction/sync with PM is not required
184 private final Object mUsersLock = new Object();
185 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700186
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800187 private final Handler mHandler;
188
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700189 private final File mUsersDir;
190 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800192 private static final IBinder mUserRestriconToken = new Binder();
193
Makoto Onuki068c54a2015-10-13 14:34:03 -0700194 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800195 * User-related information that is used for persisting to flash. Only UserInfo is
196 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800197 */
Amith Yamasani12747872015-12-07 14:19:49 -0800198 private static class UserData {
199 // Basic user information and properties
200 UserInfo info;
201 // Account name used when there is a strong association between a user and an account
202 String account;
203 // Account information for seeding into a newly created user. This could also be
204 // used for login validation for an existing user, for updating their credentials.
205 // In the latter case, data may not need to be persisted as it is only valid for the
206 // current login session.
207 String seedAccountName;
208 String seedAccountType;
209 PersistableBundle seedAccountOptions;
210 // Whether to perist the seed account information to be available after a boot
211 boolean persistSeedData;
212
213 void clearSeedAccountData() {
214 seedAccountName = null;
215 seedAccountType = null;
216 seedAccountOptions = null;
217 persistSeedData = false;
218 }
219 }
220
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800221 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800222 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800223
224 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700225 * User restrictions set via UserManager. This doesn't include restrictions set by
226 * device owner / profile owners.
227 *
228 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
229 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
230 * maybe shared between {@link #mBaseUserRestrictions} and
231 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
232 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700233 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700234 */
235 @GuardedBy("mRestrictionsLock")
236 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
237
238 /**
239 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
240 * with device / profile owner restrictions. We'll initialize it lazily; use
241 * {@link #getEffectiveUserRestrictions} to access it.
242 *
243 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
244 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
245 * maybe shared between {@link #mBaseUserRestrictions} and
246 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
247 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700248 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700249 */
250 @GuardedBy("mRestrictionsLock")
251 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
252
Makoto Onuki4f160732015-10-27 17:15:38 -0700253 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800254 * User restrictions that have already been applied in
255 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
256 * that have changed since the last
257 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700258 */
259 @GuardedBy("mRestrictionsLock")
260 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
261
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800262 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800263 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
264 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800265 */
266 @GuardedBy("mRestrictionsLock")
267 private Bundle mDevicePolicyGlobalUserRestrictions;
268
269 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800270 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
271 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800272 */
273 @GuardedBy("mRestrictionsLock")
274 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
275
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800276 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530277 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800278
279 /**
280 * Set of user IDs being actively removed. Removed IDs linger in this set
281 * for several seconds to work around a VFS caching issue.
282 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700283 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800284 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700285
Fyodor Kupolov82402752015-10-28 14:54:51 -0700286 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700287 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800288 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700289 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700290 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700291
Jason Monk62062992014-05-06 09:55:28 -0400292 private IAppOpsService mAppOpsService;
293
Makoto Onuki068c54a2015-10-13 14:34:03 -0700294 private final LocalService mLocalService;
295
Makoto Onukie7927da2015-11-25 10:05:17 -0800296 @GuardedBy("mUsersLock")
297 private boolean mIsDeviceManaged;
298
299 @GuardedBy("mUsersLock")
300 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
301
Makoto Onukid45a4a22015-11-02 17:17:38 -0800302 @GuardedBy("mUserRestrictionsListeners")
303 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
304 new ArrayList<>();
305
Clara Bayarria1771112015-12-18 16:29:18 +0000306 private final LockPatternUtils mLockPatternUtils;
307
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100308 /**
309 * Whether all users should be created ephemeral.
310 */
311 @GuardedBy("mUsersLock")
312 private boolean mForceEphemeralUsers;
313
Amith Yamasani258848d2012-08-10 17:06:33 -0700314 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700315
Dianne Hackborn4428e172012-08-24 17:43:05 -0700316 public static UserManagerService getInstance() {
317 synchronized (UserManagerService.class) {
318 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700319 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700320 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700321
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800322 @VisibleForTesting
323 UserManagerService(File dataDir) {
324 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700325 }
326
Dianne Hackborn4428e172012-08-24 17:43:05 -0700327 /**
328 * Called by package manager to create the service. This is closely
329 * associated with the package manager, and the given lock is the
330 * package manager's own lock.
331 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800332 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
333 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700334 }
335
Dianne Hackborn4428e172012-08-24 17:43:05 -0700336 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800337 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700338 mContext = context;
339 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700340 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800341 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800342 synchronized (mPackagesLock) {
343 mUsersDir = new File(dataDir, USER_INFO_DIR);
344 mUsersDir.mkdirs();
345 // Make zeroth user directory, for services to migrate their files to that location
346 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
347 userZeroDir.mkdirs();
348 FileUtils.setPermissions(mUsersDir.toString(),
349 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
350 -1, -1);
351 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
352 initDefaultGuestRestrictions();
353 readUserListLP();
354 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700355 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700356 mLocalService = new LocalService();
357 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000358 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700359 }
360
361 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100362 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800363 ArrayList<UserInfo> partials = new ArrayList<>();
364 synchronized (mUsersLock) {
365 final int userSize = mUsers.size();
366 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800367 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100368 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800369 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700370 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700371 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700372 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800373 final int partialsSize = partials.size();
374 for (int i = 0; i < partialsSize; i++) {
375 UserInfo ui = partials.get(i);
376 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
377 + " (name=" + ui.name + ")");
378 removeUserState(ui.id);
379 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800380
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700381 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800382
Jason Monk62062992014-05-06 09:55:28 -0400383 mAppOpsService = IAppOpsService.Stub.asInterface(
384 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800385
386 synchronized (mRestrictionsLock) {
387 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400388 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700389 }
390
391 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800392 public String getUserAccount(int userId) {
393 checkManageUserAndAcrossUsersFullPermission("get user account");
394 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800395 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800396 }
397 }
398
399 @Override
400 public void setUserAccount(int userId, String accountName) {
401 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800402 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800403 synchronized (mPackagesLock) {
404 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800405 final UserData userData = mUsers.get(userId);
406 if (userData == null) {
407 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
408 return;
409 }
410 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800411 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800412 userData.account = accountName;
413 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800414 }
415 }
416
417 if (userToUpdate != null) {
418 writeUserLP(userToUpdate);
419 }
420 }
421 }
422
423 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700424 public UserInfo getPrimaryUser() {
425 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700426 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700427 final int userSize = mUsers.size();
428 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800429 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800430 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700431 return ui;
432 }
433 }
434 }
435 return null;
436 }
437
438 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700439 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700440 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700441 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700442 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700443 final int userSize = mUsers.size();
444 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800445 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700446 if (ui.partial) {
447 continue;
448 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800449 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700450 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700451 }
Amith Yamasani13593602012-03-22 16:16:17 -0700452 }
453 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700454 }
Amith Yamasani13593602012-03-22 16:16:17 -0700455 }
456
Amith Yamasani258848d2012-08-10 17:06:33 -0700457 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100458 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800459 if (userId != UserHandle.getCallingUserId()) {
460 checkManageUsersPermission("getting profiles related to user " + userId);
461 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700462 final long ident = Binder.clearCallingIdentity();
463 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700464 synchronized (mUsersLock) {
465 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100466 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700467 } finally {
468 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000469 }
470 }
471
Amith Yamasanibe465322014-04-24 13:45:17 -0700472 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700473 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
474 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700475 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700476 if (user == null) {
477 // Probably a dying user
478 return users;
479 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700480 final int userSize = mUsers.size();
481 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800482 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700483 if (!isProfileOf(user, profile)) {
484 continue;
485 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100486 if (enabledOnly && !profile.isEnabled()) {
487 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700488 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700489 if (mRemovingUserIds.get(profile.id)) {
490 continue;
491 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700492 users.add(profile);
493 }
494 return users;
495 }
496
Jessica Hummelbe81c802014-04-22 15:49:22 +0100497 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700498 public int getCredentialOwnerProfile(int userHandle) {
499 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000500 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700501 synchronized (mUsersLock) {
502 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700503 if (profileParent != null) {
504 return profileParent.id;
505 }
506 }
507 }
508
509 return userHandle;
510 }
511
512 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700513 public boolean isSameProfileGroup(int userId, int otherUserId) {
514 if (userId == otherUserId) return true;
515 checkManageUsersPermission("check if in the same profile group");
516 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700517 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700518 }
519 }
520
Fyodor Kupolov82402752015-10-28 14:54:51 -0700521 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
522 synchronized (mUsersLock) {
523 UserInfo userInfo = getUserInfoLU(userId);
524 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
525 return false;
526 }
527 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
528 if (otherUserInfo == null
529 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
530 return false;
531 }
532 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700533 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700534 }
535
536 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100537 public UserInfo getProfileParent(int userHandle) {
538 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700539 synchronized (mUsersLock) {
540 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700541 }
542 }
543
Fyodor Kupolov82402752015-10-28 14:54:51 -0700544 private UserInfo getProfileParentLU(int userHandle) {
545 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700546 if (profile == null) {
547 return null;
548 }
549 int parentUserId = profile.profileGroupId;
550 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
551 return null;
552 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700553 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100554 }
555 }
556
Fyodor Kupolov82402752015-10-28 14:54:51 -0700557 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100558 return user.id == profile.id ||
559 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
560 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000561 }
562
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000563 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000564 UserHandle parentHandle, boolean inQuietMode) {
565 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
566 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
567 intent.putExtra(Intent.EXTRA_USER, profileHandle);
568 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000569 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000570 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000571 }
572
573 @Override
574 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
575 checkManageUsersPermission("silence profile");
576 boolean changed = false;
577 UserInfo profile, parent;
578 synchronized (mPackagesLock) {
579 synchronized (mUsersLock) {
580 profile = getUserInfoLU(userHandle);
581 parent = getProfileParentLU(userHandle);
582
583 }
584 if (profile == null || !profile.isManagedProfile()) {
585 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
586 }
587 if (profile.isQuietModeEnabled() != enableQuietMode) {
588 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800589 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000590 changed = true;
591 }
592 }
593 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000594 long identity = Binder.clearCallingIdentity();
595 try {
596 if (enableQuietMode) {
597 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
598 } else {
599 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
600 }
601 } catch (RemoteException e) {
602 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
603 } finally {
604 Binder.restoreCallingIdentity(identity);
605 }
606
607 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
608 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000609 }
610 }
611
612 @Override
613 public boolean isQuietModeEnabled(int userHandle) {
614 synchronized (mPackagesLock) {
615 UserInfo info;
616 synchronized (mUsersLock) {
617 info = getUserInfoLU(userHandle);
618 }
619 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000620 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000621 }
622 return info.isQuietModeEnabled();
623 }
624 }
625
Kenny Guya52dc3e2014-02-11 15:33:14 +0000626 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100627 public void setUserEnabled(int userId) {
628 checkManageUsersPermission("enable user");
629 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700630 UserInfo info;
631 synchronized (mUsersLock) {
632 info = getUserInfoLU(userId);
633 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100634 if (info != null && !info.isEnabled()) {
635 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800636 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100637 }
638 }
639 }
640
641 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700642 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700643 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700644 synchronized (mUsersLock) {
645 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700646 }
647 }
648
Amith Yamasani71e6c692013-03-24 17:39:28 -0700649 @Override
650 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700651 synchronized (mUsersLock) {
652 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700653 }
654 }
655
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700656 @Override
657 public boolean canHaveRestrictedProfile(int userId) {
658 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700659 synchronized (mUsersLock) {
660 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700661 if (userInfo == null || !userInfo.canHaveProfile()) {
662 return false;
663 }
664 if (!userInfo.isAdmin()) {
665 return false;
666 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800667 // restricted profile can be created if there is no DO set and the admin user has no PO;
668 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700669 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700670 }
671
Amith Yamasani195263742012-08-21 15:40:12 -0700672 /*
673 * Should be locked on mUsers before calling this.
674 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700675 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800676 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700677 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800678 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700679 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
680 return null;
681 }
Amith Yamasani12747872015-12-07 14:19:49 -0800682 return userData != null ? userData.info : null;
683 }
684
685 private UserData getUserDataLU(int userId) {
686 final UserData userData = mUsers.get(userId);
687 // If it is partial and not in the process of being removed, return as unknown user.
688 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
689 return null;
690 }
691 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700692 }
693
Fyodor Kupolov82402752015-10-28 14:54:51 -0700694 /**
695 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
696 * <p>No permissions checking or any addition checks are made</p>
697 */
698 private UserInfo getUserInfoNoChecks(int userId) {
699 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800700 final UserData userData = mUsers.get(userId);
701 return userData != null ? userData.info : null;
702 }
703 }
704
705 /**
706 * Obtains {@link #mUsersLock} and return UserData from mUsers.
707 * <p>No permissions checking or any addition checks are made</p>
708 */
709 private UserData getUserDataNoChecks(int userId) {
710 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700711 return mUsers.get(userId);
712 }
713 }
714
Amith Yamasani236b2b52015-08-18 14:32:14 -0700715 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700716 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700717 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700718 }
719
Amith Yamasani258848d2012-08-10 17:06:33 -0700720 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700721 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700722 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700723 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700724 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800725 UserData userData = getUserDataNoChecks(userId);
726 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700727 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
728 return;
729 }
Amith Yamasani12747872015-12-07 14:19:49 -0800730 if (name != null && !name.equals(userData.info.name)) {
731 userData.info.name = name;
732 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700733 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700734 }
735 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700736 if (changed) {
737 sendUserInfoChangedBroadcast(userId);
738 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700739 }
740
Amith Yamasani258848d2012-08-10 17:06:33 -0700741 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700742 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700743 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100744 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
745 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
746 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700747 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100748 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700749 }
750
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100751
752
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700753 private void sendUserInfoChangedBroadcast(int userId) {
754 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
755 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
756 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700757 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700758 }
759
Amith Yamasani258848d2012-08-10 17:06:33 -0700760 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100761 public ParcelFileDescriptor getUserIcon(int userId) {
762 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700763 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700764 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700765 if (info == null || info.partial) {
766 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
767 return null;
768 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700769 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100770 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
771 || callingGroupId != info.profileGroupId) {
772 checkManageUsersPermission("get the icon of a user who is not related");
773 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700774 if (info.iconPath == null) {
775 return null;
776 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100777 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700778 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100779
780 try {
781 return ParcelFileDescriptor.open(
782 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
783 } catch (FileNotFoundException e) {
784 Log.e(LOG_TAG, "Couldn't find icon file", e);
785 }
786 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700787 }
788
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700789 public void makeInitialized(int userId) {
790 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800791 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800792 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800793 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800794 userData = mUsers.get(userId);
795 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700796 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800797 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700798 }
Amith Yamasani12747872015-12-07 14:19:49 -0800799 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
800 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800801 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700802 }
803 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800804 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800805 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800806 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700807 }
808
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700809 /**
810 * If default guest restrictions haven't been initialized yet, add the basic
811 * restrictions.
812 */
813 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800814 synchronized (mGuestRestrictions) {
815 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800816 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800817 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
818 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
819 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700820 }
821 }
822
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800823 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530824 public Bundle getDefaultGuestRestrictions() {
825 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800826 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530827 return new Bundle(mGuestRestrictions);
828 }
829 }
830
831 @Override
832 public void setDefaultGuestRestrictions(Bundle restrictions) {
833 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800834 synchronized (mGuestRestrictions) {
835 mGuestRestrictions.clear();
836 mGuestRestrictions.putAll(restrictions);
837 }
838 synchronized (mPackagesLock) {
839 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530840 }
841 }
842
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800843 /**
844 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
845 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800846 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800847 @Nullable Bundle global) {
848 Preconditions.checkNotNull(local);
849 boolean globalChanged = false;
850 boolean localChanged;
851 synchronized (mRestrictionsLock) {
852 if (global != null) {
853 // Update global.
854 globalChanged = !UserRestrictionsUtils.areEqual(
855 mDevicePolicyGlobalUserRestrictions, global);
856 if (globalChanged) {
857 mDevicePolicyGlobalUserRestrictions = global;
858 }
859 }
860 {
861 // Update local.
862 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
863 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
864 if (localChanged) {
865 mDevicePolicyLocalUserRestrictions.put(userId, local);
866 }
867 }
868 }
869 if (DBG) {
870 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
871 + " global=" + global + (globalChanged ? " (changed)" : "")
872 + " local=" + local + (localChanged ? " (changed)" : "")
873 );
874 }
875 // Don't call them within the mRestrictionsLock.
876 synchronized (mPackagesLock) {
877 if (globalChanged) {
878 writeUserListLP();
879 }
880 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800881 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800882 }
883 }
884
885 synchronized (mRestrictionsLock) {
886 if (globalChanged) {
887 applyUserRestrictionsForAllUsersLR();
888 } else if (localChanged) {
889 applyUserRestrictionsLR(userId);
890 }
891 }
892 }
893
Makoto Onuki068c54a2015-10-13 14:34:03 -0700894 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700895 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800896 final Bundle baseRestrictions =
897 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
898 final Bundle global = mDevicePolicyGlobalUserRestrictions;
899 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700900
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800901 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
902 // Common case first.
903 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700904 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800905 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
906 UserRestrictionsUtils.merge(effective, global);
907 UserRestrictionsUtils.merge(effective, local);
908
Makoto Onuki068c54a2015-10-13 14:34:03 -0700909 return effective;
910 }
911
912 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700913 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700914 if (DBG) {
915 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
916 }
917 mCachedEffectiveUserRestrictions.remove(userId);
918 }
919
920 private Bundle getEffectiveUserRestrictions(int userId) {
921 synchronized (mRestrictionsLock) {
922 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
923 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700924 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700925 mCachedEffectiveUserRestrictions.put(userId, restrictions);
926 }
927 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700928 }
929 }
930
Makoto Onuki068c54a2015-10-13 14:34:03 -0700931 /** @return a specific user restriction that's in effect currently. */
932 @Override
933 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800934 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
935 return false;
936 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700937 Bundle restrictions = getEffectiveUserRestrictions(userId);
938 return restrictions != null && restrictions.getBoolean(restrictionKey);
939 }
940
941 /**
942 * @return UserRestrictions that are in effect currently. This always returns a new
943 * {@link Bundle}.
944 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700945 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800946 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800947 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800948 }
949
950 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000951 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
952 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800953 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
954 return false;
955 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000956 synchronized (mRestrictionsLock) {
957 Bundle bundle = mBaseUserRestrictions.get(userId);
958 return (bundle != null && bundle.getBoolean(restrictionKey, false));
959 }
960 }
961
962 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700963 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700964 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800965 if (!UserRestrictionsUtils.isValidRestriction(key)) {
966 return;
967 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700968 synchronized (mRestrictionsLock) {
969 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
970 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800971 final Bundle newRestrictions = UserRestrictionsUtils.clone(
972 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700973 newRestrictions.putBoolean(key, value);
974
Fyodor Kupolov82402752015-10-28 14:54:51 -0700975 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700976 }
977 }
978
Makoto Onuki068c54a2015-10-13 14:34:03 -0700979 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800980 * Optionally updating user restrictions, calculate the effective user restrictions and also
981 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700982 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800983 * @param newRestrictions User restrictions to set.
984 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700985 * @param userId target user ID.
986 */
987 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700988 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700989 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800990
991 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
992 mAppliedUserRestrictions.get(userId));
993
994 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700995 if (newRestrictions != null) {
996 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800997 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
998
999 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001000 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1001 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001002
1003 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1004 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001005 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001006 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001007 }
1008
Fyodor Kupolov82402752015-10-28 14:54:51 -07001009 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001010
Makoto Onuki759a7632015-10-28 16:43:10 -07001011 mCachedEffectiveUserRestrictions.put(userId, effective);
1012
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001013 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001014 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001015 debug("Applying user restrictions: userId=" + userId
1016 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001017 }
1018
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001019 if (mAppOpsService != null) { // We skip it until system-ready.
1020 final long token = Binder.clearCallingIdentity();
1021 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001022 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001023 } catch (RemoteException e) {
1024 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1025 } finally {
1026 Binder.restoreCallingIdentity(token);
1027 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001028 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001029
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001030 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001031
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001032 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001033 }
1034
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001035 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001036 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001037 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1038 // actually, but we still need some kind of synchronization otherwise we might end up
1039 // calling listeners out-of-order, thus "LR".
1040
1041 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1042 return;
1043 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001044
1045 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1046 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1047
1048 mHandler.post(new Runnable() {
1049 @Override
1050 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001051 UserRestrictionsUtils.applyUserRestrictions(
1052 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001053
Makoto Onukid45a4a22015-11-02 17:17:38 -08001054 final UserRestrictionsListener[] listeners;
1055 synchronized (mUserRestrictionsListeners) {
1056 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1057 mUserRestrictionsListeners.toArray(listeners);
1058 }
1059 for (int i = 0; i < listeners.length; i++) {
1060 listeners[i].onUserRestrictionsChanged(userId,
1061 newRestrictionsFinal, prevRestrictionsFinal);
1062 }
1063 }
1064 });
1065 }
1066
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001067 // Package private for the inner class.
1068 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001069 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001070 }
1071
1072 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001073 // Package private for the inner class.
1074 void applyUserRestrictionsForAllUsersLR() {
1075 if (DBG) {
1076 debug("applyUserRestrictionsForAllUsersLR");
1077 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001078 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001079 mCachedEffectiveUserRestrictions.clear();
1080
Makoto Onuki068c54a2015-10-13 14:34:03 -07001081 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1082 // it on a handler.
1083 final Runnable r = new Runnable() {
1084 @Override
1085 public void run() {
1086 // Then get the list of running users.
1087 final int[] runningUsers;
1088 try {
1089 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1090 } catch (RemoteException e) {
1091 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1092 return;
1093 }
1094 // Then re-calculate the effective restrictions and apply, only for running users.
1095 // It's okay if a new user has started after the getRunningUserIds() call,
1096 // because we'll do the same thing (re-calculate the restrictions and apply)
1097 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001098 synchronized (mRestrictionsLock) {
1099 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001100 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001101 }
1102 }
1103 }
1104 };
1105 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001106 }
1107
Amith Yamasani258848d2012-08-10 17:06:33 -07001108 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001109 * Check if we've hit the limit of how many users can be created.
1110 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001111 private boolean isUserLimitReached() {
1112 int count;
1113 synchronized (mUsersLock) {
1114 count = getAliveUsersExcludingGuestsCountLU();
1115 }
1116 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001117 }
1118
1119 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001120 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001121 checkManageUsersPermission("check if more managed profiles can be added.");
1122 if (ActivityManager.isLowRamDeviceStatic()) {
1123 return false;
1124 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001125 if (!mContext.getPackageManager().hasSystemFeature(
1126 PackageManager.FEATURE_MANAGED_USERS)) {
1127 return false;
1128 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001129 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001130 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1131 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1132 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001133 return false;
1134 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001135 synchronized(mUsersLock) {
1136 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001137 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001138 return false;
1139 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001140 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1141 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001142 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001143 return usersCountAfterRemoving == 1
1144 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001145 }
1146 }
1147
Fyodor Kupolov82402752015-10-28 14:54:51 -07001148 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001149 int aliveUserCount = 0;
1150 final int totalUserCount = mUsers.size();
1151 // Skip over users being removed
1152 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001153 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001154 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001155 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001156 aliveUserCount++;
1157 }
1158 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001159 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001160 }
1161
1162 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001163 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001164 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1165 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1166 * permissions can make certain calls to the UserManager.
1167 *
1168 * @param message used as message if SecurityException is thrown
1169 * @throws SecurityException if the caller does not have enough privilege.
1170 */
1171 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1172 final int uid = Binder.getCallingUid();
1173 if (uid != Process.SYSTEM_UID && uid != 0
1174 && ActivityManager.checkComponentPermission(
1175 Manifest.permission.MANAGE_USERS,
1176 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1177 && ActivityManager.checkComponentPermission(
1178 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1179 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1180 throw new SecurityException(
1181 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1182 + message);
1183 }
1184 }
1185
1186 /**
1187 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001188 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001189 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001190 *
1191 * @param message used as message if SecurityException is thrown
1192 * @throws SecurityException if the caller is not system or root
1193 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001194 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001195 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001196 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001197 && ActivityManager.checkComponentPermission(
1198 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001199 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1200 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1201 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001202 }
1203
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001204 /**
1205 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1206 * UserManager.
1207 *
1208 * @param message used as message if SecurityException is thrown
1209 * @throws SecurityException if the caller is not system or root
1210 */
1211 private static void checkSystemOrRoot(String message) {
1212 final int uid = Binder.getCallingUid();
1213 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1214 throw new SecurityException("Only system may: " + message);
1215 }
1216 }
1217
Fyodor Kupolov82402752015-10-28 14:54:51 -07001218 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001219 try {
1220 File dir = new File(mUsersDir, Integer.toString(info.id));
1221 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001222 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001223 if (!dir.exists()) {
1224 dir.mkdir();
1225 FileUtils.setPermissions(
1226 dir.getPath(),
1227 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1228 -1, -1);
1229 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001230 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001231 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1232 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001233 info.iconPath = file.getAbsolutePath();
1234 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001235 try {
1236 os.close();
1237 } catch (IOException ioe) {
1238 // What the ... !
1239 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001240 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001241 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001242 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001243 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001244 }
1245
Amith Yamasani0b285492011-04-14 17:35:23 -07001246 /**
1247 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1248 * cache it elsewhere.
1249 * @return the array of user ids.
1250 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001251 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001252 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001253 return mUserIds;
1254 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001255 }
1256
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001257 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001258 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001259 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001260 return;
1261 }
1262 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001263 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001264 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001265 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001266 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001267 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001268 int type;
1269 while ((type = parser.next()) != XmlPullParser.START_TAG
1270 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001271 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001272 }
1273
1274 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001275 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001276 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001277 return;
1278 }
1279
Amith Yamasani2a003292012-08-14 18:25:45 -07001280 mNextSerialNumber = -1;
1281 if (parser.getName().equals(TAG_USERS)) {
1282 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1283 if (lastSerialNumber != null) {
1284 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1285 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001286 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1287 if (versionNumber != null) {
1288 mUserVersion = Integer.parseInt(versionNumber);
1289 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001290 }
1291
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001292 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1293
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001294 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301295 if (type == XmlPullParser.START_TAG) {
1296 final String name = parser.getName();
1297 if (name.equals(TAG_USER)) {
1298 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001299
Amith Yamasani12747872015-12-07 14:19:49 -08001300 UserData userData = readUserLP(Integer.parseInt(id));
1301
1302 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001303 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001304 mUsers.put(userData.info.id, userData);
1305 if (mNextSerialNumber < 0
1306 || mNextSerialNumber <= userData.info.id) {
1307 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001308 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301309 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001310 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301311 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001312 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1313 && type != XmlPullParser.END_TAG) {
1314 if (type == XmlPullParser.START_TAG) {
1315 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001316 synchronized (mGuestRestrictions) {
1317 UserRestrictionsUtils
1318 .readRestrictions(parser, mGuestRestrictions);
1319 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001320 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1321 ) {
1322 UserRestrictionsUtils.readRestrictions(parser,
1323 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001324 }
1325 break;
1326 }
1327 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001328 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001329 }
1330 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001331 synchronized (mRestrictionsLock) {
1332 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1333 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001334 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001335 upgradeIfNecessaryLP();
1336 } catch (IOException | XmlPullParserException e) {
1337 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001338 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001339 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001340 }
1341 }
1342
Amith Yamasani6f34b412012-10-22 18:19:27 -07001343 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001344 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001345 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001346 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001347 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001348 int userVersion = mUserVersion;
1349 if (userVersion < 1) {
1350 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001351 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1352 if ("Primary".equals(userData.info.name)) {
1353 userData.info.name =
1354 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1355 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001356 }
1357 userVersion = 1;
1358 }
1359
Amith Yamasanibc9625052012-11-15 14:39:18 -08001360 if (userVersion < 2) {
1361 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001362 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1363 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1364 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1365 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001366 }
1367 userVersion = 2;
1368 }
1369
Amith Yamasani350962c2013-08-06 11:18:53 -07001370
Amith Yamasani5e486f52013-08-07 11:06:44 -07001371 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001372 userVersion = 4;
1373 }
1374
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001375 if (userVersion < 5) {
1376 initDefaultGuestRestrictions();
1377 userVersion = 5;
1378 }
1379
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001380 if (userVersion < 6) {
1381 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001382 synchronized (mUsersLock) {
1383 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001384 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001385 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001386 if (!splitSystemUser && userData.info.isRestricted()
1387 && (userData.info.restrictedProfileParentId
1388 == UserInfo.NO_PROFILE_GROUP_ID)) {
1389 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1390 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001391 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001392 }
1393 }
1394 userVersion = 6;
1395 }
1396
Amith Yamasani6f34b412012-10-22 18:19:27 -07001397 if (userVersion < USER_VERSION) {
1398 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1399 + USER_VERSION);
1400 } else {
1401 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001402
1403 if (originalVersion < mUserVersion) {
1404 writeUserListLP();
1405 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001406 }
1407 }
1408
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001409 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001410 int flags = UserInfo.FLAG_INITIALIZED;
1411 // In split system user mode, the admin and primary flags are assigned to the first human
1412 // user.
1413 if (!UserManager.isSplitSystemUser()) {
1414 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1415 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001416 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001417 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001418 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001419 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001420 UserData userData = new UserData();
1421 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001422 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001423 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001424 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001425 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001426 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001427
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001428 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001429 synchronized (mRestrictionsLock) {
1430 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1431 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001432
Fyodor Kupolov82402752015-10-28 14:54:51 -07001433 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001434 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001435
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001436 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001437 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001438 }
1439
Amith Yamasani12747872015-12-07 14:19:49 -08001440 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001441 if (DBG) {
1442 debug("scheduleWriteUser");
1443 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001444 // No need to wrap it within a lock -- worst case, we'll just post the same message
1445 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001446 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1447 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001448 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1449 }
1450 }
1451
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001452 /*
1453 * Writes the user file in this format:
1454 *
1455 * <user flags="20039023" id="0">
1456 * <name>Primary</name>
1457 * </user>
1458 */
Amith Yamasani12747872015-12-07 14:19:49 -08001459 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001460 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001461 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001462 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001463 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001464 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001465 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001466 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001467 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1468
1469 // XmlSerializer serializer = XmlUtils.serializerInstance();
1470 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001471 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001472 serializer.startDocument(null, true);
1473 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1474
Amith Yamasani12747872015-12-07 14:19:49 -08001475 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001476 serializer.startTag(null, TAG_USER);
1477 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001478 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001479 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001480 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1481 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1482 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001483 if (userInfo.iconPath != null) {
1484 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1485 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001486 if (userInfo.partial) {
1487 serializer.attribute(null, ATTR_PARTIAL, "true");
1488 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001489 if (userInfo.guestToRemove) {
1490 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1491 }
Kenny Guy2a764942014-04-02 13:29:20 +01001492 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1493 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1494 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001495 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001496 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1497 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1498 Integer.toString(userInfo.restrictedProfileParentId));
1499 }
Amith Yamasani12747872015-12-07 14:19:49 -08001500 // Write seed data
1501 if (userData.persistSeedData) {
1502 if (userData.seedAccountName != null) {
1503 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1504 }
1505 if (userData.seedAccountType != null) {
1506 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1507 }
1508 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001509 serializer.startTag(null, TAG_NAME);
1510 serializer.text(userInfo.name);
1511 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001512 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001513 UserRestrictionsUtils.writeRestrictions(serializer,
1514 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1515 UserRestrictionsUtils.writeRestrictions(serializer,
1516 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1517 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001518 }
Amith Yamasani12747872015-12-07 14:19:49 -08001519
1520 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001521 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001522 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001523 serializer.endTag(null, TAG_ACCOUNT);
1524 }
1525
Amith Yamasani12747872015-12-07 14:19:49 -08001526 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1527 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1528 userData.seedAccountOptions.saveToXml(serializer);
1529 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1530 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001531 serializer.endTag(null, TAG_USER);
1532
1533 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001534 userFile.finishWrite(fos);
1535 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001536 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001537 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001538 }
1539 }
1540
1541 /*
1542 * Writes the user list file in this format:
1543 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001544 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001545 * <user id="0"></user>
1546 * <user id="2"></user>
1547 * </users>
1548 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001549 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001550 if (DBG) {
1551 debug("writeUserList");
1552 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001553 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001554 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001555 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001556 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001557 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1558
1559 // XmlSerializer serializer = XmlUtils.serializerInstance();
1560 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001561 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001562 serializer.startDocument(null, true);
1563 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1564
1565 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001566 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001567 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001568
Adam Lesinskieddeb492014-09-08 17:50:03 -07001569 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001570 synchronized (mGuestRestrictions) {
1571 UserRestrictionsUtils
1572 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1573 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301574 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001575 synchronized (mRestrictionsLock) {
1576 UserRestrictionsUtils.writeRestrictions(serializer,
1577 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1578 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001579 int[] userIdsToWrite;
1580 synchronized (mUsersLock) {
1581 userIdsToWrite = new int[mUsers.size()];
1582 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001583 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001584 userIdsToWrite[i] = user.id;
1585 }
1586 }
1587 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001588 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001589 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001590 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001591 }
1592
1593 serializer.endTag(null, TAG_USERS);
1594
1595 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001596 userListFile.finishWrite(fos);
1597 } catch (Exception e) {
1598 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001599 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001600 }
1601 }
1602
Amith Yamasani12747872015-12-07 14:19:49 -08001603 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001604 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001605 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001606 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001607 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001608 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001609 long creationTime = 0L;
1610 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001611 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001612 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001613 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001614 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001615 boolean persistSeedData = false;
1616 String seedAccountName = null;
1617 String seedAccountType = null;
1618 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001619 Bundle baseRestrictions = new Bundle();
1620 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001621
1622 FileInputStream fis = null;
1623 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001624 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001625 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001626 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001627 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001628 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001629 int type;
1630 while ((type = parser.next()) != XmlPullParser.START_TAG
1631 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001632 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001633 }
1634
1635 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001636 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001637 return null;
1638 }
1639
1640 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001641 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1642 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001643 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001644 return null;
1645 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001646 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1647 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001648 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001649 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1650 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001651 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1652 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001653 restrictedProfileParentId = readIntAttribute(parser,
1654 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001655 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1656 if ("true".equals(valueString)) {
1657 partial = true;
1658 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001659 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1660 if ("true".equals(valueString)) {
1661 guestToRemove = true;
1662 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001663
Amith Yamasani12747872015-12-07 14:19:49 -08001664 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1665 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1666 if (seedAccountName != null || seedAccountType != null) {
1667 persistSeedData = true;
1668 }
1669
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001670 int outerDepth = parser.getDepth();
1671 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1672 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1673 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1674 continue;
1675 }
1676 String tag = parser.getName();
1677 if (TAG_NAME.equals(tag)) {
1678 type = parser.next();
1679 if (type == XmlPullParser.TEXT) {
1680 name = parser.getText();
1681 }
1682 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1684 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1685 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001686 } else if (TAG_ACCOUNT.equals(tag)) {
1687 type = parser.next();
1688 if (type == XmlPullParser.TEXT) {
1689 account = parser.getText();
1690 }
Amith Yamasani12747872015-12-07 14:19:49 -08001691 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1692 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1693 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001694 }
1695 }
1696 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001697
Amith Yamasani12747872015-12-07 14:19:49 -08001698 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001699 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001700 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001701 userInfo.creationTime = creationTime;
1702 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001703 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001704 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001705 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001706 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001707
1708 // Create the UserData object that's internal to this class
1709 UserData userData = new UserData();
1710 userData.info = userInfo;
1711 userData.account = account;
1712 userData.seedAccountName = seedAccountName;
1713 userData.seedAccountType = seedAccountType;
1714 userData.persistSeedData = persistSeedData;
1715 userData.seedAccountOptions = seedAccountOptions;
1716
Makoto Onuki068c54a2015-10-13 14:34:03 -07001717 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001718 mBaseUserRestrictions.put(id, baseRestrictions);
1719 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001720 }
Amith Yamasani12747872015-12-07 14:19:49 -08001721 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001722 } catch (IOException ioe) {
1723 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001724 } finally {
1725 if (fis != null) {
1726 try {
1727 fis.close();
1728 } catch (IOException e) {
1729 }
1730 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001731 }
1732 return null;
1733 }
1734
Amith Yamasani920ace02012-09-20 22:15:37 -07001735 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1736 String valueString = parser.getAttributeValue(null, attr);
1737 if (valueString == null) return defaultValue;
1738 try {
1739 return Integer.parseInt(valueString);
1740 } catch (NumberFormatException nfe) {
1741 return defaultValue;
1742 }
1743 }
1744
1745 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1746 String valueString = parser.getAttributeValue(null, attr);
1747 if (valueString == null) return defaultValue;
1748 try {
1749 return Long.parseLong(valueString);
1750 } catch (NumberFormatException nfe) {
1751 return defaultValue;
1752 }
1753 }
1754
Amith Yamasanib82add22013-07-09 11:24:44 -07001755 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001756 * Removes the app restrictions file for a specific package and user id, if it exists.
1757 */
1758 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1759 synchronized (mPackagesLock) {
1760 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001761 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001762 if (resFile.exists()) {
1763 resFile.delete();
1764 }
1765 }
1766 }
1767
Kenny Guya52dc3e2014-02-11 15:33:14 +00001768 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001769 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001770 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001771 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001772 }
1773
Amith Yamasani258848d2012-08-10 17:06:33 -07001774 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001775 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001776 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001777 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001778 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001779
Jessica Hummelbe81c802014-04-22 15:49:22 +01001780 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001781 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001782 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1783 return null;
1784 }
phweisse9c44062016-02-10 12:57:38 +01001785 return createUserInternalUnchecked(name, flags, parentId);
1786 }
1787
1788 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001789 if (ActivityManager.isLowRamDeviceStatic()) {
1790 return null;
1791 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001792 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001793 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001794 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001795 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001796 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001797 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001798 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001799 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001800 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001801 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001802 if (parentId != UserHandle.USER_NULL) {
1803 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001804 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001805 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001806 if (parent == null) return null;
1807 }
1808 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1809 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1810 return null;
1811 }
1812 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1813 // If we're not adding a guest user or a managed profile and the limit has
1814 // been reached, cannot add a user.
1815 return null;
1816 }
1817 // If we're adding a guest and there already exists one, bail.
1818 if (isGuest && findCurrentGuestUser() != null) {
1819 return null;
1820 }
1821 // In legacy mode, restricted profile's parent can only be the owner user
1822 if (isRestricted && !UserManager.isSplitSystemUser()
1823 && (parentId != UserHandle.USER_SYSTEM)) {
1824 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1825 return null;
1826 }
1827 if (isRestricted && UserManager.isSplitSystemUser()) {
1828 if (parent == null) {
1829 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1830 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001831 return null;
1832 }
Amith Yamasani12747872015-12-07 14:19:49 -08001833 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001834 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1835 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001836 return null;
1837 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001838 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01001839 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
1840 Log.e(LOG_TAG,
1841 "Ephemeral users are supported on split-system-user systems only.");
1842 return null;
1843 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001844 // In split system user mode, we assign the first human user the primary flag.
1845 // And if there is no device owner, we also assign the admin flag to primary user.
1846 if (UserManager.isSplitSystemUser()
1847 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1848 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001849 synchronized (mUsersLock) {
1850 if (!mIsDeviceManaged) {
1851 flags |= UserInfo.FLAG_ADMIN;
1852 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001853 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001854 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001855
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001856 userId = getNextAvailableId();
1857 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001858 boolean ephemeralGuests = Resources.getSystem()
1859 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001860
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001861 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001862 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1863 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1864 || (parent != null && parent.info.isEphemeral())) {
1865 flags |= UserInfo.FLAG_EPHEMERAL;
1866 }
1867
1868 userInfo = new UserInfo(userId, name, null, flags);
1869 userInfo.serialNumber = mNextSerialNumber++;
1870 long now = System.currentTimeMillis();
1871 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1872 userInfo.partial = true;
1873 userData = new UserData();
1874 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001875 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001876 }
1877 writeUserListLP();
1878 if (parent != null) {
1879 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001880 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1881 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001882 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001883 }
Amith Yamasani12747872015-12-07 14:19:49 -08001884 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001885 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001886 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1887 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001888 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001889 }
Amith Yamasani12747872015-12-07 14:19:49 -08001890 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001891 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001892 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001893 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001894 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001895 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkey47f71082016-02-01 17:03:54 -07001896 prepareUserStorage(userId, userInfo.serialNumber,
1897 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001898 mPm.createNewUser(userId);
1899 userInfo.partial = false;
1900 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001901 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001902 }
1903 updateUserIds();
1904 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001905 if (isGuest) {
1906 synchronized (mGuestRestrictions) {
1907 restrictions.putAll(mGuestRestrictions);
1908 }
1909 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001910 synchronized (mRestrictionsLock) {
1911 mBaseUserRestrictions.append(userId, restrictions);
1912 }
1913 mPm.newUserCreated(userId);
1914 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1915 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1916 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1917 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001918 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001919 } finally {
1920 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001921 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001922 return userInfo;
1923 }
1924
Amith Yamasani0b285492011-04-14 17:35:23 -07001925 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001926 * @hide
1927 */
Amith Yamasani12747872015-12-07 14:19:49 -08001928 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001929 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1930 checkManageUsersPermission("setupRestrictedProfile");
1931 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1932 if (user == null) {
1933 return null;
1934 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08001935 long identity = Binder.clearCallingIdentity();
1936 try {
1937 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1938 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1939 // the putIntForUser() will fail.
1940 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1941 android.provider.Settings.Secure.LOCATION_MODE,
1942 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1943 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1944 } finally {
1945 Binder.restoreCallingIdentity(identity);
1946 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001947 return user;
1948 }
1949
1950 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001951 * Find the current guest user. If the Guest user is partial,
1952 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001953 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001954 private UserInfo findCurrentGuestUser() {
1955 synchronized (mUsersLock) {
1956 final int size = mUsers.size();
1957 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001958 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001959 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1960 return user;
1961 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001962 }
1963 }
1964 return null;
1965 }
1966
1967 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001968 * Mark this guest user for deletion to allow us to create another guest
1969 * and switch to that user before actually removing this guest.
1970 * @param userHandle the userid of the current guest
1971 * @return whether the user could be marked for deletion
1972 */
Amith Yamasani12747872015-12-07 14:19:49 -08001973 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001974 public boolean markGuestForDeletion(int userHandle) {
1975 checkManageUsersPermission("Only the system can remove users");
1976 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1977 UserManager.DISALLOW_REMOVE_USER, false)) {
1978 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1979 return false;
1980 }
1981
1982 long ident = Binder.clearCallingIdentity();
1983 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001984 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001985 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001986 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001987 userData = mUsers.get(userHandle);
1988 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001989 return false;
1990 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001991 }
Amith Yamasani12747872015-12-07 14:19:49 -08001992 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001993 return false;
1994 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001995 // We set this to a guest user that is to be removed. This is a temporary state
1996 // where we are allowed to add new Guest users, even if this one is still not
1997 // removed. This user will still show up in getUserInfo() calls.
1998 // If we don't get around to removing this Guest user, it will be purged on next
1999 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002000 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002001 // Mark it as disabled, so that it isn't returned any more when
2002 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002003 userData.info.flags |= UserInfo.FLAG_DISABLED;
2004 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002005 }
2006 } finally {
2007 Binder.restoreCallingIdentity(ident);
2008 }
2009 return true;
2010 }
2011
2012 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002013 * Removes a user and all data directories created for that user. This method should be called
2014 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002015 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002016 */
Amith Yamasani12747872015-12-07 14:19:49 -08002017 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002018 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002019 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002020 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2021 UserManager.DISALLOW_REMOVE_USER, false)) {
2022 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2023 return false;
2024 }
2025
Kenny Guyee58b4f2014-05-23 15:19:53 +01002026 long ident = Binder.clearCallingIdentity();
2027 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002028 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002029 int currentUser = ActivityManager.getCurrentUser();
2030 if (currentUser == userHandle) {
2031 Log.w(LOG_TAG, "Current user cannot be removed");
2032 return false;
2033 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002034 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002035 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002036 userData = mUsers.get(userHandle);
2037 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002038 return false;
2039 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002040
Fyodor Kupolov82402752015-10-28 14:54:51 -07002041 // We remember deleted user IDs to prevent them from being
2042 // reused during the current boot; they can still be reused
2043 // after a reboot.
2044 mRemovingUserIds.put(userHandle, true);
2045 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002046
Kenny Guyee58b4f2014-05-23 15:19:53 +01002047 try {
2048 mAppOpsService.removeUser(userHandle);
2049 } catch (RemoteException e) {
2050 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2051 }
2052 // Set this to a partially created user, so that the user will be purged
2053 // on next startup, in case the runtime stops now before stopping and
2054 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002055 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002056 // Mark it as disabled, so that it isn't returned any more when
2057 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002058 userData.info.flags |= UserInfo.FLAG_DISABLED;
2059 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002060 }
2061
Amith Yamasani12747872015-12-07 14:19:49 -08002062 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2063 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002064 // Send broadcast to notify system that the user removed was a
2065 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002066 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002067 }
2068
2069 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2070 int res;
2071 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002072 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2073 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002074 @Override
2075 public void userStopped(int userId) {
2076 finishRemoveUser(userId);
2077 }
2078 @Override
2079 public void userStopAborted(int userId) {
2080 }
2081 });
2082 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002083 return false;
2084 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002085 return res == ActivityManager.USER_OP_SUCCESS;
2086 } finally {
2087 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002088 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002089 }
2090
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002091 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002092 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002093 // Let other services shutdown any activity and clean up their state before completely
2094 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002095 long ident = Binder.clearCallingIdentity();
2096 try {
2097 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2098 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002099 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2100 android.Manifest.permission.MANAGE_USERS,
2101
2102 new BroadcastReceiver() {
2103 @Override
2104 public void onReceive(Context context, Intent intent) {
2105 if (DBG) {
2106 Slog.i(LOG_TAG,
2107 "USER_REMOVED broadcast sent, cleaning up user data "
2108 + userHandle);
2109 }
2110 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002111 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002112 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002113 // Clean up any ActivityManager state
2114 LocalServices.getService(ActivityManagerInternal.class)
2115 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002116 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002117 }
2118 }.start();
2119 }
2120 },
2121
2122 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002123 } finally {
2124 Binder.restoreCallingIdentity(ident);
2125 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002126 }
2127
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002128 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002129 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002130 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002131 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002132
2133 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002134 synchronized (mUsersLock) {
2135 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002136 mIsUserManaged.delete(userHandle);
2137 }
2138 synchronized (mRestrictionsLock) {
2139 mBaseUserRestrictions.remove(userHandle);
2140 mAppliedUserRestrictions.remove(userHandle);
2141 mCachedEffectiveUserRestrictions.remove(userHandle);
2142 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002143 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002144 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002145 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002146 userFile.delete();
2147 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002148 synchronized (mPackagesLock) {
2149 writeUserListLP();
2150 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002151 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002152 File userDir = Environment.getUserSystemDirectory(userHandle);
2153 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2154 if (userDir.renameTo(renamedUserDir)) {
2155 removeDirectoryRecursive(renamedUserDir);
2156 } else {
2157 removeDirectoryRecursive(userDir);
2158 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002159 }
2160
Amith Yamasani61f57372012-08-31 12:12:28 -07002161 private void removeDirectoryRecursive(File parent) {
2162 if (parent.isDirectory()) {
2163 String[] files = parent.list();
2164 for (String filename : files) {
2165 File child = new File(parent, filename);
2166 removeDirectoryRecursive(child);
2167 }
2168 }
2169 parent.delete();
2170 }
2171
Kenny Guyf8d3a232014-05-15 16:09:52 +01002172 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002173 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002174 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2175 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002176 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002177 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002178 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002179 }
2180
Amith Yamasani2a003292012-08-14 18:25:45 -07002181 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002182 public Bundle getApplicationRestrictions(String packageName) {
2183 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2184 }
2185
2186 @Override
2187 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002188 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002189 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002190 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002191 }
2192 synchronized (mPackagesLock) {
2193 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002194 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002195 }
2196 }
2197
2198 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002199 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002200 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002201 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002202 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002203 if (restrictions == null || restrictions.isEmpty()) {
2204 cleanAppRestrictionsForPackage(packageName, userId);
2205 } else {
2206 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002207 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002208 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002209 }
Robin Lee66e5d962014-04-09 16:44:21 +01002210
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002211 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2212 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2213 changeIntent.setPackage(packageName);
2214 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2215 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002216 }
2217
2218 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002219 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002220 try {
2221 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002222 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002223 } catch (NameNotFoundException nnfe) {
2224 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002225 } finally {
2226 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002227 }
2228 }
2229
Fyodor Kupolov82402752015-10-28 14:54:51 -07002230 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002231 AtomicFile restrictionsFile =
2232 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2233 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002234 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002235 }
2236
2237 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002238 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002239 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002240 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002241 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002242 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002243 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002244
2245 FileInputStream fis = null;
2246 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002247 fis = restrictionsFile.openRead();
2248 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002249 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002250 XmlUtils.nextElement(parser);
2251 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002252 Slog.e(LOG_TAG, "Unable to read restrictions file "
2253 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002254 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002255 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002256 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2257 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002258 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002259 } catch (IOException|XmlPullParserException e) {
2260 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002261 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002262 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002263 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002264 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002265 }
2266
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002267 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2268 XmlPullParser parser) throws XmlPullParserException, IOException {
2269 int type = parser.getEventType();
2270 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2271 String key = parser.getAttributeValue(null, ATTR_KEY);
2272 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2273 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2274 if (multiple != null) {
2275 values.clear();
2276 int count = Integer.parseInt(multiple);
2277 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2278 if (type == XmlPullParser.START_TAG
2279 && parser.getName().equals(TAG_VALUE)) {
2280 values.add(parser.nextText().trim());
2281 count--;
2282 }
2283 }
2284 String [] valueStrings = new String[values.size()];
2285 values.toArray(valueStrings);
2286 restrictions.putStringArray(key, valueStrings);
2287 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2288 restrictions.putBundle(key, readBundleEntry(parser, values));
2289 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2290 final int outerDepth = parser.getDepth();
2291 ArrayList<Bundle> bundleList = new ArrayList<>();
2292 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2293 Bundle childBundle = readBundleEntry(parser, values);
2294 bundleList.add(childBundle);
2295 }
2296 restrictions.putParcelableArray(key,
2297 bundleList.toArray(new Bundle[bundleList.size()]));
2298 } else {
2299 String value = parser.nextText().trim();
2300 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2301 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2302 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2303 restrictions.putInt(key, Integer.parseInt(value));
2304 } else {
2305 restrictions.putString(key, value);
2306 }
2307 }
2308 }
2309 }
2310
2311 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2312 throws IOException, XmlPullParserException {
2313 Bundle childBundle = new Bundle();
2314 final int outerDepth = parser.getDepth();
2315 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2316 readEntry(childBundle, values, parser);
2317 }
2318 return childBundle;
2319 }
2320
Fyodor Kupolov82402752015-10-28 14:54:51 -07002321 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002322 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002323 AtomicFile restrictionsFile = new AtomicFile(
2324 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002325 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002326 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002327 }
2328
2329 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002330 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002331 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002332 try {
2333 fos = restrictionsFile.startWrite();
2334 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2335
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002336 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002337 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002338 serializer.startDocument(null, true);
2339 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2340
2341 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002342 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002343 serializer.endTag(null, TAG_RESTRICTIONS);
2344
2345 serializer.endDocument();
2346 restrictionsFile.finishWrite(fos);
2347 } catch (Exception e) {
2348 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002349 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2350 }
2351 }
2352
2353 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2354 throws IOException {
2355 for (String key : restrictions.keySet()) {
2356 Object value = restrictions.get(key);
2357 serializer.startTag(null, TAG_ENTRY);
2358 serializer.attribute(null, ATTR_KEY, key);
2359
2360 if (value instanceof Boolean) {
2361 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2362 serializer.text(value.toString());
2363 } else if (value instanceof Integer) {
2364 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2365 serializer.text(value.toString());
2366 } else if (value == null || value instanceof String) {
2367 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2368 serializer.text(value != null ? (String) value : "");
2369 } else if (value instanceof Bundle) {
2370 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2371 writeBundle((Bundle) value, serializer);
2372 } else if (value instanceof Parcelable[]) {
2373 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2374 Parcelable[] array = (Parcelable[]) value;
2375 for (Parcelable parcelable : array) {
2376 if (!(parcelable instanceof Bundle)) {
2377 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2378 }
2379 serializer.startTag(null, TAG_ENTRY);
2380 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2381 writeBundle((Bundle) parcelable, serializer);
2382 serializer.endTag(null, TAG_ENTRY);
2383 }
2384 } else {
2385 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2386 String[] values = (String[]) value;
2387 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2388 for (String choice : values) {
2389 serializer.startTag(null, TAG_VALUE);
2390 serializer.text(choice != null ? choice : "");
2391 serializer.endTag(null, TAG_VALUE);
2392 }
2393 }
2394 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002395 }
2396 }
2397
2398 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002399 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002400 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002401 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002402 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002403 }
2404 }
2405
2406 @Override
2407 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002408 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002409 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002410 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002411 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002412 }
2413 // Not found
2414 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002415 }
2416 }
2417
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002418 @Override
2419 public long getUserCreationTime(int userHandle) {
2420 int callingUserId = UserHandle.getCallingUserId();
2421 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002422 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002423 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002424 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002425 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002426 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002427 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002428 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002429 }
2430 }
2431 }
2432 if (userInfo == null) {
2433 throw new SecurityException("userHandle can only be the calling user or a managed "
2434 + "profile associated with this user");
2435 }
2436 return userInfo.creationTime;
2437 }
2438
Amith Yamasani0b285492011-04-14 17:35:23 -07002439 /**
2440 * Caches the list of user ids in an array, adjusting the array size when necessary.
2441 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002442 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002443 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002444 synchronized (mUsersLock) {
2445 final int userSize = mUsers.size();
2446 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002447 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 num++;
2449 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002450 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002451 final int[] newUsers = new int[num];
2452 int n = 0;
2453 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002454 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002455 newUsers[n++] = mUsers.keyAt(i);
2456 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002457 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002458 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002459 }
2460 }
2461
2462 /**
Jeff Sharkey47f71082016-02-01 17:03:54 -07002463 * Prepare storage areas for given user on all mounted devices.
2464 */
2465 private void prepareUserStorage(int userId, int userSerial, int flags) {
2466 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2467 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
2468 final String volumeUuid = vol.getFsUuid();
2469 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
2470 }
2471 }
2472
2473 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002474 * Called right before a user is started. This gives us a chance to prepare
2475 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002476 */
2477 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002478 final int userSerial = getUserSerialNumber(userId);
2479 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
2480 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002481
2482 if (userId != UserHandle.USER_SYSTEM) {
2483 synchronized (mRestrictionsLock) {
2484 applyUserRestrictionsLR(userId);
2485 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002486 }
2487 }
2488
2489 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002490 * Called right before a user is unlocked. This gives us a chance to prepare
2491 * app storage.
2492 */
2493 public void onBeforeUnlockUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002494 final int userSerial = getUserSerialNumber(userId);
2495 prepareUserStorage(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
2496 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002497 }
2498
2499 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002500 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002501 * @param userId the user that was just foregrounded
2502 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002503 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002504 UserData userData = getUserDataNoChecks(userId);
2505 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002506 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2507 return;
2508 }
2509 long now = System.currentTimeMillis();
2510 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002511 userData.info.lastLoggedInTime = now;
2512 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002513 }
2514 }
2515
2516 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002517 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002518 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2519 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002520 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002521 private int getNextAvailableId() {
2522 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002523 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002524 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002525 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002526 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002527 }
2528 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002529 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002530 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002531 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002532 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002533
Amith Yamasanifc95e702013-09-26 13:20:17 -07002534 private String packageToRestrictionsFileName(String packageName) {
2535 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2536 }
2537
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002538 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002539 * Enforce that serial number stored in user directory inode matches the
2540 * given expected value. Gracefully sets the serial number if currently
2541 * undefined.
2542 *
2543 * @throws IOException when problem extracting serial number, or serial
2544 * number is mismatched.
2545 */
2546 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2547 final int foundSerial = getSerialNumber(file);
2548 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2549
2550 if (foundSerial == -1) {
2551 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2552 try {
2553 setSerialNumber(file, serialNumber);
2554 } catch (IOException e) {
2555 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2556 }
2557
2558 } else if (foundSerial != serialNumber) {
2559 throw new IOException("Found serial number " + foundSerial
2560 + " doesn't match expected " + serialNumber);
2561 }
2562 }
2563
2564 /**
2565 * Set serial number stored in user directory inode.
2566 *
2567 * @throws IOException if serial number was already set
2568 */
2569 private static void setSerialNumber(File file, int serialNumber)
2570 throws IOException {
2571 try {
2572 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2573 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2574 } catch (ErrnoException e) {
2575 throw e.rethrowAsIOException();
2576 }
2577 }
2578
2579 /**
2580 * Return serial number stored in user directory inode.
2581 *
2582 * @return parsed serial number, or -1 if not set
2583 */
2584 private static int getSerialNumber(File file) throws IOException {
2585 try {
2586 final byte[] buf = new byte[256];
2587 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2588 final String serial = new String(buf, 0, len);
2589 try {
2590 return Integer.parseInt(serial);
2591 } catch (NumberFormatException e) {
2592 throw new IOException("Bad serial number: " + serial);
2593 }
2594 } catch (ErrnoException e) {
2595 if (e.errno == OsConstants.ENODATA) {
2596 return -1;
2597 } else {
2598 throw e.rethrowAsIOException();
2599 }
2600 }
2601 }
2602
Amith Yamasani920ace02012-09-20 22:15:37 -07002603 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002604 public void setSeedAccountData(int userId, String accountName, String accountType,
2605 PersistableBundle accountOptions, boolean persist) {
2606 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2607 synchronized (mPackagesLock) {
2608 final UserData userData;
2609 synchronized (mUsersLock) {
2610 userData = getUserDataLU(userId);
2611 if (userData == null) {
2612 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2613 return;
2614 }
2615 userData.seedAccountName = accountName;
2616 userData.seedAccountType = accountType;
2617 userData.seedAccountOptions = accountOptions;
2618 userData.persistSeedData = persist;
2619 }
2620 if (persist) {
2621 writeUserLP(userData);
2622 }
2623 }
2624 }
2625
2626 @Override
2627 public String getSeedAccountName() throws RemoteException {
2628 checkManageUsersPermission("Cannot get seed account information");
2629 synchronized (mUsersLock) {
2630 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2631 return userData.seedAccountName;
2632 }
2633 }
2634
2635 @Override
2636 public String getSeedAccountType() throws RemoteException {
2637 checkManageUsersPermission("Cannot get seed account information");
2638 synchronized (mUsersLock) {
2639 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2640 return userData.seedAccountType;
2641 }
2642 }
2643
2644 @Override
2645 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2646 checkManageUsersPermission("Cannot get seed account information");
2647 synchronized (mUsersLock) {
2648 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2649 return userData.seedAccountOptions;
2650 }
2651 }
2652
2653 @Override
2654 public void clearSeedAccountData() throws RemoteException {
2655 checkManageUsersPermission("Cannot clear seed account information");
2656 synchronized (mPackagesLock) {
2657 UserData userData;
2658 synchronized (mUsersLock) {
2659 userData = getUserDataLU(UserHandle.getCallingUserId());
2660 if (userData == null) return;
2661 userData.clearSeedAccountData();
2662 }
2663 writeUserLP(userData);
2664 }
2665 }
2666
2667 @Override
2668 public boolean someUserHasSeedAccount(String accountName, String accountType)
2669 throws RemoteException {
2670 checkManageUsersPermission("Cannot check seed account information");
2671 synchronized (mUsersLock) {
2672 final int userSize = mUsers.size();
2673 for (int i = 0; i < userSize; i++) {
2674 final UserData data = mUsers.valueAt(i);
2675 if (data.info.isInitialized()) continue;
2676 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2677 continue;
2678 }
2679 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2680 continue;
2681 }
2682 return true;
2683 }
2684 }
2685 return false;
2686 }
2687
2688 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002689 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2690 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2691 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2692 }
2693
2694 int onShellCommand(Shell shell, String cmd) {
2695 if (cmd == null) {
2696 return shell.handleDefaultCommands(cmd);
2697 }
2698
2699 final PrintWriter pw = shell.getOutPrintWriter();
2700 try {
2701 switch(cmd) {
2702 case "list":
2703 return runList(pw);
2704 }
2705 } catch (RemoteException e) {
2706 pw.println("Remote exception: " + e);
2707 }
2708 return -1;
2709 }
2710
2711 private int runList(PrintWriter pw) throws RemoteException {
2712 final IActivityManager am = ActivityManagerNative.getDefault();
2713 final List<UserInfo> users = getUsers(false);
2714 if (users == null) {
2715 pw.println("Error: couldn't get users");
2716 return 1;
2717 } else {
2718 pw.println("Users:");
2719 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002720 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002721 pw.println("\t" + users.get(i).toString() + running);
2722 }
2723 return 0;
2724 }
2725 }
2726
2727 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002728 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2729 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2730 != PackageManager.PERMISSION_GRANTED) {
2731 pw.println("Permission Denial: can't dump UserManager from from pid="
2732 + Binder.getCallingPid()
2733 + ", uid=" + Binder.getCallingUid()
2734 + " without permission "
2735 + android.Manifest.permission.DUMP);
2736 return;
2737 }
2738
2739 long now = System.currentTimeMillis();
2740 StringBuilder sb = new StringBuilder();
2741 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002742 synchronized (mUsersLock) {
2743 pw.println("Users:");
2744 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002745 UserData userData = mUsers.valueAt(i);
2746 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002747 continue;
2748 }
Amith Yamasani12747872015-12-07 14:19:49 -08002749 UserInfo userInfo = userData.info;
2750 final int userId = userInfo.id;
2751 pw.print(" "); pw.print(userInfo);
2752 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002753 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002754 pw.print(" <removing> ");
2755 }
Amith Yamasani12747872015-12-07 14:19:49 -08002756 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002757 pw.print(" <partial>");
2758 }
2759 pw.println();
2760 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002761 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002762 pw.println("<unknown>");
2763 } else {
2764 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002765 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002766 sb.append(" ago");
2767 pw.println(sb);
2768 }
2769 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002770 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002771 pw.println("<unknown>");
2772 } else {
2773 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002774 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002775 sb.append(" ago");
2776 pw.println(sb);
2777 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002778 pw.print(" Has profile owner: ");
2779 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002780 pw.println(" Restrictions:");
2781 synchronized (mRestrictionsLock) {
2782 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002783 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002784 pw.println(" Device policy local restrictions:");
2785 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002786 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002787 pw.println(" Effective restrictions:");
2788 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002789 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002790 }
Amith Yamasani12747872015-12-07 14:19:49 -08002791
2792 if (userData.account != null) {
2793 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002794 pw.println();
2795 }
Amith Yamasani12747872015-12-07 14:19:49 -08002796
2797 if (userData.seedAccountName != null) {
2798 pw.print(" Seed account name: " + userData.seedAccountName);
2799 pw.println();
2800 if (userData.seedAccountType != null) {
2801 pw.print(" account type: " + userData.seedAccountType);
2802 pw.println();
2803 }
2804 if (userData.seedAccountOptions != null) {
2805 pw.print(" account options exist");
2806 pw.println();
2807 }
2808 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002809 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002810 }
Amith Yamasani12747872015-12-07 14:19:49 -08002811 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002812 pw.println(" Device policy global restrictions:");
2813 synchronized (mRestrictionsLock) {
2814 UserRestrictionsUtils
2815 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2816 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002817 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002818 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002819 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002820 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002821 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002822 synchronized (mUsersLock) {
2823 pw.println();
2824 pw.println(" Device managed: " + mIsDeviceManaged);
2825 }
Amith Yamasani12747872015-12-07 14:19:49 -08002826 // Dump some capabilities
2827 pw.println();
2828 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2829 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002830 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2831 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002832 }
2833 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002834
2835 final class MainHandler extends Handler {
2836
2837 @Override
2838 public void handleMessage(Message msg) {
2839 switch (msg.what) {
2840 case WRITE_USER_MSG:
2841 removeMessages(WRITE_USER_MSG, msg.obj);
2842 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002843 int userId = ((UserData) msg.obj).info.id;
2844 UserData userData = getUserDataNoChecks(userId);
2845 if (userData != null) {
2846 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002847 }
2848 }
2849 }
2850 }
2851 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002852
2853 /**
2854 * @param userId
2855 * @return whether the user has been initialized yet
2856 */
2857 boolean isInitialized(int userId) {
2858 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2859 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002860
2861 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002862 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002863 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2864 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002865 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002866 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002867 }
2868
2869 @Override
2870 public Bundle getBaseUserRestrictions(int userId) {
2871 synchronized (mRestrictionsLock) {
2872 return mBaseUserRestrictions.get(userId);
2873 }
2874 }
2875
2876 @Override
2877 public void setBaseUserRestrictionsByDpmsForMigration(
2878 int userId, Bundle baseRestrictions) {
2879 synchronized (mRestrictionsLock) {
2880 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002881 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002882 }
2883
Amith Yamasani12747872015-12-07 14:19:49 -08002884 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002885 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002886 if (userData != null) {
2887 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002888 } else {
2889 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2890 }
2891 }
2892 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002893
2894 @Override
2895 public boolean getUserRestriction(int userId, String key) {
2896 return getUserRestrictions(userId).getBoolean(key);
2897 }
2898
2899 @Override
2900 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2901 synchronized (mUserRestrictionsListeners) {
2902 mUserRestrictionsListeners.add(listener);
2903 }
2904 }
2905
2906 @Override
2907 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2908 synchronized (mUserRestrictionsListeners) {
2909 mUserRestrictionsListeners.remove(listener);
2910 }
2911 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002912
2913 @Override
2914 public void setDeviceManaged(boolean isManaged) {
2915 synchronized (mUsersLock) {
2916 mIsDeviceManaged = isManaged;
2917 }
2918 }
2919
2920 @Override
2921 public void setUserManaged(int userId, boolean isManaged) {
2922 synchronized (mUsersLock) {
2923 mIsUserManaged.put(userId, isManaged);
2924 }
2925 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002926
2927 @Override
2928 public void setUserIcon(int userId, Bitmap bitmap) {
2929 long ident = Binder.clearCallingIdentity();
2930 try {
2931 synchronized (mPackagesLock) {
2932 UserData userData = getUserDataNoChecks(userId);
2933 if (userData == null || userData.info.partial) {
2934 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2935 return;
2936 }
2937 writeBitmapLP(userData.info, bitmap);
2938 writeUserLP(userData);
2939 }
2940 sendUserInfoChangedBroadcast(userId);
2941 } finally {
2942 Binder.restoreCallingIdentity(ident);
2943 }
2944 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002945
2946 @Override
2947 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
2948 synchronized (mUsersLock) {
2949 mForceEphemeralUsers = forceEphemeralUsers;
2950 }
2951 }
2952
2953 @Override
2954 public void removeAllUsers() {
2955 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
2956 // Remove the non-system users straight away.
2957 removeNonSystemUsers();
2958 } else {
2959 // Switch to the system user first and then remove the other users.
2960 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
2961 @Override
2962 public void onReceive(Context context, Intent intent) {
2963 int userId =
2964 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2965 if (userId != UserHandle.USER_SYSTEM) {
2966 return;
2967 }
2968 mContext.unregisterReceiver(this);
2969 removeNonSystemUsers();
2970 }
2971 };
2972 IntentFilter userSwitchedFilter = new IntentFilter();
2973 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
2974 mContext.registerReceiver(
2975 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
2976
2977 // Switch to the system user.
2978 ActivityManager am =
2979 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
2980 am.switchUser(UserHandle.USER_SYSTEM);
2981 }
2982 }
phweisse9c44062016-02-10 12:57:38 +01002983
2984 @Override
2985 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
2986 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
2987 // Keep this in sync with UserManager.createUser
2988 if (user != null && !user.isAdmin()) {
2989 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
2990 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
2991 }
2992 return user;
2993 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002994 }
2995
2996 /* Remove all the users except of the system one. */
2997 private void removeNonSystemUsers() {
2998 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
2999 synchronized (mUsersLock) {
3000 final int userSize = mUsers.size();
3001 for (int i = 0; i < userSize; i++) {
3002 UserInfo ui = mUsers.valueAt(i).info;
3003 if (ui.id != UserHandle.USER_SYSTEM) {
3004 usersToRemove.add(ui);
3005 }
3006 }
3007 }
3008 for (UserInfo ui: usersToRemove) {
3009 removeUser(ui.id);
3010 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003011 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003012
3013 private class Shell extends ShellCommand {
3014 @Override
3015 public int onCommand(String cmd) {
3016 return onShellCommand(this, cmd);
3017 }
3018
3019 @Override
3020 public void onHelp() {
3021 final PrintWriter pw = getOutPrintWriter();
3022 pw.println("User manager (user) commands:");
3023 pw.println(" help");
3024 pw.println(" Print this help text.");
3025 pw.println("");
3026 pw.println(" list");
3027 pw.println(" Prints all users on the system.");
3028 }
3029 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003030
3031 private static void debug(String message) {
3032 Log.d(LOG_TAG, message +
3033 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3034 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003035}