blob: a8cf110655f80b9d789dcd41bb2840e4dbdaba04 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Benjamin Franzf02420c2016-04-04 18:52:21 +010019import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
20import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
21
Xiaohui Chenb3b92582015-12-07 11:22:13 -080022import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070023import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070024import android.annotation.Nullable;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060025import android.annotation.UserIdInt;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070027import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070028import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070029import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070030import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070031import android.app.IStopUserCallback;
Benjamin Franzf02420c2016-04-04 18:52:21 +010032import android.app.KeyguardManager;
Ricky Waib1dd80b2016-06-07 18:00:55 +010033import android.app.PendingIntent;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070034import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.content.Context;
36import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010037import android.content.IntentFilter;
Benjamin Franzf02420c2016-04-04 18:52:21 +010038import android.content.IntentSender;
Amith Yamasani0b285492011-04-14 17:35:23 -070039import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080040import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070041import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010042import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070043import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070044import android.os.Binder;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -060045import android.os.Build;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080046import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080047import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.os.Environment;
49import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.os.Handler;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080051import android.os.IBinder;
Amith Yamasani258848d2012-08-10 17:06:33 -070052import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080053import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010054import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070055import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080056import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070057import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070058import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070059import android.os.ResultReceiver;
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +010060import android.os.SELinux;
Jason Monk62062992014-05-06 09:55:28 -040061import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070062import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070063import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070064import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070065import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080066import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010067import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070068import android.system.ErrnoException;
69import android.system.Os;
70import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070071import android.util.AtomicFile;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070072import android.util.IntArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070073import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import android.util.Slog;
75import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080076import android.util.SparseBooleanArray;
Fyodor Kupolovac06a492016-05-25 14:45:29 -070077import android.util.SparseIntArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070078import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079import android.util.Xml;
80
Makoto Onuki068c54a2015-10-13 14:34:03 -070081import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070082import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040083import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080084import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080085import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070086import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070087import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000088import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070089import com.android.server.LocalServices;
Fyodor Kupolovac06a492016-05-25 14:45:29 -070090import com.android.server.am.UserState;
Jeff Sharkey47f71082016-02-01 17:03:54 -070091
92import libcore.io.IoUtils;
93import libcore.util.Objects;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080094
95import org.xmlpull.v1.XmlPullParser;
96import org.xmlpull.v1.XmlPullParserException;
97import org.xmlpull.v1.XmlSerializer;
98
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099import java.io.BufferedOutputStream;
100import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -0700101import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700102import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700103import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104import java.io.FileOutputStream;
105import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -0700106import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100107import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108import java.util.ArrayList;
109import java.util.List;
110
Makoto Onuki068c54a2015-10-13 14:34:03 -0700111/**
112 * Service for {@link UserManager}.
113 *
114 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700115 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800116 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700117 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
118 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
119 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700120 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700121public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700122 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800123 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800124 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700125
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700126 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800127 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700129 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700131 private static final String ATTR_CREATION_TIME = "created";
132 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -0600133 private static final String ATTR_LAST_LOGGED_IN_FINGERPRINT = "lastLoggedInFingerprint";
Amith Yamasani2a003292012-08-14 18:25:45 -0700134 private static final String ATTR_SERIAL_NO = "serialNumber";
135 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700136 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700137 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700138 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100139 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700140 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800141 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
142 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530143 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800146 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800147 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100148 private static final String TAG_GLOBAL_RESTRICTION_OWNER_ID = "globalRestrictionOwnerUserId";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800149 private static final String TAG_ENTRY = "entry";
150 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800151 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800152 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700153 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800154 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700155
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700156 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
157 private static final String ATTR_TYPE_STRING = "s";
158 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700159 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700160 private static final String ATTR_TYPE_BUNDLE = "B";
161 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700162
Amith Yamasani0b285492011-04-14 17:35:23 -0700163 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700164 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700165 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100166 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800168 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700169 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800170
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700171 private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
172 UserInfo.FLAG_MANAGED_PROFILE
173 | UserInfo.FLAG_EPHEMERAL
174 | UserInfo.FLAG_RESTRICTED
175 | UserInfo.FLAG_GUEST;
176
Amith Yamasani634cf312012-10-04 17:34:21 -0700177 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700178 // We need to keep process uid within Integer.MAX_VALUE.
179 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700180
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700181 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700182
Amith Yamasani920ace02012-09-20 22:15:37 -0700183 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
184
Nicolas Prevotb8186812015-08-06 15:00:03 +0100185 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700186 // without first making sure that the rest of the framework is prepared for it.
187 private static final int MAX_MANAGED_PROFILES = 1;
188
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800189 static final int WRITE_USER_MSG = 1;
190 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530191
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700192 private static final String XATTR_SERIAL = "user.serial";
193
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800194 // Tron counters
195 private static final String TRON_GUEST_CREATED = "users_guest_created";
196 private static final String TRON_USER_CREATED = "users_user_created";
197
Dianne Hackborn4428e172012-08-24 17:43:05 -0700198 private final Context mContext;
199 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700200 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700201 // Short-term lock for internal state, when interaction/sync with PM is not required
202 private final Object mUsersLock = new Object();
203 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700204
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800205 private final Handler mHandler;
206
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700207 private final File mUsersDir;
208 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700209
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800210 private static final IBinder mUserRestriconToken = new Binder();
211
Makoto Onuki068c54a2015-10-13 14:34:03 -0700212 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800213 * User-related information that is used for persisting to flash. Only UserInfo is
214 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800215 */
Amith Yamasani12747872015-12-07 14:19:49 -0800216 private static class UserData {
217 // Basic user information and properties
218 UserInfo info;
219 // Account name used when there is a strong association between a user and an account
220 String account;
221 // Account information for seeding into a newly created user. This could also be
222 // used for login validation for an existing user, for updating their credentials.
223 // In the latter case, data may not need to be persisted as it is only valid for the
224 // current login session.
225 String seedAccountName;
226 String seedAccountType;
227 PersistableBundle seedAccountOptions;
228 // Whether to perist the seed account information to be available after a boot
229 boolean persistSeedData;
230
231 void clearSeedAccountData() {
232 seedAccountName = null;
233 seedAccountType = null;
234 seedAccountOptions = null;
235 persistSeedData = false;
236 }
237 }
238
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800239 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800240 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800241
242 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700243 * User restrictions set via UserManager. This doesn't include restrictions set by
244 * device owner / profile owners.
245 *
246 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
247 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
248 * maybe shared between {@link #mBaseUserRestrictions} and
249 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
250 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700251 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700252 */
253 @GuardedBy("mRestrictionsLock")
254 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
255
256 /**
257 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
258 * with device / profile owner restrictions. We'll initialize it lazily; use
259 * {@link #getEffectiveUserRestrictions} to access it.
260 *
261 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
262 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
263 * maybe shared between {@link #mBaseUserRestrictions} and
264 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
265 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700266 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700267 */
268 @GuardedBy("mRestrictionsLock")
269 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
270
Makoto Onuki4f160732015-10-27 17:15:38 -0700271 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800272 * User restrictions that have already been applied in
273 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
274 * that have changed since the last
275 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700276 */
277 @GuardedBy("mRestrictionsLock")
278 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
279
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800280 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800281 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
282 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800283 */
284 @GuardedBy("mRestrictionsLock")
285 private Bundle mDevicePolicyGlobalUserRestrictions;
286
287 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100288 * Id of the user that set global restrictions.
289 */
290 @GuardedBy("mRestrictionsLock")
291 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
292
293 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800294 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
295 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800296 */
297 @GuardedBy("mRestrictionsLock")
298 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
299
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800300 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530301 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800302
303 /**
304 * Set of user IDs being actively removed. Removed IDs linger in this set
305 * for several seconds to work around a VFS caching issue.
306 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700307 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800308 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700309
Fyodor Kupolov82402752015-10-28 14:54:51 -0700310 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700311 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800312 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700313 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700314 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700315
Jason Monk62062992014-05-06 09:55:28 -0400316 private IAppOpsService mAppOpsService;
317
Makoto Onuki068c54a2015-10-13 14:34:03 -0700318 private final LocalService mLocalService;
319
Makoto Onukie7927da2015-11-25 10:05:17 -0800320 @GuardedBy("mUsersLock")
321 private boolean mIsDeviceManaged;
322
323 @GuardedBy("mUsersLock")
324 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
325
Makoto Onukid45a4a22015-11-02 17:17:38 -0800326 @GuardedBy("mUserRestrictionsListeners")
327 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
328 new ArrayList<>();
329
Clara Bayarria1771112015-12-18 16:29:18 +0000330 private final LockPatternUtils mLockPatternUtils;
331
Ricky Waib1dd80b2016-06-07 18:00:55 +0100332 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
333 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
334
335 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
336 @Override
337 public void onReceive(Context context, Intent intent) {
338 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
339 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
340 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
341 setQuietModeEnabled(userHandle, false);
342 if (target != null) {
343 try {
344 mContext.startIntentSender(target, null, 0, 0, 0);
345 } catch (IntentSender.SendIntentException e) {
346 /* ignore */
347 }
348 }
349 }
350 }
351 };
352
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100353 /**
354 * Whether all users should be created ephemeral.
355 */
356 @GuardedBy("mUsersLock")
357 private boolean mForceEphemeralUsers;
358
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700359 @GuardedBy("mUserStates")
360 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700361
Amith Yamasani258848d2012-08-10 17:06:33 -0700362 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700363
Dianne Hackborn4428e172012-08-24 17:43:05 -0700364 public static UserManagerService getInstance() {
365 synchronized (UserManagerService.class) {
366 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700367 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700368 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700369
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800370 @VisibleForTesting
371 UserManagerService(File dataDir) {
372 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700373 }
374
Dianne Hackborn4428e172012-08-24 17:43:05 -0700375 /**
376 * Called by package manager to create the service. This is closely
377 * associated with the package manager, and the given lock is the
378 * package manager's own lock.
379 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800380 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
381 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700382 }
383
Dianne Hackborn4428e172012-08-24 17:43:05 -0700384 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800385 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700386 mContext = context;
387 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700388 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800389 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800390 synchronized (mPackagesLock) {
391 mUsersDir = new File(dataDir, USER_INFO_DIR);
392 mUsersDir.mkdirs();
393 // Make zeroth user directory, for services to migrate their files to that location
394 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
395 userZeroDir.mkdirs();
396 FileUtils.setPermissions(mUsersDir.toString(),
397 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
398 -1, -1);
399 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
400 initDefaultGuestRestrictions();
401 readUserListLP();
402 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700403 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700404 mLocalService = new LocalService();
405 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000406 mLockPatternUtils = new LockPatternUtils(mContext);
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700407 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700408 }
409
410 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100411 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800412 ArrayList<UserInfo> partials = new ArrayList<>();
413 synchronized (mUsersLock) {
414 final int userSize = mUsers.size();
415 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800416 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100417 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800418 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700419 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700420 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700421 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800422 final int partialsSize = partials.size();
423 for (int i = 0; i < partialsSize; i++) {
424 UserInfo ui = partials.get(i);
425 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
426 + " (name=" + ui.name + ")");
427 removeUserState(ui.id);
428 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800429
Jason Monk62062992014-05-06 09:55:28 -0400430 mAppOpsService = IAppOpsService.Stub.asInterface(
431 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800432
433 synchronized (mRestrictionsLock) {
434 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400435 }
Samuel Tand9453b82016-03-14 15:57:02 -0700436
437 UserInfo currentGuestUser = findCurrentGuestUser();
438 if (currentGuestUser != null && !hasUserRestriction(
439 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
440 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
441 // to it, in case this guest was created in a previous version where this
442 // user restriction was not a default guest restriction.
443 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
444 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100445 mContext.registerReceiver(mDisableQuietModeCallback,
446 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
447 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700448 }
449
450 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800451 public String getUserAccount(int userId) {
452 checkManageUserAndAcrossUsersFullPermission("get user account");
453 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800454 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800455 }
456 }
457
458 @Override
459 public void setUserAccount(int userId, String accountName) {
460 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800461 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800462 synchronized (mPackagesLock) {
463 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800464 final UserData userData = mUsers.get(userId);
465 if (userData == null) {
466 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
467 return;
468 }
469 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800470 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800471 userData.account = accountName;
472 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800473 }
474 }
475
476 if (userToUpdate != null) {
477 writeUserLP(userToUpdate);
478 }
479 }
480 }
481
482 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700483 public UserInfo getPrimaryUser() {
484 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700485 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700486 final int userSize = mUsers.size();
487 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800488 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800489 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700490 return ui;
491 }
492 }
493 }
494 return null;
495 }
496
497 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700498 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -0700499 checkManageOrCreateUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700500 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700501 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700502 final int userSize = mUsers.size();
503 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800504 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700505 if (ui.partial) {
506 continue;
507 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800508 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700509 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700510 }
Amith Yamasani13593602012-03-22 16:16:17 -0700511 }
512 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700513 }
Amith Yamasani13593602012-03-22 16:16:17 -0700514 }
515
Amith Yamasani258848d2012-08-10 17:06:33 -0700516 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100517 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700518 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800519 if (userId != UserHandle.getCallingUserId()) {
520 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700521 } else {
522 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800523 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700524 final long ident = Binder.clearCallingIdentity();
525 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700526 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700527 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100528 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700529 } finally {
530 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000531 }
532 }
533
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700534 @Override
535 public int[] getProfileIds(int userId, boolean enabledOnly) {
536 if (userId != UserHandle.getCallingUserId()) {
537 checkManageUsersPermission("getting profiles related to user " + userId);
538 }
539 final long ident = Binder.clearCallingIdentity();
540 try {
541 synchronized (mUsersLock) {
542 return getProfileIdsLU(userId, enabledOnly).toArray();
543 }
544 } finally {
545 Binder.restoreCallingIdentity(ident);
546 }
547 }
548
Amith Yamasanibe465322014-04-24 13:45:17 -0700549 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700550 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700551 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
552 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
553 for (int i = 0; i < profileIds.size(); i++) {
554 int profileId = profileIds.get(i);
555 UserInfo userInfo = mUsers.get(profileId).info;
556 // If full info is not required - clear PII data to prevent 3P apps from reading it
557 if (!fullInfo) {
558 userInfo = new UserInfo(userInfo);
559 userInfo.name = null;
560 userInfo.iconPath = null;
561 } else {
562 userInfo = userWithName(userInfo);
563 }
564 users.add(userInfo);
565 }
566 return users;
567 }
568
569 /**
570 * Assume permissions already checked and caller's identity cleared
571 */
572 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700573 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700574 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700575 if (user == null) {
576 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700577 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700578 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700579 final int userSize = mUsers.size();
580 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800581 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700582 if (!isProfileOf(user, profile)) {
583 continue;
584 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100585 if (enabledOnly && !profile.isEnabled()) {
586 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700587 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700588 if (mRemovingUserIds.get(profile.id)) {
589 continue;
590 }
Tony Mak80189cd2016-04-05 17:21:42 +0100591 if (profile.partial) {
592 continue;
593 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700594 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700595 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700596 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700597 }
598
Jessica Hummelbe81c802014-04-22 15:49:22 +0100599 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700600 public int getCredentialOwnerProfile(int userHandle) {
601 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000602 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700603 synchronized (mUsersLock) {
604 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700605 if (profileParent != null) {
606 return profileParent.id;
607 }
608 }
609 }
610
611 return userHandle;
612 }
613
614 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700615 public boolean isSameProfileGroup(int userId, int otherUserId) {
616 if (userId == otherUserId) return true;
617 checkManageUsersPermission("check if in the same profile group");
618 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700619 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700620 }
621 }
622
Fyodor Kupolov82402752015-10-28 14:54:51 -0700623 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
624 synchronized (mUsersLock) {
625 UserInfo userInfo = getUserInfoLU(userId);
626 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
627 return false;
628 }
629 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
630 if (otherUserInfo == null
631 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
632 return false;
633 }
634 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700635 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700636 }
637
638 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100639 public UserInfo getProfileParent(int userHandle) {
640 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700641 synchronized (mUsersLock) {
642 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700643 }
644 }
645
Fyodor Kupolov82402752015-10-28 14:54:51 -0700646 private UserInfo getProfileParentLU(int userHandle) {
647 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700648 if (profile == null) {
649 return null;
650 }
651 int parentUserId = profile.profileGroupId;
652 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
653 return null;
654 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700655 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100656 }
657 }
658
Fyodor Kupolov82402752015-10-28 14:54:51 -0700659 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100660 return user.id == profile.id ||
661 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
662 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000663 }
664
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000665 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000666 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100667 Intent intent = new Intent();
668 if (inQuietMode) {
669 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
670 } else {
671 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
672 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000673 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
674 intent.putExtra(Intent.EXTRA_USER, profileHandle);
675 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000676 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000677 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000678 }
679
680 @Override
681 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
682 checkManageUsersPermission("silence profile");
683 boolean changed = false;
684 UserInfo profile, parent;
685 synchronized (mPackagesLock) {
686 synchronized (mUsersLock) {
687 profile = getUserInfoLU(userHandle);
688 parent = getProfileParentLU(userHandle);
689
690 }
691 if (profile == null || !profile.isManagedProfile()) {
692 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
693 }
694 if (profile.isQuietModeEnabled() != enableQuietMode) {
695 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800696 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000697 changed = true;
698 }
699 }
700 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000701 long identity = Binder.clearCallingIdentity();
702 try {
703 if (enableQuietMode) {
Rubin Xuf8451b92016-04-01 15:50:58 +0100704 LocalServices.getService(ActivityManagerInternal.class)
705 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000706 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
707 } else {
708 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
709 }
710 } catch (RemoteException e) {
711 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
712 } finally {
713 Binder.restoreCallingIdentity(identity);
714 }
715
716 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
717 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000718 }
719 }
720
721 @Override
722 public boolean isQuietModeEnabled(int userHandle) {
723 synchronized (mPackagesLock) {
724 UserInfo info;
725 synchronized (mUsersLock) {
726 info = getUserInfoLU(userHandle);
727 }
728 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000729 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000730 }
731 return info.isQuietModeEnabled();
732 }
733 }
734
Kenny Guya52dc3e2014-02-11 15:33:14 +0000735 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100736 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100737 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600738 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100739 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100740 // if the user is already unlocked, no need to show a profile challenge
741 setQuietModeEnabled(userHandle, false);
742 return true;
743 }
744
745 long identity = Binder.clearCallingIdentity();
746 try {
747 // otherwise, we show a profile challenge to trigger decryption of the user
748 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
749 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100750 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
751 // lock, confirm screenlock page will know and show personal challenge, and unlock
752 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100753 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
754 userHandle);
755 if (unlockIntent == null) {
756 return false;
757 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100758 final Intent callBackIntent = new Intent(
759 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100760 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100761 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100762 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100763 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
764 callBackIntent.setPackage(mContext.getPackageName());
765 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
766 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
767 mContext,
768 0,
769 callBackIntent,
770 PendingIntent.FLAG_CANCEL_CURRENT |
771 PendingIntent.FLAG_ONE_SHOT |
772 PendingIntent.FLAG_IMMUTABLE);
773 // After unlocking the challenge, it will disable quiet mode and run the original
774 // intentSender
775 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100776 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
777 mContext.startActivity(unlockIntent);
778 } finally {
779 Binder.restoreCallingIdentity(identity);
780 }
781 return false;
782 }
783
784 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100785 public void setUserEnabled(int userId) {
786 checkManageUsersPermission("enable user");
787 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700788 UserInfo info;
789 synchronized (mUsersLock) {
790 info = getUserInfoLU(userId);
791 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100792 if (info != null && !info.isEnabled()) {
793 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800794 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100795 }
796 }
797 }
798
799 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700800 public UserInfo getUserInfo(int userId) {
Sudheer Shankaaccaa082016-06-14 16:22:57 -0700801 checkManageOrCreateUsersPermission("query user");
Tony Mak8673b282016-03-21 21:10:59 +0000802 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700803 return userWithName(getUserInfoLU(userId));
804 }
805 }
806
807 /**
808 * Returns a UserInfo object with the name filled in, for Owner, or the original
809 * if the name is already set.
810 */
811 private UserInfo userWithName(UserInfo orig) {
812 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
813 UserInfo withName = new UserInfo(orig);
814 withName.name = getOwnerName();
815 return withName;
816 } else {
817 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000818 }
819 }
820
821 @Override
822 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000823 int callingUserId = UserHandle.getCallingUserId();
824 if (callingUserId != userId && !hasManageUsersPermission()) {
825 synchronized (mPackagesLock) {
826 if (!isSameProfileGroupLP(callingUserId, userId)) {
827 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000828 "You need MANAGE_USERS permission to: check if specified user a " +
829 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000830 }
831 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000832 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700833 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000834 UserInfo userInfo = getUserInfoLU(userId);
835 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700836 }
837 }
838
Amith Yamasani71e6c692013-03-24 17:39:28 -0700839 @Override
840 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700841 synchronized (mUsersLock) {
842 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700843 }
844 }
845
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700846 @Override
847 public boolean canHaveRestrictedProfile(int userId) {
848 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700849 synchronized (mUsersLock) {
850 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700851 if (userInfo == null || !userInfo.canHaveProfile()) {
852 return false;
853 }
854 if (!userInfo.isAdmin()) {
855 return false;
856 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800857 // restricted profile can be created if there is no DO set and the admin user has no PO;
858 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700859 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700860 }
861
Amith Yamasani195263742012-08-21 15:40:12 -0700862 /*
863 * Should be locked on mUsers before calling this.
864 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700865 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800866 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700867 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800868 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700869 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
870 return null;
871 }
Amith Yamasani12747872015-12-07 14:19:49 -0800872 return userData != null ? userData.info : null;
873 }
874
875 private UserData getUserDataLU(int userId) {
876 final UserData userData = mUsers.get(userId);
877 // If it is partial and not in the process of being removed, return as unknown user.
878 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
879 return null;
880 }
881 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700882 }
883
Fyodor Kupolov82402752015-10-28 14:54:51 -0700884 /**
885 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
886 * <p>No permissions checking or any addition checks are made</p>
887 */
888 private UserInfo getUserInfoNoChecks(int userId) {
889 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800890 final UserData userData = mUsers.get(userId);
891 return userData != null ? userData.info : null;
892 }
893 }
894
895 /**
896 * Obtains {@link #mUsersLock} and return UserData from mUsers.
897 * <p>No permissions checking or any addition checks are made</p>
898 */
899 private UserData getUserDataNoChecks(int userId) {
900 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700901 return mUsers.get(userId);
902 }
903 }
904
Amith Yamasani236b2b52015-08-18 14:32:14 -0700905 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700906 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700907 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700908 }
909
Amith Yamasani258848d2012-08-10 17:06:33 -0700910 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700911 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700912 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700913 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700914 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800915 UserData userData = getUserDataNoChecks(userId);
916 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700917 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
918 return;
919 }
Amith Yamasani12747872015-12-07 14:19:49 -0800920 if (name != null && !name.equals(userData.info.name)) {
921 userData.info.name = name;
922 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700923 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700924 }
925 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700926 if (changed) {
927 sendUserInfoChangedBroadcast(userId);
928 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700929 }
930
Amith Yamasani258848d2012-08-10 17:06:33 -0700931 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700932 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700933 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100934 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
935 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
936 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700937 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100938 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700939 }
940
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100941
942
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700943 private void sendUserInfoChangedBroadcast(int userId) {
944 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
945 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
946 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700947 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700948 }
949
Amith Yamasani258848d2012-08-10 17:06:33 -0700950 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100951 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100952 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700953 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100954 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
955 if (targetUserInfo == null || targetUserInfo.partial) {
956 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700957 return null;
958 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100959
960 final int callingUserId = UserHandle.getCallingUserId();
961 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
962 final int targetGroupId = targetUserInfo.profileGroupId;
963 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
964 && callingGroupId == targetGroupId);
965 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100966 checkManageUsersPermission("get the icon of a user who is not related");
967 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100968
969 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700970 return null;
971 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100972 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700973 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100974
975 try {
976 return ParcelFileDescriptor.open(
977 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
978 } catch (FileNotFoundException e) {
979 Log.e(LOG_TAG, "Couldn't find icon file", e);
980 }
981 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700982 }
983
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700984 public void makeInitialized(int userId) {
985 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800986 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800987 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800988 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800989 userData = mUsers.get(userId);
990 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700991 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800992 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700993 }
Amith Yamasani12747872015-12-07 14:19:49 -0800994 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
995 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800996 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700997 }
998 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800999 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -08001000 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001001 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001002 }
1003
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001004 /**
1005 * If default guest restrictions haven't been initialized yet, add the basic
1006 * restrictions.
1007 */
1008 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001009 synchronized (mGuestRestrictions) {
1010 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001011 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001012 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001013 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1014 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1015 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001016 }
1017 }
1018
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001019 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301020 public Bundle getDefaultGuestRestrictions() {
1021 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001022 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301023 return new Bundle(mGuestRestrictions);
1024 }
1025 }
1026
1027 @Override
1028 public void setDefaultGuestRestrictions(Bundle restrictions) {
1029 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001030 synchronized (mGuestRestrictions) {
1031 mGuestRestrictions.clear();
1032 mGuestRestrictions.putAll(restrictions);
1033 }
1034 synchronized (mPackagesLock) {
1035 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301036 }
1037 }
1038
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001039 /**
1040 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1041 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001042 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001043 @Nullable Bundle global) {
1044 Preconditions.checkNotNull(local);
1045 boolean globalChanged = false;
1046 boolean localChanged;
1047 synchronized (mRestrictionsLock) {
1048 if (global != null) {
1049 // Update global.
1050 globalChanged = !UserRestrictionsUtils.areEqual(
1051 mDevicePolicyGlobalUserRestrictions, global);
1052 if (globalChanged) {
1053 mDevicePolicyGlobalUserRestrictions = global;
1054 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001055 // Remember the global restriction owner userId to be able to make a distinction
1056 // in getUserRestrictionSource on who set local policies.
1057 mGlobalRestrictionOwnerUserId = userId;
1058 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001059 if (mGlobalRestrictionOwnerUserId == userId) {
1060 // When profile owner sets restrictions it passes null global bundle and we
1061 // reset global restriction owner userId.
1062 // This means this user used to have DO, but now the DO is gone and the user
1063 // instead has PO.
1064 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1065 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001066 }
1067 {
1068 // Update local.
1069 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1070 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1071 if (localChanged) {
1072 mDevicePolicyLocalUserRestrictions.put(userId, local);
1073 }
1074 }
1075 }
1076 if (DBG) {
1077 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1078 + " global=" + global + (globalChanged ? " (changed)" : "")
1079 + " local=" + local + (localChanged ? " (changed)" : "")
1080 );
1081 }
1082 // Don't call them within the mRestrictionsLock.
1083 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001084 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001085 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001086 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001087 if (globalChanged) {
1088 writeUserListLP();
1089 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001090 }
1091
1092 synchronized (mRestrictionsLock) {
1093 if (globalChanged) {
1094 applyUserRestrictionsForAllUsersLR();
1095 } else if (localChanged) {
1096 applyUserRestrictionsLR(userId);
1097 }
1098 }
1099 }
1100
Makoto Onuki068c54a2015-10-13 14:34:03 -07001101 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001102 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001103 final Bundle baseRestrictions =
1104 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1105 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1106 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001107
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001108 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1109 // Common case first.
1110 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001111 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001112 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1113 UserRestrictionsUtils.merge(effective, global);
1114 UserRestrictionsUtils.merge(effective, local);
1115
Makoto Onuki068c54a2015-10-13 14:34:03 -07001116 return effective;
1117 }
1118
1119 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001120 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001121 if (DBG) {
1122 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1123 }
1124 mCachedEffectiveUserRestrictions.remove(userId);
1125 }
1126
1127 private Bundle getEffectiveUserRestrictions(int userId) {
1128 synchronized (mRestrictionsLock) {
1129 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1130 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001131 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001132 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1133 }
1134 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001135 }
1136 }
1137
Makoto Onuki068c54a2015-10-13 14:34:03 -07001138 /** @return a specific user restriction that's in effect currently. */
1139 @Override
1140 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001141 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1142 return false;
1143 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001144 Bundle restrictions = getEffectiveUserRestrictions(userId);
1145 return restrictions != null && restrictions.getBoolean(restrictionKey);
1146 }
1147
1148 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001149 * @hide
1150 *
1151 * Returns who set a user restriction on a user.
1152 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1153 * @param restrictionKey the string key representing the restriction
1154 * @param userId the id of the user for whom to retrieve the restrictions.
1155 * @return The source of user restriction. Any combination of
1156 * {@link UserManager#RESTRICTION_NOT_SET},
1157 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1158 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1159 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1160 */
1161 @Override
1162 public int getUserRestrictionSource(String restrictionKey, int userId) {
1163 checkManageUsersPermission("getUserRestrictionSource");
1164 int result = UserManager.RESTRICTION_NOT_SET;
1165
1166 // Shortcut for the most common case
1167 if (!hasUserRestriction(restrictionKey, userId)) {
1168 return result;
1169 }
1170
1171 if (hasBaseUserRestriction(restrictionKey, userId)) {
1172 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1173 }
1174
1175 synchronized(mRestrictionsLock) {
1176 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1177 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1178 && localRestrictions.getBoolean(restrictionKey)) {
1179 // Local restrictions may have been set by device owner the userId of which is
1180 // stored in mGlobalRestrictionOwnerUserId.
1181 if (mGlobalRestrictionOwnerUserId == userId) {
1182 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1183 } else {
1184 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1185 }
1186 }
1187 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1188 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1189 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1190 }
1191 }
1192
1193 return result;
1194 }
1195
1196 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001197 * @return UserRestrictions that are in effect currently. This always returns a new
1198 * {@link Bundle}.
1199 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001200 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001201 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001202 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001203 }
1204
1205 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001206 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1207 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001208 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1209 return false;
1210 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001211 synchronized (mRestrictionsLock) {
1212 Bundle bundle = mBaseUserRestrictions.get(userId);
1213 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1214 }
1215 }
1216
1217 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001218 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001219 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001220 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1221 return;
1222 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001223 synchronized (mRestrictionsLock) {
1224 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1225 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001226 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1227 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001228 newRestrictions.putBoolean(key, value);
1229
Fyodor Kupolov82402752015-10-28 14:54:51 -07001230 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001231 }
1232 }
1233
Makoto Onuki068c54a2015-10-13 14:34:03 -07001234 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001235 * Optionally updating user restrictions, calculate the effective user restrictions and also
1236 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001237 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001238 * @param newRestrictions User restrictions to set.
1239 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001240 * @param userId target user ID.
1241 */
1242 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001243 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001244 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001245
1246 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1247 mAppliedUserRestrictions.get(userId));
1248
1249 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001250 if (newRestrictions != null) {
1251 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001252 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1253
1254 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001255 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1256 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001257
1258 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1259 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001260 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001261 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001262 }
1263
Fyodor Kupolov82402752015-10-28 14:54:51 -07001264 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001265
Makoto Onuki759a7632015-10-28 16:43:10 -07001266 mCachedEffectiveUserRestrictions.put(userId, effective);
1267
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001268 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001269 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001270 debug("Applying user restrictions: userId=" + userId
1271 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001272 }
1273
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001274 if (mAppOpsService != null) { // We skip it until system-ready.
1275 final long token = Binder.clearCallingIdentity();
1276 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001277 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001278 } catch (RemoteException e) {
1279 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1280 } finally {
1281 Binder.restoreCallingIdentity(token);
1282 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001283 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001284
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001285 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001286
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001287 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001288 }
1289
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001290 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001291 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001292 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1293 // actually, but we still need some kind of synchronization otherwise we might end up
1294 // calling listeners out-of-order, thus "LR".
1295
1296 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1297 return;
1298 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001299
1300 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1301 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1302
1303 mHandler.post(new Runnable() {
1304 @Override
1305 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001306 UserRestrictionsUtils.applyUserRestrictions(
1307 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001308
Makoto Onukid45a4a22015-11-02 17:17:38 -08001309 final UserRestrictionsListener[] listeners;
1310 synchronized (mUserRestrictionsListeners) {
1311 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1312 mUserRestrictionsListeners.toArray(listeners);
1313 }
1314 for (int i = 0; i < listeners.length; i++) {
1315 listeners[i].onUserRestrictionsChanged(userId,
1316 newRestrictionsFinal, prevRestrictionsFinal);
1317 }
1318 }
1319 });
1320 }
1321
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001322 // Package private for the inner class.
1323 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001324 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001325 }
1326
1327 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001328 // Package private for the inner class.
1329 void applyUserRestrictionsForAllUsersLR() {
1330 if (DBG) {
1331 debug("applyUserRestrictionsForAllUsersLR");
1332 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001333 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001334 mCachedEffectiveUserRestrictions.clear();
1335
Makoto Onuki068c54a2015-10-13 14:34:03 -07001336 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1337 // it on a handler.
1338 final Runnable r = new Runnable() {
1339 @Override
1340 public void run() {
1341 // Then get the list of running users.
1342 final int[] runningUsers;
1343 try {
1344 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1345 } catch (RemoteException e) {
1346 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1347 return;
1348 }
1349 // Then re-calculate the effective restrictions and apply, only for running users.
1350 // It's okay if a new user has started after the getRunningUserIds() call,
1351 // because we'll do the same thing (re-calculate the restrictions and apply)
1352 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001353 synchronized (mRestrictionsLock) {
1354 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001355 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001356 }
1357 }
1358 }
1359 };
1360 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001361 }
1362
Amith Yamasani258848d2012-08-10 17:06:33 -07001363 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001364 * Check if we've hit the limit of how many users can be created.
1365 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001366 private boolean isUserLimitReached() {
1367 int count;
1368 synchronized (mUsersLock) {
1369 count = getAliveUsersExcludingGuestsCountLU();
1370 }
1371 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001372 }
1373
1374 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001375 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001376 checkManageUsersPermission("check if more managed profiles can be added.");
1377 if (ActivityManager.isLowRamDeviceStatic()) {
1378 return false;
1379 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001380 if (!mContext.getPackageManager().hasSystemFeature(
1381 PackageManager.FEATURE_MANAGED_USERS)) {
1382 return false;
1383 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001384 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001385 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1386 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1387 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001388 return false;
1389 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001390 synchronized(mUsersLock) {
1391 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001392 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001393 return false;
1394 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001395 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1396 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001397 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001398 return usersCountAfterRemoving == 1
1399 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001400 }
1401 }
1402
Fyodor Kupolov82402752015-10-28 14:54:51 -07001403 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001404 int aliveUserCount = 0;
1405 final int totalUserCount = mUsers.size();
1406 // Skip over users being removed
1407 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001408 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001409 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001410 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001411 aliveUserCount++;
1412 }
1413 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001414 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001415 }
1416
1417 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001418 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001419 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1420 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1421 * permissions can make certain calls to the UserManager.
1422 *
1423 * @param message used as message if SecurityException is thrown
1424 * @throws SecurityException if the caller does not have enough privilege.
1425 */
1426 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1427 final int uid = Binder.getCallingUid();
1428 if (uid != Process.SYSTEM_UID && uid != 0
1429 && ActivityManager.checkComponentPermission(
1430 Manifest.permission.MANAGE_USERS,
1431 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1432 && ActivityManager.checkComponentPermission(
1433 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1434 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1435 throw new SecurityException(
1436 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1437 + message);
1438 }
1439 }
1440
1441 /**
1442 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001443 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001444 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001445 *
1446 * @param message used as message if SecurityException is thrown
1447 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001448 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001449 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001450 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001451 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001452 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1453 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001454 }
1455
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001456 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001457 * Enforces that only the system UID or root's UID or apps that have the
1458 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1459 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
1460 * can make certain calls to the UserManager.
1461 *
1462 * @param message used as message if SecurityException is thrown
1463 * @throws SecurityException if the caller is not system or root
1464 * @see #hasManageOrCreateUsersPermission()
1465 */
1466 private static final void checkManageOrCreateUsersPermission(String message) {
1467 if (!hasManageOrCreateUsersPermission()) {
1468 throw new SecurityException(
1469 "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
1470 }
1471 }
1472
1473 /**
1474 * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
1475 * to create user/profiles other than what is allowed for
1476 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
1477 * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
1478 */
1479 private static final void checkManageOrCreateUsersPermission(int creationFlags) {
1480 if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
1481 if (!hasManageOrCreateUsersPermission()) {
1482 throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
1483 + "permission to create an user with flags: " + creationFlags);
1484 }
1485 } else if (!hasManageUsersPermission()) {
1486 throw new SecurityException("You need MANAGE_USERS permission to create an user "
1487 + " with flags: " + creationFlags);
1488 }
1489 }
1490
1491 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001492 * @return whether the calling UID is system UID or root's UID or the calling app has the
1493 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1494 */
1495 private static final boolean hasManageUsersPermission() {
1496 final int callingUid = Binder.getCallingUid();
1497 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1498 || callingUid == Process.ROOT_UID
1499 || ActivityManager.checkComponentPermission(
1500 android.Manifest.permission.MANAGE_USERS,
1501 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1502 }
1503
1504 /**
Sudheer Shankaf5cea032016-06-08 17:13:24 -07001505 * @return whether the calling UID is system UID or root's UID or the calling app has the
1506 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
1507 * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
1508 */
1509 private static final boolean hasManageOrCreateUsersPermission() {
1510 final int callingUid = Binder.getCallingUid();
1511 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1512 || callingUid == Process.ROOT_UID
1513 || ActivityManager.checkComponentPermission(
1514 android.Manifest.permission.MANAGE_USERS,
1515 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
1516 || ActivityManager.checkComponentPermission(
1517 android.Manifest.permission.CREATE_USERS,
1518 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1519 }
1520
1521 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001522 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1523 * UserManager.
1524 *
1525 * @param message used as message if SecurityException is thrown
1526 * @throws SecurityException if the caller is not system or root
1527 */
1528 private static void checkSystemOrRoot(String message) {
1529 final int uid = Binder.getCallingUid();
1530 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1531 throw new SecurityException("Only system may: " + message);
1532 }
1533 }
1534
Fyodor Kupolov82402752015-10-28 14:54:51 -07001535 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001536 try {
1537 File dir = new File(mUsersDir, Integer.toString(info.id));
1538 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001539 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001540 if (!dir.exists()) {
1541 dir.mkdir();
1542 FileUtils.setPermissions(
1543 dir.getPath(),
1544 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1545 -1, -1);
1546 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001547 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001548 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001549 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001550 info.iconPath = file.getAbsolutePath();
1551 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001552 try {
1553 os.close();
1554 } catch (IOException ioe) {
1555 // What the ... !
1556 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001557 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001558 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001559 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001560 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001561 }
1562
Amith Yamasani0b285492011-04-14 17:35:23 -07001563 /**
1564 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1565 * cache it elsewhere.
1566 * @return the array of user ids.
1567 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001568 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001569 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001570 return mUserIds;
1571 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001572 }
1573
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001574 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001575 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001576 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001577 return;
1578 }
1579 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001580 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001581 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001582 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001583 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001584 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001585 int type;
1586 while ((type = parser.next()) != XmlPullParser.START_TAG
1587 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001588 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001589 }
1590
1591 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001592 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001593 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001594 return;
1595 }
1596
Amith Yamasani2a003292012-08-14 18:25:45 -07001597 mNextSerialNumber = -1;
1598 if (parser.getName().equals(TAG_USERS)) {
1599 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1600 if (lastSerialNumber != null) {
1601 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1602 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001603 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1604 if (versionNumber != null) {
1605 mUserVersion = Integer.parseInt(versionNumber);
1606 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001607 }
1608
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001609 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1610
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001611 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301612 if (type == XmlPullParser.START_TAG) {
1613 final String name = parser.getName();
1614 if (name.equals(TAG_USER)) {
1615 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001616
Amith Yamasani12747872015-12-07 14:19:49 -08001617 UserData userData = readUserLP(Integer.parseInt(id));
1618
1619 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001620 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001621 mUsers.put(userData.info.id, userData);
1622 if (mNextSerialNumber < 0
1623 || mNextSerialNumber <= userData.info.id) {
1624 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001625 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301626 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001627 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301628 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001629 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1630 && type != XmlPullParser.END_TAG) {
1631 if (type == XmlPullParser.START_TAG) {
1632 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001633 synchronized (mGuestRestrictions) {
1634 UserRestrictionsUtils
1635 .readRestrictions(parser, mGuestRestrictions);
1636 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001637 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1638 ) {
1639 UserRestrictionsUtils.readRestrictions(parser,
1640 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001641 }
1642 break;
1643 }
1644 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001645 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1646 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1647 if (ownerUserId != null) {
1648 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1649 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001650 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001651 }
1652 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 synchronized (mRestrictionsLock) {
1654 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1655 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001656 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001657 upgradeIfNecessaryLP();
1658 } catch (IOException | XmlPullParserException e) {
1659 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001660 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001661 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662 }
1663 }
1664
Amith Yamasani6f34b412012-10-22 18:19:27 -07001665 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001666 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001667 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001668 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001669 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001670 int userVersion = mUserVersion;
1671 if (userVersion < 1) {
1672 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001673 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1674 if ("Primary".equals(userData.info.name)) {
1675 userData.info.name =
1676 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1677 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001678 }
1679 userVersion = 1;
1680 }
1681
Amith Yamasanibc9625052012-11-15 14:39:18 -08001682 if (userVersion < 2) {
1683 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001684 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1685 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1686 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1687 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001688 }
1689 userVersion = 2;
1690 }
1691
Amith Yamasani350962c2013-08-06 11:18:53 -07001692
Amith Yamasani5e486f52013-08-07 11:06:44 -07001693 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001694 userVersion = 4;
1695 }
1696
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001697 if (userVersion < 5) {
1698 initDefaultGuestRestrictions();
1699 userVersion = 5;
1700 }
1701
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001702 if (userVersion < 6) {
1703 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001704 synchronized (mUsersLock) {
1705 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001706 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001707 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001708 if (!splitSystemUser && userData.info.isRestricted()
1709 && (userData.info.restrictedProfileParentId
1710 == UserInfo.NO_PROFILE_GROUP_ID)) {
1711 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1712 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001713 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001714 }
1715 }
1716 userVersion = 6;
1717 }
1718
Amith Yamasani6f34b412012-10-22 18:19:27 -07001719 if (userVersion < USER_VERSION) {
1720 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1721 + USER_VERSION);
1722 } else {
1723 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001724
1725 if (originalVersion < mUserVersion) {
1726 writeUserListLP();
1727 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001728 }
1729 }
1730
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001731 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001732 int flags = UserInfo.FLAG_INITIALIZED;
1733 // In split system user mode, the admin and primary flags are assigned to the first human
1734 // user.
1735 if (!UserManager.isSplitSystemUser()) {
1736 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1737 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001738 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001739 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001740 UserData userData = new UserData();
1741 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001742 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001743 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001744 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001745 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001746 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001747
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001748 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001749 synchronized (mRestrictionsLock) {
1750 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1751 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001752
Fyodor Kupolov82402752015-10-28 14:54:51 -07001753 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001754 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001755
Amith Yamasani12747872015-12-07 14:19:49 -08001756 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001757 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001758 }
1759
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001760 private String getOwnerName() {
1761 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1762 }
1763
Amith Yamasani12747872015-12-07 14:19:49 -08001764 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001765 if (DBG) {
1766 debug("scheduleWriteUser");
1767 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001768 // No need to wrap it within a lock -- worst case, we'll just post the same message
1769 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001770 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1771 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001772 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1773 }
1774 }
1775
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001776 /*
1777 * Writes the user file in this format:
1778 *
1779 * <user flags="20039023" id="0">
1780 * <name>Primary</name>
1781 * </user>
1782 */
Amith Yamasani12747872015-12-07 14:19:49 -08001783 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001784 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001785 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001786 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001787 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001788 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001789 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001790 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001791 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1792
1793 // XmlSerializer serializer = XmlUtils.serializerInstance();
1794 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001795 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001796 serializer.startDocument(null, true);
1797 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1798
Amith Yamasani12747872015-12-07 14:19:49 -08001799 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001800 serializer.startTag(null, TAG_USER);
1801 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001802 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001803 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001804 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1805 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1806 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001807 if (userInfo.lastLoggedInFingerprint != null) {
1808 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1809 userInfo.lastLoggedInFingerprint);
1810 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001811 if (userInfo.iconPath != null) {
1812 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1813 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001814 if (userInfo.partial) {
1815 serializer.attribute(null, ATTR_PARTIAL, "true");
1816 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001817 if (userInfo.guestToRemove) {
1818 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1819 }
Kenny Guy2a764942014-04-02 13:29:20 +01001820 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1821 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1822 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001823 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001824 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1825 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1826 Integer.toString(userInfo.restrictedProfileParentId));
1827 }
Amith Yamasani12747872015-12-07 14:19:49 -08001828 // Write seed data
1829 if (userData.persistSeedData) {
1830 if (userData.seedAccountName != null) {
1831 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1832 }
1833 if (userData.seedAccountType != null) {
1834 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1835 }
1836 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001837 if (userInfo.name != null) {
1838 serializer.startTag(null, TAG_NAME);
1839 serializer.text(userInfo.name);
1840 serializer.endTag(null, TAG_NAME);
1841 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001842 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001843 UserRestrictionsUtils.writeRestrictions(serializer,
1844 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1845 UserRestrictionsUtils.writeRestrictions(serializer,
1846 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1847 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001848 }
Amith Yamasani12747872015-12-07 14:19:49 -08001849
1850 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001851 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001852 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001853 serializer.endTag(null, TAG_ACCOUNT);
1854 }
1855
Amith Yamasani12747872015-12-07 14:19:49 -08001856 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1857 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1858 userData.seedAccountOptions.saveToXml(serializer);
1859 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1860 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001861 serializer.endTag(null, TAG_USER);
1862
1863 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001864 userFile.finishWrite(fos);
1865 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001866 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001867 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001868 }
1869 }
1870
1871 /*
1872 * Writes the user list file in this format:
1873 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001874 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001875 * <user id="0"></user>
1876 * <user id="2"></user>
1877 * </users>
1878 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001879 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001880 if (DBG) {
1881 debug("writeUserList");
1882 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001883 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001884 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001885 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001886 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001887 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1888
1889 // XmlSerializer serializer = XmlUtils.serializerInstance();
1890 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001891 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001892 serializer.startDocument(null, true);
1893 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1894
1895 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001896 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001897 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001898
Adam Lesinskieddeb492014-09-08 17:50:03 -07001899 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001900 synchronized (mGuestRestrictions) {
1901 UserRestrictionsUtils
1902 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1903 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301904 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001905 synchronized (mRestrictionsLock) {
1906 UserRestrictionsUtils.writeRestrictions(serializer,
1907 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1908 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001909 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1910 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1911 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001912 int[] userIdsToWrite;
1913 synchronized (mUsersLock) {
1914 userIdsToWrite = new int[mUsers.size()];
1915 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001916 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001917 userIdsToWrite[i] = user.id;
1918 }
1919 }
1920 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001921 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001922 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001923 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001924 }
1925
1926 serializer.endTag(null, TAG_USERS);
1927
1928 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001929 userListFile.finishWrite(fos);
1930 } catch (Exception e) {
1931 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001932 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001933 }
1934 }
1935
Amith Yamasani12747872015-12-07 14:19:49 -08001936 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001937 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001938 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001939 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001940 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001941 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001942 long creationTime = 0L;
1943 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001944 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001945 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001946 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001947 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001948 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001949 boolean persistSeedData = false;
1950 String seedAccountName = null;
1951 String seedAccountType = null;
1952 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001953 Bundle baseRestrictions = new Bundle();
1954 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001955
1956 FileInputStream fis = null;
1957 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001958 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001959 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001960 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001961 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001962 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001963 int type;
1964 while ((type = parser.next()) != XmlPullParser.START_TAG
1965 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001966 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001967 }
1968
1969 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001970 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001971 return null;
1972 }
1973
1974 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001975 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1976 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001977 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001978 return null;
1979 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001980 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1981 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001982 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001983 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1984 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001985 lastLoggedInFingerprint = parser.getAttributeValue(null,
1986 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001987 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1988 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001989 restrictedProfileParentId = readIntAttribute(parser,
1990 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001991 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1992 if ("true".equals(valueString)) {
1993 partial = true;
1994 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001995 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1996 if ("true".equals(valueString)) {
1997 guestToRemove = true;
1998 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001999
Amith Yamasani12747872015-12-07 14:19:49 -08002000 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
2001 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
2002 if (seedAccountName != null || seedAccountType != null) {
2003 persistSeedData = true;
2004 }
2005
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002006 int outerDepth = parser.getDepth();
2007 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2008 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2009 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2010 continue;
2011 }
2012 String tag = parser.getName();
2013 if (TAG_NAME.equals(tag)) {
2014 type = parser.next();
2015 if (type == XmlPullParser.TEXT) {
2016 name = parser.getText();
2017 }
2018 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002019 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
2020 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
2021 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002022 } else if (TAG_ACCOUNT.equals(tag)) {
2023 type = parser.next();
2024 if (type == XmlPullParser.TEXT) {
2025 account = parser.getText();
2026 }
Amith Yamasani12747872015-12-07 14:19:49 -08002027 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
2028 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
2029 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002030 }
2031 }
2032 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002033
Amith Yamasani12747872015-12-07 14:19:49 -08002034 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07002035 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07002036 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07002037 userInfo.creationTime = creationTime;
2038 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002039 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002040 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07002041 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01002042 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002043 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08002044
2045 // Create the UserData object that's internal to this class
2046 UserData userData = new UserData();
2047 userData.info = userInfo;
2048 userData.account = account;
2049 userData.seedAccountName = seedAccountName;
2050 userData.seedAccountType = seedAccountType;
2051 userData.persistSeedData = persistSeedData;
2052 userData.seedAccountOptions = seedAccountOptions;
2053
Makoto Onuki068c54a2015-10-13 14:34:03 -07002054 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002055 mBaseUserRestrictions.put(id, baseRestrictions);
2056 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002057 }
Amith Yamasani12747872015-12-07 14:19:49 -08002058 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002059 } catch (IOException ioe) {
2060 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002061 } finally {
2062 if (fis != null) {
2063 try {
2064 fis.close();
2065 } catch (IOException e) {
2066 }
2067 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002068 }
2069 return null;
2070 }
2071
Amith Yamasani920ace02012-09-20 22:15:37 -07002072 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2073 String valueString = parser.getAttributeValue(null, attr);
2074 if (valueString == null) return defaultValue;
2075 try {
2076 return Integer.parseInt(valueString);
2077 } catch (NumberFormatException nfe) {
2078 return defaultValue;
2079 }
2080 }
2081
2082 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2083 String valueString = parser.getAttributeValue(null, attr);
2084 if (valueString == null) return defaultValue;
2085 try {
2086 return Long.parseLong(valueString);
2087 } catch (NumberFormatException nfe) {
2088 return defaultValue;
2089 }
2090 }
2091
Amith Yamasanib82add22013-07-09 11:24:44 -07002092 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002093 * Removes the app restrictions file for a specific package and user id, if it exists.
2094 */
2095 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2096 synchronized (mPackagesLock) {
2097 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002098 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002099 if (resFile.exists()) {
2100 resFile.delete();
2101 }
2102 }
2103 }
2104
Kenny Guya52dc3e2014-02-11 15:33:14 +00002105 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002106 public UserInfo createProfileForUser(String name, int flags, int userId) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002107 checkManageOrCreateUsersPermission(flags);
Kenny Guy2a764942014-04-02 13:29:20 +01002108 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002109 }
2110
Amith Yamasani258848d2012-08-10 17:06:33 -07002111 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002112 public UserInfo createUser(String name, int flags) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002113 checkManageOrCreateUsersPermission(flags);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002114 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002115 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002116
Jessica Hummelbe81c802014-04-22 15:49:22 +01002117 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002118 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002119 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2120 return null;
2121 }
phweisse9c44062016-02-10 12:57:38 +01002122 return createUserInternalUnchecked(name, flags, parentId);
2123 }
2124
2125 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002126 if (ActivityManager.isLowRamDeviceStatic()) {
2127 return null;
2128 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002129 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002130 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002131 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002132 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002133 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002134 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002135 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002136 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002137 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002138 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002139 if (parentId != UserHandle.USER_NULL) {
2140 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002141 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002142 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002143 if (parent == null) return null;
2144 }
2145 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2146 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2147 return null;
2148 }
2149 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
2150 // If we're not adding a guest user or a managed profile and the limit has
2151 // been reached, cannot add a user.
2152 return null;
2153 }
2154 // If we're adding a guest and there already exists one, bail.
2155 if (isGuest && findCurrentGuestUser() != null) {
2156 return null;
2157 }
2158 // In legacy mode, restricted profile's parent can only be the owner user
2159 if (isRestricted && !UserManager.isSplitSystemUser()
2160 && (parentId != UserHandle.USER_SYSTEM)) {
2161 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2162 return null;
2163 }
2164 if (isRestricted && UserManager.isSplitSystemUser()) {
2165 if (parent == null) {
2166 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2167 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002168 return null;
2169 }
Amith Yamasani12747872015-12-07 14:19:49 -08002170 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002171 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2172 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002173 return null;
2174 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002175 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01002176 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
2177 Log.e(LOG_TAG,
2178 "Ephemeral users are supported on split-system-user systems only.");
2179 return null;
2180 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002181 // In split system user mode, we assign the first human user the primary flag.
2182 // And if there is no device owner, we also assign the admin flag to primary user.
2183 if (UserManager.isSplitSystemUser()
2184 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2185 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002186 synchronized (mUsersLock) {
2187 if (!mIsDeviceManaged) {
2188 flags |= UserInfo.FLAG_ADMIN;
2189 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002190 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002191 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002192
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002193 userId = getNextAvailableId();
2194 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002195 boolean ephemeralGuests = Resources.getSystem()
2196 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002197
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002198 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002199 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2200 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2201 || (parent != null && parent.info.isEphemeral())) {
2202 flags |= UserInfo.FLAG_EPHEMERAL;
2203 }
2204
2205 userInfo = new UserInfo(userId, name, null, flags);
2206 userInfo.serialNumber = mNextSerialNumber++;
2207 long now = System.currentTimeMillis();
2208 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2209 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002210 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002211 userData = new UserData();
2212 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002213 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002214 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002215 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002216 writeUserListLP();
2217 if (parent != null) {
2218 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002219 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2220 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002221 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002222 }
Amith Yamasani12747872015-12-07 14:19:49 -08002223 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002224 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002225 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2226 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002227 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002228 }
Amith Yamasani12747872015-12-07 14:19:49 -08002229 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002230 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002231 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002232 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002233 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002234 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002235 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002236 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002237 mPm.createNewUser(userId);
2238 userInfo.partial = false;
2239 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002240 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002241 }
2242 updateUserIds();
2243 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002244 if (isGuest) {
2245 synchronized (mGuestRestrictions) {
2246 restrictions.putAll(mGuestRestrictions);
2247 }
2248 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002249 synchronized (mRestrictionsLock) {
2250 mBaseUserRestrictions.append(userId, restrictions);
2251 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002252 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2253 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2254 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2255 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002256 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002257 } finally {
2258 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002259 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002260 return userInfo;
2261 }
2262
Amith Yamasani0b285492011-04-14 17:35:23 -07002263 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002264 * @hide
2265 */
Amith Yamasani12747872015-12-07 14:19:49 -08002266 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002267 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2268 checkManageUsersPermission("setupRestrictedProfile");
2269 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2270 if (user == null) {
2271 return null;
2272 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002273 long identity = Binder.clearCallingIdentity();
2274 try {
2275 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2276 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2277 // the putIntForUser() will fail.
2278 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2279 android.provider.Settings.Secure.LOCATION_MODE,
2280 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2281 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2282 } finally {
2283 Binder.restoreCallingIdentity(identity);
2284 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002285 return user;
2286 }
2287
2288 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002289 * Find the current guest user. If the Guest user is partial,
2290 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002291 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002292 private UserInfo findCurrentGuestUser() {
2293 synchronized (mUsersLock) {
2294 final int size = mUsers.size();
2295 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002296 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002297 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2298 return user;
2299 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002300 }
2301 }
2302 return null;
2303 }
2304
2305 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002306 * Mark this guest user for deletion to allow us to create another guest
2307 * and switch to that user before actually removing this guest.
2308 * @param userHandle the userid of the current guest
2309 * @return whether the user could be marked for deletion
2310 */
Amith Yamasani12747872015-12-07 14:19:49 -08002311 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002312 public boolean markGuestForDeletion(int userHandle) {
2313 checkManageUsersPermission("Only the system can remove users");
2314 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2315 UserManager.DISALLOW_REMOVE_USER, false)) {
2316 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2317 return false;
2318 }
2319
2320 long ident = Binder.clearCallingIdentity();
2321 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002322 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002323 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002324 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002325 userData = mUsers.get(userHandle);
2326 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002327 return false;
2328 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002329 }
Amith Yamasani12747872015-12-07 14:19:49 -08002330 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002331 return false;
2332 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002333 // We set this to a guest user that is to be removed. This is a temporary state
2334 // where we are allowed to add new Guest users, even if this one is still not
2335 // removed. This user will still show up in getUserInfo() calls.
2336 // If we don't get around to removing this Guest user, it will be purged on next
2337 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002338 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002339 // Mark it as disabled, so that it isn't returned any more when
2340 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002341 userData.info.flags |= UserInfo.FLAG_DISABLED;
2342 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002343 }
2344 } finally {
2345 Binder.restoreCallingIdentity(ident);
2346 }
2347 return true;
2348 }
2349
2350 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002351 * Removes a user and all data directories created for that user. This method should be called
2352 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002353 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002354 */
Amith Yamasani12747872015-12-07 14:19:49 -08002355 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002356 public boolean removeUser(int userHandle) {
Sudheer Shankaf5cea032016-06-08 17:13:24 -07002357 checkManageOrCreateUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002358 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2359 UserManager.DISALLOW_REMOVE_USER, false)) {
2360 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2361 return false;
2362 }
2363
Kenny Guyee58b4f2014-05-23 15:19:53 +01002364 long ident = Binder.clearCallingIdentity();
2365 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002366 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002367 int currentUser = ActivityManager.getCurrentUser();
2368 if (currentUser == userHandle) {
2369 Log.w(LOG_TAG, "Current user cannot be removed");
2370 return false;
2371 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002372 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002373 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002374 userData = mUsers.get(userHandle);
2375 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002376 return false;
2377 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002378
Fyodor Kupolov82402752015-10-28 14:54:51 -07002379 // We remember deleted user IDs to prevent them from being
2380 // reused during the current boot; they can still be reused
2381 // after a reboot.
2382 mRemovingUserIds.put(userHandle, true);
2383 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002384
Kenny Guyee58b4f2014-05-23 15:19:53 +01002385 try {
2386 mAppOpsService.removeUser(userHandle);
2387 } catch (RemoteException e) {
2388 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2389 }
2390 // Set this to a partially created user, so that the user will be purged
2391 // on next startup, in case the runtime stops now before stopping and
2392 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002393 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002394 // Mark it as disabled, so that it isn't returned any more when
2395 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002396 userData.info.flags |= UserInfo.FLAG_DISABLED;
2397 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002398 }
2399
Amith Yamasani12747872015-12-07 14:19:49 -08002400 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2401 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002402 // Send broadcast to notify system that the user removed was a
2403 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002404 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002405 }
2406
2407 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2408 int res;
2409 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002410 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2411 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002412 @Override
2413 public void userStopped(int userId) {
2414 finishRemoveUser(userId);
2415 }
2416 @Override
2417 public void userStopAborted(int userId) {
2418 }
2419 });
2420 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002421 return false;
2422 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002423 return res == ActivityManager.USER_OP_SUCCESS;
2424 } finally {
2425 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002426 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002427 }
2428
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002429 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002430 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002431 // Let other services shutdown any activity and clean up their state before completely
2432 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002433 long ident = Binder.clearCallingIdentity();
2434 try {
2435 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2436 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002437 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2438 android.Manifest.permission.MANAGE_USERS,
2439
2440 new BroadcastReceiver() {
2441 @Override
2442 public void onReceive(Context context, Intent intent) {
2443 if (DBG) {
2444 Slog.i(LOG_TAG,
2445 "USER_REMOVED broadcast sent, cleaning up user data "
2446 + userHandle);
2447 }
2448 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002449 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002450 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002451 // Clean up any ActivityManager state
2452 LocalServices.getService(ActivityManagerInternal.class)
2453 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002454 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002455 }
2456 }.start();
2457 }
2458 },
2459
2460 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002461 } finally {
2462 Binder.restoreCallingIdentity(ident);
2463 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002464 }
2465
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002466 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002467 try {
2468 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2469 } catch (IllegalStateException e) {
2470 // This may be simply because the user was partially created.
2471 Slog.i(LOG_TAG,
2472 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2473 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002474
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002475 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002476 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002477 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002478 synchronized (mUsersLock) {
2479 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002480 mIsUserManaged.delete(userHandle);
Fyodor Kupolovac06a492016-05-25 14:45:29 -07002481 }
2482 synchronized (mUserStates) {
2483 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002484 }
2485 synchronized (mRestrictionsLock) {
2486 mBaseUserRestrictions.remove(userHandle);
2487 mAppliedUserRestrictions.remove(userHandle);
2488 mCachedEffectiveUserRestrictions.remove(userHandle);
2489 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002490 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002491 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002492 synchronized (mPackagesLock) {
2493 writeUserListLP();
2494 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002495 // Remove user file
2496 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2497 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002498 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002499
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002500 // Now that we've purged all the metadata above, destroy the actual data
2501 // on disk; if we battery pull in here we'll finish cleaning up when
2502 // reconciling after reboot.
2503 mPm.destroyUserData(userHandle,
2504 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Amith Yamasani61f57372012-08-31 12:12:28 -07002505 }
2506
Kenny Guyf8d3a232014-05-15 16:09:52 +01002507 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002508 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002509 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2510 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002511 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002512 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002513 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002514 }
2515
Amith Yamasani2a003292012-08-14 18:25:45 -07002516 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002517 public Bundle getApplicationRestrictions(String packageName) {
2518 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2519 }
2520
2521 @Override
2522 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002523 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002524 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002525 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002526 }
2527 synchronized (mPackagesLock) {
2528 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002529 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002530 }
2531 }
2532
2533 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002534 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002535 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002536 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002537 if (restrictions != null) {
2538 restrictions.setDefusable(true);
2539 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002540 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002541 if (restrictions == null || restrictions.isEmpty()) {
2542 cleanAppRestrictionsForPackage(packageName, userId);
2543 } else {
2544 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002545 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002546 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002547 }
Robin Lee66e5d962014-04-09 16:44:21 +01002548
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002549 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2550 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2551 changeIntent.setPackage(packageName);
2552 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2553 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002554 }
2555
2556 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002557 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002558 try {
2559 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002560 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002561 } catch (NameNotFoundException nnfe) {
2562 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002563 } finally {
2564 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002565 }
2566 }
2567
Fyodor Kupolov82402752015-10-28 14:54:51 -07002568 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002569 AtomicFile restrictionsFile =
2570 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2571 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002572 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002573 }
2574
2575 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002576 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002577 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002578 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002579 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002580 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002581 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002582
2583 FileInputStream fis = null;
2584 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002585 fis = restrictionsFile.openRead();
2586 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002587 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002588 XmlUtils.nextElement(parser);
2589 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002590 Slog.e(LOG_TAG, "Unable to read restrictions file "
2591 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002592 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002593 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002594 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2595 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002596 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002597 } catch (IOException|XmlPullParserException e) {
2598 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002599 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002600 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002601 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002602 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002603 }
2604
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002605 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2606 XmlPullParser parser) throws XmlPullParserException, IOException {
2607 int type = parser.getEventType();
2608 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2609 String key = parser.getAttributeValue(null, ATTR_KEY);
2610 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2611 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2612 if (multiple != null) {
2613 values.clear();
2614 int count = Integer.parseInt(multiple);
2615 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2616 if (type == XmlPullParser.START_TAG
2617 && parser.getName().equals(TAG_VALUE)) {
2618 values.add(parser.nextText().trim());
2619 count--;
2620 }
2621 }
2622 String [] valueStrings = new String[values.size()];
2623 values.toArray(valueStrings);
2624 restrictions.putStringArray(key, valueStrings);
2625 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2626 restrictions.putBundle(key, readBundleEntry(parser, values));
2627 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2628 final int outerDepth = parser.getDepth();
2629 ArrayList<Bundle> bundleList = new ArrayList<>();
2630 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2631 Bundle childBundle = readBundleEntry(parser, values);
2632 bundleList.add(childBundle);
2633 }
2634 restrictions.putParcelableArray(key,
2635 bundleList.toArray(new Bundle[bundleList.size()]));
2636 } else {
2637 String value = parser.nextText().trim();
2638 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2639 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2640 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2641 restrictions.putInt(key, Integer.parseInt(value));
2642 } else {
2643 restrictions.putString(key, value);
2644 }
2645 }
2646 }
2647 }
2648
2649 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2650 throws IOException, XmlPullParserException {
2651 Bundle childBundle = new Bundle();
2652 final int outerDepth = parser.getDepth();
2653 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2654 readEntry(childBundle, values, parser);
2655 }
2656 return childBundle;
2657 }
2658
Fyodor Kupolov82402752015-10-28 14:54:51 -07002659 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002660 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002661 AtomicFile restrictionsFile = new AtomicFile(
2662 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002663 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002664 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002665 }
2666
2667 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002668 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002669 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002670 try {
2671 fos = restrictionsFile.startWrite();
2672 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2673
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002674 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002675 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002676 serializer.startDocument(null, true);
2677 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2678
2679 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002680 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002681 serializer.endTag(null, TAG_RESTRICTIONS);
2682
2683 serializer.endDocument();
2684 restrictionsFile.finishWrite(fos);
2685 } catch (Exception e) {
2686 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002687 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2688 }
2689 }
2690
2691 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2692 throws IOException {
2693 for (String key : restrictions.keySet()) {
2694 Object value = restrictions.get(key);
2695 serializer.startTag(null, TAG_ENTRY);
2696 serializer.attribute(null, ATTR_KEY, key);
2697
2698 if (value instanceof Boolean) {
2699 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2700 serializer.text(value.toString());
2701 } else if (value instanceof Integer) {
2702 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2703 serializer.text(value.toString());
2704 } else if (value == null || value instanceof String) {
2705 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2706 serializer.text(value != null ? (String) value : "");
2707 } else if (value instanceof Bundle) {
2708 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2709 writeBundle((Bundle) value, serializer);
2710 } else if (value instanceof Parcelable[]) {
2711 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2712 Parcelable[] array = (Parcelable[]) value;
2713 for (Parcelable parcelable : array) {
2714 if (!(parcelable instanceof Bundle)) {
2715 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2716 }
2717 serializer.startTag(null, TAG_ENTRY);
2718 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2719 writeBundle((Bundle) parcelable, serializer);
2720 serializer.endTag(null, TAG_ENTRY);
2721 }
2722 } else {
2723 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2724 String[] values = (String[]) value;
2725 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2726 for (String choice : values) {
2727 serializer.startTag(null, TAG_VALUE);
2728 serializer.text(choice != null ? choice : "");
2729 serializer.endTag(null, TAG_VALUE);
2730 }
2731 }
2732 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002733 }
2734 }
2735
2736 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002737 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002738 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002739 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002740 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002741 }
2742 }
2743
2744 @Override
2745 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002746 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002747 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002748 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002749 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002750 }
2751 // Not found
2752 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002753 }
2754 }
2755
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002756 @Override
2757 public long getUserCreationTime(int userHandle) {
2758 int callingUserId = UserHandle.getCallingUserId();
2759 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002760 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002761 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002762 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002763 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002764 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002765 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002766 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002767 }
2768 }
2769 }
2770 if (userInfo == null) {
2771 throw new SecurityException("userHandle can only be the calling user or a managed "
2772 + "profile associated with this user");
2773 }
2774 return userInfo.creationTime;
2775 }
2776
Amith Yamasani0b285492011-04-14 17:35:23 -07002777 /**
2778 * Caches the list of user ids in an array, adjusting the array size when necessary.
2779 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002780 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002781 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002782 synchronized (mUsersLock) {
2783 final int userSize = mUsers.size();
2784 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002785 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002786 num++;
2787 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002788 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002789 final int[] newUsers = new int[num];
2790 int n = 0;
2791 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002792 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002793 newUsers[n++] = mUsers.keyAt(i);
2794 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002795 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002796 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002797 }
2798 }
2799
2800 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002801 * Called right before a user is started. This gives us a chance to prepare
2802 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002803 */
2804 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002805 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002806 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002807 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002808
2809 if (userId != UserHandle.USER_SYSTEM) {
2810 synchronized (mRestrictionsLock) {
2811 applyUserRestrictionsLR(userId);
2812 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002813 UserInfo userInfo = getUserInfoNoChecks(userId);
2814 if (userInfo != null && !userInfo.isInitialized()) {
2815 mPm.onBeforeUserStartUninitialized(userId);
2816 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002817 }
2818 }
2819
2820 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002821 * Called right before a user is unlocked. This gives us a chance to prepare
2822 * app storage.
2823 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002824 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002825 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002826 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002827 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002828 }
2829
2830 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002831 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002832 * @param userId the user that was just foregrounded
2833 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002834 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002835 UserData userData = getUserDataNoChecks(userId);
2836 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002837 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2838 return;
2839 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002840
2841 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002842 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002843 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002844 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002845 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2846 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002847 }
2848
2849 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002850 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002851 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2852 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002853 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002854 private int getNextAvailableId() {
2855 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002856 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002857 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002858 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002859 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002860 }
2861 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002862 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002863 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002864 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002865 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002866
Amith Yamasanifc95e702013-09-26 13:20:17 -07002867 private String packageToRestrictionsFileName(String packageName) {
2868 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2869 }
2870
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002871 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002872 * Enforce that serial number stored in user directory inode matches the
2873 * given expected value. Gracefully sets the serial number if currently
2874 * undefined.
2875 *
2876 * @throws IOException when problem extracting serial number, or serial
2877 * number is mismatched.
2878 */
2879 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2880 final int foundSerial = getSerialNumber(file);
2881 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2882
2883 if (foundSerial == -1) {
2884 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2885 try {
2886 setSerialNumber(file, serialNumber);
2887 } catch (IOException e) {
2888 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2889 }
2890
2891 } else if (foundSerial != serialNumber) {
2892 throw new IOException("Found serial number " + foundSerial
2893 + " doesn't match expected " + serialNumber);
2894 }
2895 }
2896
2897 /**
2898 * Set serial number stored in user directory inode.
2899 *
2900 * @throws IOException if serial number was already set
2901 */
2902 private static void setSerialNumber(File file, int serialNumber)
2903 throws IOException {
2904 try {
2905 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2906 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2907 } catch (ErrnoException e) {
2908 throw e.rethrowAsIOException();
2909 }
2910 }
2911
2912 /**
2913 * Return serial number stored in user directory inode.
2914 *
2915 * @return parsed serial number, or -1 if not set
2916 */
2917 private static int getSerialNumber(File file) throws IOException {
2918 try {
2919 final byte[] buf = new byte[256];
2920 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2921 final String serial = new String(buf, 0, len);
2922 try {
2923 return Integer.parseInt(serial);
2924 } catch (NumberFormatException e) {
2925 throw new IOException("Bad serial number: " + serial);
2926 }
2927 } catch (ErrnoException e) {
2928 if (e.errno == OsConstants.ENODATA) {
2929 return -1;
2930 } else {
2931 throw e.rethrowAsIOException();
2932 }
2933 }
2934 }
2935
Amith Yamasani920ace02012-09-20 22:15:37 -07002936 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002937 public void setSeedAccountData(int userId, String accountName, String accountType,
2938 PersistableBundle accountOptions, boolean persist) {
2939 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2940 synchronized (mPackagesLock) {
2941 final UserData userData;
2942 synchronized (mUsersLock) {
2943 userData = getUserDataLU(userId);
2944 if (userData == null) {
2945 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2946 return;
2947 }
2948 userData.seedAccountName = accountName;
2949 userData.seedAccountType = accountType;
2950 userData.seedAccountOptions = accountOptions;
2951 userData.persistSeedData = persist;
2952 }
2953 if (persist) {
2954 writeUserLP(userData);
2955 }
2956 }
2957 }
2958
2959 @Override
2960 public String getSeedAccountName() throws RemoteException {
2961 checkManageUsersPermission("Cannot get seed account information");
2962 synchronized (mUsersLock) {
2963 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2964 return userData.seedAccountName;
2965 }
2966 }
2967
2968 @Override
2969 public String getSeedAccountType() throws RemoteException {
2970 checkManageUsersPermission("Cannot get seed account information");
2971 synchronized (mUsersLock) {
2972 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2973 return userData.seedAccountType;
2974 }
2975 }
2976
2977 @Override
2978 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2979 checkManageUsersPermission("Cannot get seed account information");
2980 synchronized (mUsersLock) {
2981 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2982 return userData.seedAccountOptions;
2983 }
2984 }
2985
2986 @Override
2987 public void clearSeedAccountData() throws RemoteException {
2988 checkManageUsersPermission("Cannot clear seed account information");
2989 synchronized (mPackagesLock) {
2990 UserData userData;
2991 synchronized (mUsersLock) {
2992 userData = getUserDataLU(UserHandle.getCallingUserId());
2993 if (userData == null) return;
2994 userData.clearSeedAccountData();
2995 }
2996 writeUserLP(userData);
2997 }
2998 }
2999
3000 @Override
3001 public boolean someUserHasSeedAccount(String accountName, String accountType)
3002 throws RemoteException {
3003 checkManageUsersPermission("Cannot check seed account information");
3004 synchronized (mUsersLock) {
3005 final int userSize = mUsers.size();
3006 for (int i = 0; i < userSize; i++) {
3007 final UserData data = mUsers.valueAt(i);
3008 if (data.info.isInitialized()) continue;
3009 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
3010 continue;
3011 }
3012 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
3013 continue;
3014 }
3015 return true;
3016 }
3017 }
3018 return false;
3019 }
3020
3021 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07003022 public void onShellCommand(FileDescriptor in, FileDescriptor out,
3023 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
3024 (new Shell()).exec(this, in, out, err, args, resultReceiver);
3025 }
3026
3027 int onShellCommand(Shell shell, String cmd) {
3028 if (cmd == null) {
3029 return shell.handleDefaultCommands(cmd);
3030 }
3031
3032 final PrintWriter pw = shell.getOutPrintWriter();
3033 try {
3034 switch(cmd) {
3035 case "list":
3036 return runList(pw);
3037 }
3038 } catch (RemoteException e) {
3039 pw.println("Remote exception: " + e);
3040 }
3041 return -1;
3042 }
3043
3044 private int runList(PrintWriter pw) throws RemoteException {
3045 final IActivityManager am = ActivityManagerNative.getDefault();
3046 final List<UserInfo> users = getUsers(false);
3047 if (users == null) {
3048 pw.println("Error: couldn't get users");
3049 return 1;
3050 } else {
3051 pw.println("Users:");
3052 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08003053 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07003054 pw.println("\t" + users.get(i).toString() + running);
3055 }
3056 return 0;
3057 }
3058 }
3059
3060 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003061 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3062 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3063 != PackageManager.PERMISSION_GRANTED) {
3064 pw.println("Permission Denial: can't dump UserManager from from pid="
3065 + Binder.getCallingPid()
3066 + ", uid=" + Binder.getCallingUid()
3067 + " without permission "
3068 + android.Manifest.permission.DUMP);
3069 return;
3070 }
3071
3072 long now = System.currentTimeMillis();
3073 StringBuilder sb = new StringBuilder();
3074 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003075 synchronized (mUsersLock) {
3076 pw.println("Users:");
3077 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003078 UserData userData = mUsers.valueAt(i);
3079 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003080 continue;
3081 }
Amith Yamasani12747872015-12-07 14:19:49 -08003082 UserInfo userInfo = userData.info;
3083 final int userId = userInfo.id;
3084 pw.print(" "); pw.print(userInfo);
3085 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003086 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003087 pw.print(" <removing> ");
3088 }
Amith Yamasani12747872015-12-07 14:19:49 -08003089 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003090 pw.print(" <partial>");
3091 }
3092 pw.println();
3093 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003094 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003095 pw.println("<unknown>");
3096 } else {
3097 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003098 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003099 sb.append(" ago");
3100 pw.println(sb);
3101 }
3102 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003103 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003104 pw.println("<unknown>");
3105 } else {
3106 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003107 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003108 sb.append(" ago");
3109 pw.println(sb);
3110 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003111 pw.print(" Last logged in fingerprint: ");
3112 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003113 pw.print(" Has profile owner: ");
3114 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003115 pw.println(" Restrictions:");
3116 synchronized (mRestrictionsLock) {
3117 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003118 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003119 pw.println(" Device policy local restrictions:");
3120 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003121 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003122 pw.println(" Effective restrictions:");
3123 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003124 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003125 }
Amith Yamasani12747872015-12-07 14:19:49 -08003126
3127 if (userData.account != null) {
3128 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003129 pw.println();
3130 }
Amith Yamasani12747872015-12-07 14:19:49 -08003131
3132 if (userData.seedAccountName != null) {
3133 pw.print(" Seed account name: " + userData.seedAccountName);
3134 pw.println();
3135 if (userData.seedAccountType != null) {
3136 pw.print(" account type: " + userData.seedAccountType);
3137 pw.println();
3138 }
3139 if (userData.seedAccountOptions != null) {
3140 pw.print(" account options exist");
3141 pw.println();
3142 }
3143 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003144 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003145 }
Amith Yamasani12747872015-12-07 14:19:49 -08003146 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003147 pw.println(" Device policy global restrictions:");
3148 synchronized (mRestrictionsLock) {
3149 UserRestrictionsUtils
3150 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3151 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003152 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003153 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3154 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003155 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003156 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003157 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003158 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003159 synchronized (mUsersLock) {
3160 pw.println();
3161 pw.println(" Device managed: " + mIsDeviceManaged);
3162 }
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003163 synchronized (mUserStates) {
3164 pw.println(" Started users state: " + mUserStates);
3165 }
Amith Yamasani12747872015-12-07 14:19:49 -08003166 // Dump some capabilities
3167 pw.println();
3168 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3169 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003170 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3171 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003172 }
3173 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003174
3175 final class MainHandler extends Handler {
3176
3177 @Override
3178 public void handleMessage(Message msg) {
3179 switch (msg.what) {
3180 case WRITE_USER_MSG:
3181 removeMessages(WRITE_USER_MSG, msg.obj);
3182 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003183 int userId = ((UserData) msg.obj).info.id;
3184 UserData userData = getUserDataNoChecks(userId);
3185 if (userData != null) {
3186 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003187 }
3188 }
3189 }
3190 }
3191 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003192
3193 /**
3194 * @param userId
3195 * @return whether the user has been initialized yet
3196 */
3197 boolean isInitialized(int userId) {
3198 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3199 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003200
3201 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003202 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003203 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3204 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003205 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003206 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003207 }
3208
3209 @Override
3210 public Bundle getBaseUserRestrictions(int userId) {
3211 synchronized (mRestrictionsLock) {
3212 return mBaseUserRestrictions.get(userId);
3213 }
3214 }
3215
3216 @Override
3217 public void setBaseUserRestrictionsByDpmsForMigration(
3218 int userId, Bundle baseRestrictions) {
3219 synchronized (mRestrictionsLock) {
3220 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003221 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003222 }
3223
Amith Yamasani12747872015-12-07 14:19:49 -08003224 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003225 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003226 if (userData != null) {
3227 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003228 } else {
3229 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3230 }
3231 }
3232 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003233
3234 @Override
3235 public boolean getUserRestriction(int userId, String key) {
3236 return getUserRestrictions(userId).getBoolean(key);
3237 }
3238
3239 @Override
3240 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3241 synchronized (mUserRestrictionsListeners) {
3242 mUserRestrictionsListeners.add(listener);
3243 }
3244 }
3245
3246 @Override
3247 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3248 synchronized (mUserRestrictionsListeners) {
3249 mUserRestrictionsListeners.remove(listener);
3250 }
3251 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003252
3253 @Override
3254 public void setDeviceManaged(boolean isManaged) {
3255 synchronized (mUsersLock) {
3256 mIsDeviceManaged = isManaged;
3257 }
3258 }
3259
3260 @Override
3261 public void setUserManaged(int userId, boolean isManaged) {
3262 synchronized (mUsersLock) {
3263 mIsUserManaged.put(userId, isManaged);
3264 }
3265 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003266
3267 @Override
3268 public void setUserIcon(int userId, Bitmap bitmap) {
3269 long ident = Binder.clearCallingIdentity();
3270 try {
3271 synchronized (mPackagesLock) {
3272 UserData userData = getUserDataNoChecks(userId);
3273 if (userData == null || userData.info.partial) {
3274 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3275 return;
3276 }
3277 writeBitmapLP(userData.info, bitmap);
3278 writeUserLP(userData);
3279 }
3280 sendUserInfoChangedBroadcast(userId);
3281 } finally {
3282 Binder.restoreCallingIdentity(ident);
3283 }
3284 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003285
3286 @Override
3287 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3288 synchronized (mUsersLock) {
3289 mForceEphemeralUsers = forceEphemeralUsers;
3290 }
3291 }
3292
3293 @Override
3294 public void removeAllUsers() {
3295 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3296 // Remove the non-system users straight away.
3297 removeNonSystemUsers();
3298 } else {
3299 // Switch to the system user first and then remove the other users.
3300 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3301 @Override
3302 public void onReceive(Context context, Intent intent) {
3303 int userId =
3304 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3305 if (userId != UserHandle.USER_SYSTEM) {
3306 return;
3307 }
3308 mContext.unregisterReceiver(this);
3309 removeNonSystemUsers();
3310 }
3311 };
3312 IntentFilter userSwitchedFilter = new IntentFilter();
3313 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3314 mContext.registerReceiver(
3315 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3316
3317 // Switch to the system user.
3318 ActivityManager am =
3319 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3320 am.switchUser(UserHandle.USER_SYSTEM);
3321 }
3322 }
phweisse9c44062016-02-10 12:57:38 +01003323
3324 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003325 public void onEphemeralUserStop(int userId) {
3326 synchronized (mUsersLock) {
3327 UserInfo userInfo = getUserInfoLU(userId);
3328 if (userInfo != null && userInfo.isEphemeral()) {
3329 // Do not allow switching back to the ephemeral user again as the user is going
3330 // to be deleted.
3331 userInfo.flags |= UserInfo.FLAG_DISABLED;
3332 if (userInfo.isGuest()) {
3333 // Indicate that the guest will be deleted after it stops.
3334 userInfo.guestToRemove = true;
3335 }
3336 }
3337 }
3338 }
3339
3340 @Override
phweisse9c44062016-02-10 12:57:38 +01003341 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3342 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3343 // Keep this in sync with UserManager.createUser
3344 if (user != null && !user.isAdmin()) {
3345 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3346 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3347 }
3348 return user;
3349 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003350
3351 @Override
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003352 public boolean isUserRunning(int userId) {
3353 synchronized (mUserStates) {
3354 return mUserStates.get(userId, -1) >= 0;
3355 }
3356 }
3357
3358 @Override
3359 public void setUserState(int userId, int userState) {
3360 synchronized (mUserStates) {
3361 mUserStates.put(userId, userState);
3362 }
3363 }
3364
3365 @Override
3366 public void removeUserState(int userId) {
3367 synchronized (mUserStates) {
3368 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003369 }
3370 }
3371
3372 @Override
3373 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003374 synchronized (mUserStates) {
3375 int state = mUserStates.get(userId, -1);
3376 return (state == UserState.STATE_RUNNING_UNLOCKING)
3377 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003378 }
3379 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003380 }
3381
3382 /* Remove all the users except of the system one. */
3383 private void removeNonSystemUsers() {
3384 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3385 synchronized (mUsersLock) {
3386 final int userSize = mUsers.size();
3387 for (int i = 0; i < userSize; i++) {
3388 UserInfo ui = mUsers.valueAt(i).info;
3389 if (ui.id != UserHandle.USER_SYSTEM) {
3390 usersToRemove.add(ui);
3391 }
3392 }
3393 }
3394 for (UserInfo ui: usersToRemove) {
3395 removeUser(ui.id);
3396 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003397 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003398
3399 private class Shell extends ShellCommand {
3400 @Override
3401 public int onCommand(String cmd) {
3402 return onShellCommand(this, cmd);
3403 }
3404
3405 @Override
3406 public void onHelp() {
3407 final PrintWriter pw = getOutPrintWriter();
3408 pw.println("User manager (user) commands:");
3409 pw.println(" help");
3410 pw.println(" Print this help text.");
3411 pw.println("");
3412 pw.println(" list");
3413 pw.println(" Prints all users on the system.");
3414 }
3415 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003416
3417 private static void debug(String message) {
3418 Log.d(LOG_TAG, message +
3419 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3420 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003421}