blob: ab20a1431d13370392cbf219f5597120d2c7f695 [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
Amith Yamasani634cf312012-10-04 17:34:21 -0700171 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700172 // We need to keep process uid within Integer.MAX_VALUE.
173 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700174
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700175 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700176
Amith Yamasani920ace02012-09-20 22:15:37 -0700177 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
178
Nicolas Prevotb8186812015-08-06 15:00:03 +0100179 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700180 // without first making sure that the rest of the framework is prepared for it.
181 private static final int MAX_MANAGED_PROFILES = 1;
182
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800183 static final int WRITE_USER_MSG = 1;
184 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530185
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700186 private static final String XATTR_SERIAL = "user.serial";
187
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800188 // Tron counters
189 private static final String TRON_GUEST_CREATED = "users_guest_created";
190 private static final String TRON_USER_CREATED = "users_user_created";
191
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192 private final Context mContext;
193 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700194 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700195 // Short-term lock for internal state, when interaction/sync with PM is not required
196 private final Object mUsersLock = new Object();
197 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700198
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800199 private final Handler mHandler;
200
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700201 private final File mUsersDir;
202 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700203
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800204 private static final IBinder mUserRestriconToken = new Binder();
205
Makoto Onuki068c54a2015-10-13 14:34:03 -0700206 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800207 * User-related information that is used for persisting to flash. Only UserInfo is
208 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800209 */
Amith Yamasani12747872015-12-07 14:19:49 -0800210 private static class UserData {
211 // Basic user information and properties
212 UserInfo info;
213 // Account name used when there is a strong association between a user and an account
214 String account;
215 // Account information for seeding into a newly created user. This could also be
216 // used for login validation for an existing user, for updating their credentials.
217 // In the latter case, data may not need to be persisted as it is only valid for the
218 // current login session.
219 String seedAccountName;
220 String seedAccountType;
221 PersistableBundle seedAccountOptions;
222 // Whether to perist the seed account information to be available after a boot
223 boolean persistSeedData;
224
225 void clearSeedAccountData() {
226 seedAccountName = null;
227 seedAccountType = null;
228 seedAccountOptions = null;
229 persistSeedData = false;
230 }
231 }
232
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800233 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800234 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800235
236 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700237 * User restrictions set via UserManager. This doesn't include restrictions set by
238 * device owner / profile owners.
239 *
240 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
241 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
242 * maybe shared between {@link #mBaseUserRestrictions} and
243 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
244 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700245 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 */
247 @GuardedBy("mRestrictionsLock")
248 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
249
250 /**
251 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
252 * with device / profile owner restrictions. We'll initialize it lazily; use
253 * {@link #getEffectiveUserRestrictions} to access it.
254 *
255 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
256 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
257 * maybe shared between {@link #mBaseUserRestrictions} and
258 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
259 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700260 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700261 */
262 @GuardedBy("mRestrictionsLock")
263 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
264
Makoto Onuki4f160732015-10-27 17:15:38 -0700265 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800266 * User restrictions that have already been applied in
267 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
268 * that have changed since the last
269 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700270 */
271 @GuardedBy("mRestrictionsLock")
272 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
273
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800274 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800275 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
276 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800277 */
278 @GuardedBy("mRestrictionsLock")
279 private Bundle mDevicePolicyGlobalUserRestrictions;
280
281 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +0100282 * Id of the user that set global restrictions.
283 */
284 @GuardedBy("mRestrictionsLock")
285 private int mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
286
287 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800288 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
289 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800290 */
291 @GuardedBy("mRestrictionsLock")
292 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
293
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800294 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530295 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800296
297 /**
298 * Set of user IDs being actively removed. Removed IDs linger in this set
299 * for several seconds to work around a VFS caching issue.
300 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700301 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800302 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700303
Fyodor Kupolov82402752015-10-28 14:54:51 -0700304 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700305 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800306 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700307 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700308 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700309
Jason Monk62062992014-05-06 09:55:28 -0400310 private IAppOpsService mAppOpsService;
311
Makoto Onuki068c54a2015-10-13 14:34:03 -0700312 private final LocalService mLocalService;
313
Makoto Onukie7927da2015-11-25 10:05:17 -0800314 @GuardedBy("mUsersLock")
315 private boolean mIsDeviceManaged;
316
317 @GuardedBy("mUsersLock")
318 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
319
Makoto Onukid45a4a22015-11-02 17:17:38 -0800320 @GuardedBy("mUserRestrictionsListeners")
321 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
322 new ArrayList<>();
323
Clara Bayarria1771112015-12-18 16:29:18 +0000324 private final LockPatternUtils mLockPatternUtils;
325
Ricky Waib1dd80b2016-06-07 18:00:55 +0100326 private final String ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK =
327 "com.android.server.pm.DISABLE_QUIET_MODE_AFTER_UNLOCK";
328
329 private final BroadcastReceiver mDisableQuietModeCallback = new BroadcastReceiver() {
330 @Override
331 public void onReceive(Context context, Intent intent) {
332 if (ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK.equals(intent.getAction())) {
333 final IntentSender target = intent.getParcelableExtra(Intent.EXTRA_INTENT);
334 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
335 setQuietModeEnabled(userHandle, false);
336 if (target != null) {
337 try {
338 mContext.startIntentSender(target, null, 0, 0, 0);
339 } catch (IntentSender.SendIntentException e) {
340 /* ignore */
341 }
342 }
343 }
344 }
345 };
346
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100347 /**
348 * Whether all users should be created ephemeral.
349 */
350 @GuardedBy("mUsersLock")
351 private boolean mForceEphemeralUsers;
352
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700353 @GuardedBy("mUserStates")
354 private final SparseIntArray mUserStates = new SparseIntArray();
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -0700355
Amith Yamasani258848d2012-08-10 17:06:33 -0700356 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700357
Dianne Hackborn4428e172012-08-24 17:43:05 -0700358 public static UserManagerService getInstance() {
359 synchronized (UserManagerService.class) {
360 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700361 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700362 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700363
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800364 @VisibleForTesting
365 UserManagerService(File dataDir) {
366 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700367 }
368
Dianne Hackborn4428e172012-08-24 17:43:05 -0700369 /**
370 * Called by package manager to create the service. This is closely
371 * associated with the package manager, and the given lock is the
372 * package manager's own lock.
373 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800374 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
375 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700376 }
377
Dianne Hackborn4428e172012-08-24 17:43:05 -0700378 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800379 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700380 mContext = context;
381 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700382 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800383 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800384 synchronized (mPackagesLock) {
385 mUsersDir = new File(dataDir, USER_INFO_DIR);
386 mUsersDir.mkdirs();
387 // Make zeroth user directory, for services to migrate their files to that location
388 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
389 userZeroDir.mkdirs();
390 FileUtils.setPermissions(mUsersDir.toString(),
391 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
392 -1, -1);
393 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
394 initDefaultGuestRestrictions();
395 readUserListLP();
396 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700397 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700398 mLocalService = new LocalService();
399 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000400 mLockPatternUtils = new LockPatternUtils(mContext);
Fyodor Kupolovac06a492016-05-25 14:45:29 -0700401 mUserStates.put(UserHandle.USER_SYSTEM, UserState.STATE_BOOTING);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700402 }
403
404 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100405 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800406 ArrayList<UserInfo> partials = new ArrayList<>();
407 synchronized (mUsersLock) {
408 final int userSize = mUsers.size();
409 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800410 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100411 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800412 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700413 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700414 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700415 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800416 final int partialsSize = partials.size();
417 for (int i = 0; i < partialsSize; i++) {
418 UserInfo ui = partials.get(i);
419 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
420 + " (name=" + ui.name + ")");
421 removeUserState(ui.id);
422 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800423
Jason Monk62062992014-05-06 09:55:28 -0400424 mAppOpsService = IAppOpsService.Stub.asInterface(
425 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800426
427 synchronized (mRestrictionsLock) {
428 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400429 }
Samuel Tand9453b82016-03-14 15:57:02 -0700430
431 UserInfo currentGuestUser = findCurrentGuestUser();
432 if (currentGuestUser != null && !hasUserRestriction(
433 UserManager.DISALLOW_CONFIG_WIFI, currentGuestUser.id)) {
434 // If a guest user currently exists, apply the DISALLOW_CONFIG_WIFI option
435 // to it, in case this guest was created in a previous version where this
436 // user restriction was not a default guest restriction.
437 setUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, true, currentGuestUser.id);
438 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100439 mContext.registerReceiver(mDisableQuietModeCallback,
440 new IntentFilter(ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK),
441 null, mHandler);
Amith Yamasani258848d2012-08-10 17:06:33 -0700442 }
443
444 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800445 public String getUserAccount(int userId) {
446 checkManageUserAndAcrossUsersFullPermission("get user account");
447 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800448 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800449 }
450 }
451
452 @Override
453 public void setUserAccount(int userId, String accountName) {
454 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800455 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800456 synchronized (mPackagesLock) {
457 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800458 final UserData userData = mUsers.get(userId);
459 if (userData == null) {
460 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
461 return;
462 }
463 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800464 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800465 userData.account = accountName;
466 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800467 }
468 }
469
470 if (userToUpdate != null) {
471 writeUserLP(userToUpdate);
472 }
473 }
474 }
475
476 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700477 public UserInfo getPrimaryUser() {
478 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700479 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700480 final int userSize = mUsers.size();
481 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800482 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800483 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700484 return ui;
485 }
486 }
487 }
488 return null;
489 }
490
491 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700492 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700493 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700494 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700495 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700496 final int userSize = mUsers.size();
497 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800498 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700499 if (ui.partial) {
500 continue;
501 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800502 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700503 users.add(userWithName(ui));
Amith Yamasani920ace02012-09-20 22:15:37 -0700504 }
Amith Yamasani13593602012-03-22 16:16:17 -0700505 }
506 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700507 }
Amith Yamasani13593602012-03-22 16:16:17 -0700508 }
509
Amith Yamasani258848d2012-08-10 17:06:33 -0700510 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100511 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700512 boolean returnFullInfo = true;
Amith Yamasani4f582632014-02-19 14:31:52 -0800513 if (userId != UserHandle.getCallingUserId()) {
514 checkManageUsersPermission("getting profiles related to user " + userId);
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700515 } else {
516 returnFullInfo = hasManageUsersPermission();
Amith Yamasani4f582632014-02-19 14:31:52 -0800517 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700518 final long ident = Binder.clearCallingIdentity();
519 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700520 synchronized (mUsersLock) {
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700521 return getProfilesLU(userId, enabledOnly, returnFullInfo);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100522 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700523 } finally {
524 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000525 }
526 }
527
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700528 @Override
529 public int[] getProfileIds(int userId, boolean enabledOnly) {
530 if (userId != UserHandle.getCallingUserId()) {
531 checkManageUsersPermission("getting profiles related to user " + userId);
532 }
533 final long ident = Binder.clearCallingIdentity();
534 try {
535 synchronized (mUsersLock) {
536 return getProfileIdsLU(userId, enabledOnly).toArray();
537 }
538 } finally {
539 Binder.restoreCallingIdentity(ident);
540 }
541 }
542
Amith Yamasanibe465322014-04-24 13:45:17 -0700543 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolovc533b562016-04-01 14:37:07 -0700544 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly, boolean fullInfo) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700545 IntArray profileIds = getProfileIdsLU(userId, enabledOnly);
546 ArrayList<UserInfo> users = new ArrayList<>(profileIds.size());
547 for (int i = 0; i < profileIds.size(); i++) {
548 int profileId = profileIds.get(i);
549 UserInfo userInfo = mUsers.get(profileId).info;
550 // If full info is not required - clear PII data to prevent 3P apps from reading it
551 if (!fullInfo) {
552 userInfo = new UserInfo(userInfo);
553 userInfo.name = null;
554 userInfo.iconPath = null;
555 } else {
556 userInfo = userWithName(userInfo);
557 }
558 users.add(userInfo);
559 }
560 return users;
561 }
562
563 /**
564 * Assume permissions already checked and caller's identity cleared
565 */
566 private IntArray getProfileIdsLU(int userId, boolean enabledOnly) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700567 UserInfo user = getUserInfoLU(userId);
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700568 IntArray result = new IntArray(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700569 if (user == null) {
570 // Probably a dying user
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700571 return result;
Amith Yamasanidda003f2014-08-28 18:06:51 -0700572 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700573 final int userSize = mUsers.size();
574 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800575 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700576 if (!isProfileOf(user, profile)) {
577 continue;
578 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100579 if (enabledOnly && !profile.isEnabled()) {
580 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700581 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700582 if (mRemovingUserIds.get(profile.id)) {
583 continue;
584 }
Tony Mak80189cd2016-04-05 17:21:42 +0100585 if (profile.partial) {
586 continue;
587 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700588 result.add(profile.id);
Amith Yamasanibe465322014-04-24 13:45:17 -0700589 }
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700590 return result;
Amith Yamasanibe465322014-04-24 13:45:17 -0700591 }
592
Jessica Hummelbe81c802014-04-22 15:49:22 +0100593 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700594 public int getCredentialOwnerProfile(int userHandle) {
595 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000596 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700597 synchronized (mUsersLock) {
598 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700599 if (profileParent != null) {
600 return profileParent.id;
601 }
602 }
603 }
604
605 return userHandle;
606 }
607
608 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700609 public boolean isSameProfileGroup(int userId, int otherUserId) {
610 if (userId == otherUserId) return true;
611 checkManageUsersPermission("check if in the same profile group");
612 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700613 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700614 }
615 }
616
Fyodor Kupolov82402752015-10-28 14:54:51 -0700617 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
618 synchronized (mUsersLock) {
619 UserInfo userInfo = getUserInfoLU(userId);
620 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
621 return false;
622 }
623 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
624 if (otherUserInfo == null
625 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
626 return false;
627 }
628 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700629 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700630 }
631
632 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100633 public UserInfo getProfileParent(int userHandle) {
634 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700635 synchronized (mUsersLock) {
636 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700637 }
638 }
639
Fyodor Kupolov82402752015-10-28 14:54:51 -0700640 private UserInfo getProfileParentLU(int userHandle) {
641 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700642 if (profile == null) {
643 return null;
644 }
645 int parentUserId = profile.profileGroupId;
646 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
647 return null;
648 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700649 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100650 }
651 }
652
Fyodor Kupolov82402752015-10-28 14:54:51 -0700653 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100654 return user.id == profile.id ||
655 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
656 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000657 }
658
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000659 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000660 UserHandle parentHandle, boolean inQuietMode) {
Rubin Xue95057a2016-04-01 16:49:25 +0100661 Intent intent = new Intent();
662 if (inQuietMode) {
663 intent.setAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
664 } else {
665 intent.setAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
666 }
Rubin Xuf13c9802016-01-21 18:06:00 +0000667 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
668 intent.putExtra(Intent.EXTRA_USER, profileHandle);
669 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000670 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000671 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000672 }
673
674 @Override
675 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
676 checkManageUsersPermission("silence profile");
677 boolean changed = false;
678 UserInfo profile, parent;
679 synchronized (mPackagesLock) {
680 synchronized (mUsersLock) {
681 profile = getUserInfoLU(userHandle);
682 parent = getProfileParentLU(userHandle);
683
684 }
685 if (profile == null || !profile.isManagedProfile()) {
686 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
687 }
688 if (profile.isQuietModeEnabled() != enableQuietMode) {
689 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800690 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000691 changed = true;
692 }
693 }
694 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000695 long identity = Binder.clearCallingIdentity();
696 try {
697 if (enableQuietMode) {
Rubin Xuf8451b92016-04-01 15:50:58 +0100698 LocalServices.getService(ActivityManagerInternal.class)
699 .killForegroundAppsForUser(userHandle);
Rubin Xuf13c9802016-01-21 18:06:00 +0000700 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
701 } else {
702 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
703 }
704 } catch (RemoteException e) {
705 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
706 } finally {
707 Binder.restoreCallingIdentity(identity);
708 }
709
710 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
711 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000712 }
713 }
714
715 @Override
716 public boolean isQuietModeEnabled(int userHandle) {
717 synchronized (mPackagesLock) {
718 UserInfo info;
719 synchronized (mUsersLock) {
720 info = getUserInfoLU(userHandle);
721 }
722 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000723 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000724 }
725 return info.isQuietModeEnabled();
726 }
727 }
728
Kenny Guya52dc3e2014-02-11 15:33:14 +0000729 @Override
Benjamin Franzf02420c2016-04-04 18:52:21 +0100730 public boolean trySetQuietModeDisabled(int userHandle, IntentSender target) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100731 checkManageUsersPermission("silence profile");
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600732 if (StorageManager.isUserKeyUnlocked(userHandle)
Ricky Wai9cc7ad62016-05-11 18:00:20 +0100733 || !mLockPatternUtils.isSecure(userHandle)) {
Benjamin Franzf02420c2016-04-04 18:52:21 +0100734 // if the user is already unlocked, no need to show a profile challenge
735 setQuietModeEnabled(userHandle, false);
736 return true;
737 }
738
739 long identity = Binder.clearCallingIdentity();
740 try {
741 // otherwise, we show a profile challenge to trigger decryption of the user
742 final KeyguardManager km = (KeyguardManager) mContext.getSystemService(
743 Context.KEYGUARD_SERVICE);
Ricky Wai7881cf82016-04-15 17:20:12 +0100744 // We should use userHandle not credentialOwnerUserId here, as even if it is unified
745 // lock, confirm screenlock page will know and show personal challenge, and unlock
746 // work profile when personal challenge is correct
Benjamin Franzf02420c2016-04-04 18:52:21 +0100747 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null,
748 userHandle);
749 if (unlockIntent == null) {
750 return false;
751 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100752 final Intent callBackIntent = new Intent(
753 ACTION_DISABLE_QUIET_MODE_AFTER_UNLOCK);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100754 if (target != null) {
Ricky Waib1dd80b2016-06-07 18:00:55 +0100755 callBackIntent.putExtra(Intent.EXTRA_INTENT, target);
Benjamin Franzf02420c2016-04-04 18:52:21 +0100756 }
Ricky Waib1dd80b2016-06-07 18:00:55 +0100757 callBackIntent.putExtra(Intent.EXTRA_USER_ID, userHandle);
758 callBackIntent.setPackage(mContext.getPackageName());
759 callBackIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
760 final PendingIntent pendingIntent = PendingIntent.getBroadcast(
761 mContext,
762 0,
763 callBackIntent,
764 PendingIntent.FLAG_CANCEL_CURRENT |
765 PendingIntent.FLAG_ONE_SHOT |
766 PendingIntent.FLAG_IMMUTABLE);
767 // After unlocking the challenge, it will disable quiet mode and run the original
768 // intentSender
769 unlockIntent.putExtra(Intent.EXTRA_INTENT, pendingIntent.getIntentSender());
Benjamin Franzf02420c2016-04-04 18:52:21 +0100770 unlockIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
771 mContext.startActivity(unlockIntent);
772 } finally {
773 Binder.restoreCallingIdentity(identity);
774 }
775 return false;
776 }
777
778 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100779 public void setUserEnabled(int userId) {
780 checkManageUsersPermission("enable user");
781 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700782 UserInfo info;
783 synchronized (mUsersLock) {
784 info = getUserInfoLU(userId);
785 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100786 if (info != null && !info.isEnabled()) {
787 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800788 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100789 }
790 }
791 }
792
793 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700794 public UserInfo getUserInfo(int userId) {
Tony Mak8673b282016-03-21 21:10:59 +0000795 checkManageUsersPermission("query user");
796 synchronized (mUsersLock) {
Amith Yamasani6f48d6e2016-03-23 14:28:25 -0700797 return userWithName(getUserInfoLU(userId));
798 }
799 }
800
801 /**
802 * Returns a UserInfo object with the name filled in, for Owner, or the original
803 * if the name is already set.
804 */
805 private UserInfo userWithName(UserInfo orig) {
806 if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
807 UserInfo withName = new UserInfo(orig);
808 withName.name = getOwnerName();
809 return withName;
810 } else {
811 return orig;
Tony Mak8673b282016-03-21 21:10:59 +0000812 }
813 }
814
815 @Override
816 public boolean isManagedProfile(int userId) {
Tony Makb531d082016-03-16 14:49:52 +0000817 int callingUserId = UserHandle.getCallingUserId();
818 if (callingUserId != userId && !hasManageUsersPermission()) {
819 synchronized (mPackagesLock) {
820 if (!isSameProfileGroupLP(callingUserId, userId)) {
821 throw new SecurityException(
Tony Mak8673b282016-03-21 21:10:59 +0000822 "You need MANAGE_USERS permission to: check if specified user a " +
823 "managed profile outside your profile group");
Tony Makb531d082016-03-16 14:49:52 +0000824 }
825 }
Tony Mak4dc008c2016-03-16 10:46:49 +0000826 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700827 synchronized (mUsersLock) {
Tony Mak8673b282016-03-21 21:10:59 +0000828 UserInfo userInfo = getUserInfoLU(userId);
829 return userInfo != null && userInfo.isManagedProfile();
Amith Yamasani13593602012-03-22 16:16:17 -0700830 }
831 }
832
Amith Yamasani71e6c692013-03-24 17:39:28 -0700833 @Override
834 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700835 synchronized (mUsersLock) {
836 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700837 }
838 }
839
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700840 @Override
841 public boolean canHaveRestrictedProfile(int userId) {
842 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700843 synchronized (mUsersLock) {
844 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700845 if (userInfo == null || !userInfo.canHaveProfile()) {
846 return false;
847 }
848 if (!userInfo.isAdmin()) {
849 return false;
850 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800851 // restricted profile can be created if there is no DO set and the admin user has no PO;
852 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700853 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700854 }
855
Amith Yamasani195263742012-08-21 15:40:12 -0700856 /*
857 * Should be locked on mUsers before calling this.
858 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700859 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800860 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700861 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800862 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700863 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
864 return null;
865 }
Amith Yamasani12747872015-12-07 14:19:49 -0800866 return userData != null ? userData.info : null;
867 }
868
869 private UserData getUserDataLU(int userId) {
870 final UserData userData = mUsers.get(userId);
871 // If it is partial and not in the process of being removed, return as unknown user.
872 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
873 return null;
874 }
875 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700876 }
877
Fyodor Kupolov82402752015-10-28 14:54:51 -0700878 /**
879 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
880 * <p>No permissions checking or any addition checks are made</p>
881 */
882 private UserInfo getUserInfoNoChecks(int userId) {
883 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800884 final UserData userData = mUsers.get(userId);
885 return userData != null ? userData.info : null;
886 }
887 }
888
889 /**
890 * Obtains {@link #mUsersLock} and return UserData from mUsers.
891 * <p>No permissions checking or any addition checks are made</p>
892 */
893 private UserData getUserDataNoChecks(int userId) {
894 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700895 return mUsers.get(userId);
896 }
897 }
898
Amith Yamasani236b2b52015-08-18 14:32:14 -0700899 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700900 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700901 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700902 }
903
Amith Yamasani258848d2012-08-10 17:06:33 -0700904 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700905 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700906 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700907 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700908 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800909 UserData userData = getUserDataNoChecks(userId);
910 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700911 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
912 return;
913 }
Amith Yamasani12747872015-12-07 14:19:49 -0800914 if (name != null && !name.equals(userData.info.name)) {
915 userData.info.name = name;
916 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700917 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700918 }
919 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700920 if (changed) {
921 sendUserInfoChangedBroadcast(userId);
922 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700923 }
924
Amith Yamasani258848d2012-08-10 17:06:33 -0700925 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700926 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700927 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100928 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
929 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
930 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700931 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100932 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700933 }
934
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100935
936
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700937 private void sendUserInfoChangedBroadcast(int userId) {
938 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
939 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
940 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700941 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700942 }
943
Amith Yamasani258848d2012-08-10 17:06:33 -0700944 @Override
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100945 public ParcelFileDescriptor getUserIcon(int targetUserId) {
Adrian Roos1bdff912015-02-17 15:51:35 +0100946 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700947 synchronized (mPackagesLock) {
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100948 UserInfo targetUserInfo = getUserInfoNoChecks(targetUserId);
949 if (targetUserInfo == null || targetUserInfo.partial) {
950 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + targetUserId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700951 return null;
952 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100953
954 final int callingUserId = UserHandle.getCallingUserId();
955 final int callingGroupId = getUserInfoNoChecks(callingUserId).profileGroupId;
956 final int targetGroupId = targetUserInfo.profileGroupId;
957 final boolean sameGroup = (callingGroupId != UserInfo.NO_PROFILE_GROUP_ID
958 && callingGroupId == targetGroupId);
959 if ((callingUserId != targetUserId) && !sameGroup) {
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100960 checkManageUsersPermission("get the icon of a user who is not related");
961 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100962
963 if (targetUserInfo.iconPath == null) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700964 return null;
965 }
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +0100966 iconPath = targetUserInfo.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700967 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100968
969 try {
970 return ParcelFileDescriptor.open(
971 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
972 } catch (FileNotFoundException e) {
973 Log.e(LOG_TAG, "Couldn't find icon file", e);
974 }
975 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700976 }
977
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700978 public void makeInitialized(int userId) {
979 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800980 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800981 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800982 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800983 userData = mUsers.get(userId);
984 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700985 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800986 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700987 }
Amith Yamasani12747872015-12-07 14:19:49 -0800988 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
989 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800990 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700991 }
992 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800993 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800994 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800995 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700996 }
997
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700998 /**
999 * If default guest restrictions haven't been initialized yet, add the basic
1000 * restrictions.
1001 */
1002 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001003 synchronized (mGuestRestrictions) {
1004 if (mGuestRestrictions.isEmpty()) {
Samuel Tand9453b82016-03-14 15:57:02 -07001005 mGuestRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_WIFI, true);
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001006 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001007 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
1008 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
1009 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001010 }
1011 }
1012
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001013 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301014 public Bundle getDefaultGuestRestrictions() {
1015 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001016 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301017 return new Bundle(mGuestRestrictions);
1018 }
1019 }
1020
1021 @Override
1022 public void setDefaultGuestRestrictions(Bundle restrictions) {
1023 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001024 synchronized (mGuestRestrictions) {
1025 mGuestRestrictions.clear();
1026 mGuestRestrictions.putAll(restrictions);
1027 }
1028 synchronized (mPackagesLock) {
1029 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301030 }
1031 }
1032
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001033 /**
1034 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
1035 */
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001036 void setDevicePolicyUserRestrictionsInner(int userId, @NonNull Bundle local,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001037 @Nullable Bundle global) {
1038 Preconditions.checkNotNull(local);
1039 boolean globalChanged = false;
1040 boolean localChanged;
1041 synchronized (mRestrictionsLock) {
1042 if (global != null) {
1043 // Update global.
1044 globalChanged = !UserRestrictionsUtils.areEqual(
1045 mDevicePolicyGlobalUserRestrictions, global);
1046 if (globalChanged) {
1047 mDevicePolicyGlobalUserRestrictions = global;
1048 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001049 // Remember the global restriction owner userId to be able to make a distinction
1050 // in getUserRestrictionSource on who set local policies.
1051 mGlobalRestrictionOwnerUserId = userId;
1052 } else {
Zoltan Szatmary-Ban8a5536d2016-05-27 17:56:44 +01001053 if (mGlobalRestrictionOwnerUserId == userId) {
1054 // When profile owner sets restrictions it passes null global bundle and we
1055 // reset global restriction owner userId.
1056 // This means this user used to have DO, but now the DO is gone and the user
1057 // instead has PO.
1058 mGlobalRestrictionOwnerUserId = UserHandle.USER_NULL;
1059 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001060 }
1061 {
1062 // Update local.
1063 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
1064 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
1065 if (localChanged) {
1066 mDevicePolicyLocalUserRestrictions.put(userId, local);
1067 }
1068 }
1069 }
1070 if (DBG) {
1071 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
1072 + " global=" + global + (globalChanged ? " (changed)" : "")
1073 + " local=" + local + (localChanged ? " (changed)" : "")
1074 );
1075 }
1076 // Don't call them within the mRestrictionsLock.
1077 synchronized (mPackagesLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001078 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -08001079 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001080 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06001081 if (globalChanged) {
1082 writeUserListLP();
1083 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001084 }
1085
1086 synchronized (mRestrictionsLock) {
1087 if (globalChanged) {
1088 applyUserRestrictionsForAllUsersLR();
1089 } else if (localChanged) {
1090 applyUserRestrictionsLR(userId);
1091 }
1092 }
1093 }
1094
Makoto Onuki068c54a2015-10-13 14:34:03 -07001095 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001096 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001097 final Bundle baseRestrictions =
1098 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
1099 final Bundle global = mDevicePolicyGlobalUserRestrictions;
1100 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001101
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001102 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
1103 // Common case first.
1104 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001105 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001106 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
1107 UserRestrictionsUtils.merge(effective, global);
1108 UserRestrictionsUtils.merge(effective, local);
1109
Makoto Onuki068c54a2015-10-13 14:34:03 -07001110 return effective;
1111 }
1112
1113 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001114 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001115 if (DBG) {
1116 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
1117 }
1118 mCachedEffectiveUserRestrictions.remove(userId);
1119 }
1120
1121 private Bundle getEffectiveUserRestrictions(int userId) {
1122 synchronized (mRestrictionsLock) {
1123 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
1124 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001125 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001126 mCachedEffectiveUserRestrictions.put(userId, restrictions);
1127 }
1128 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001129 }
1130 }
1131
Makoto Onuki068c54a2015-10-13 14:34:03 -07001132 /** @return a specific user restriction that's in effect currently. */
1133 @Override
1134 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001135 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1136 return false;
1137 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001138 Bundle restrictions = getEffectiveUserRestrictions(userId);
1139 return restrictions != null && restrictions.getBoolean(restrictionKey);
1140 }
1141
1142 /**
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001143 * @hide
1144 *
1145 * Returns who set a user restriction on a user.
1146 * Requires {@link android.Manifest.permission#MANAGE_USERS} permission.
1147 * @param restrictionKey the string key representing the restriction
1148 * @param userId the id of the user for whom to retrieve the restrictions.
1149 * @return The source of user restriction. Any combination of
1150 * {@link UserManager#RESTRICTION_NOT_SET},
1151 * {@link UserManager#RESTRICTION_SOURCE_SYSTEM},
1152 * {@link UserManager#RESTRICTION_SOURCE_DEVICE_OWNER}
1153 * and {@link UserManager#RESTRICTION_SOURCE_PROFILE_OWNER}
1154 */
1155 @Override
1156 public int getUserRestrictionSource(String restrictionKey, int userId) {
1157 checkManageUsersPermission("getUserRestrictionSource");
1158 int result = UserManager.RESTRICTION_NOT_SET;
1159
1160 // Shortcut for the most common case
1161 if (!hasUserRestriction(restrictionKey, userId)) {
1162 return result;
1163 }
1164
1165 if (hasBaseUserRestriction(restrictionKey, userId)) {
1166 result |= UserManager.RESTRICTION_SOURCE_SYSTEM;
1167 }
1168
1169 synchronized(mRestrictionsLock) {
1170 Bundle localRestrictions = mDevicePolicyLocalUserRestrictions.get(userId);
1171 if (!UserRestrictionsUtils.isEmpty(localRestrictions)
1172 && localRestrictions.getBoolean(restrictionKey)) {
1173 // Local restrictions may have been set by device owner the userId of which is
1174 // stored in mGlobalRestrictionOwnerUserId.
1175 if (mGlobalRestrictionOwnerUserId == userId) {
1176 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1177 } else {
1178 result |= UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
1179 }
1180 }
1181 if (!UserRestrictionsUtils.isEmpty(mDevicePolicyGlobalUserRestrictions)
1182 && mDevicePolicyGlobalUserRestrictions.getBoolean(restrictionKey)) {
1183 result |= UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
1184 }
1185 }
1186
1187 return result;
1188 }
1189
1190 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -07001191 * @return UserRestrictions that are in effect currently. This always returns a new
1192 * {@link Bundle}.
1193 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -07001194 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001195 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001196 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001197 }
1198
1199 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001200 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
1201 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001202 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
1203 return false;
1204 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +00001205 synchronized (mRestrictionsLock) {
1206 Bundle bundle = mBaseUserRestrictions.get(userId);
1207 return (bundle != null && bundle.getBoolean(restrictionKey, false));
1208 }
1209 }
1210
1211 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001212 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -07001213 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -08001214 if (!UserRestrictionsUtils.isValidRestriction(key)) {
1215 return;
1216 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001217 synchronized (mRestrictionsLock) {
1218 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
1219 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001220 final Bundle newRestrictions = UserRestrictionsUtils.clone(
1221 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001222 newRestrictions.putBoolean(key, value);
1223
Fyodor Kupolov82402752015-10-28 14:54:51 -07001224 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001225 }
1226 }
1227
Makoto Onuki068c54a2015-10-13 14:34:03 -07001228 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001229 * Optionally updating user restrictions, calculate the effective user restrictions and also
1230 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001231 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001232 * @param newRestrictions User restrictions to set.
1233 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001234 * @param userId target user ID.
1235 */
1236 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07001237 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -07001238 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001239
1240 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
1241 mAppliedUserRestrictions.get(userId));
1242
1243 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001244 if (newRestrictions != null) {
1245 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001246 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
1247
1248 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001249 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1250 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001251
1252 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1253 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001254 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001255 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001256 }
1257
Fyodor Kupolov82402752015-10-28 14:54:51 -07001258 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001259
Makoto Onuki759a7632015-10-28 16:43:10 -07001260 mCachedEffectiveUserRestrictions.put(userId, effective);
1261
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001262 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001263 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001264 debug("Applying user restrictions: userId=" + userId
1265 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001266 }
1267
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001268 if (mAppOpsService != null) { // We skip it until system-ready.
1269 final long token = Binder.clearCallingIdentity();
1270 try {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001271 mAppOpsService.setUserRestrictions(effective, mUserRestriconToken, userId);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001272 } catch (RemoteException e) {
1273 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1274 } finally {
1275 Binder.restoreCallingIdentity(token);
1276 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001277 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001278
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001279 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001280
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001281 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001282 }
1283
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001284 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001285 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001286 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1287 // actually, but we still need some kind of synchronization otherwise we might end up
1288 // calling listeners out-of-order, thus "LR".
1289
1290 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1291 return;
1292 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001293
1294 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1295 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1296
1297 mHandler.post(new Runnable() {
1298 @Override
1299 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001300 UserRestrictionsUtils.applyUserRestrictions(
1301 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001302
Makoto Onukid45a4a22015-11-02 17:17:38 -08001303 final UserRestrictionsListener[] listeners;
1304 synchronized (mUserRestrictionsListeners) {
1305 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1306 mUserRestrictionsListeners.toArray(listeners);
1307 }
1308 for (int i = 0; i < listeners.length; i++) {
1309 listeners[i].onUserRestrictionsChanged(userId,
1310 newRestrictionsFinal, prevRestrictionsFinal);
1311 }
1312 }
1313 });
1314 }
1315
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001316 // Package private for the inner class.
1317 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001318 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001319 }
1320
1321 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001322 // Package private for the inner class.
1323 void applyUserRestrictionsForAllUsersLR() {
1324 if (DBG) {
1325 debug("applyUserRestrictionsForAllUsersLR");
1326 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001327 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001328 mCachedEffectiveUserRestrictions.clear();
1329
Makoto Onuki068c54a2015-10-13 14:34:03 -07001330 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1331 // it on a handler.
1332 final Runnable r = new Runnable() {
1333 @Override
1334 public void run() {
1335 // Then get the list of running users.
1336 final int[] runningUsers;
1337 try {
1338 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1339 } catch (RemoteException e) {
1340 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1341 return;
1342 }
1343 // Then re-calculate the effective restrictions and apply, only for running users.
1344 // It's okay if a new user has started after the getRunningUserIds() call,
1345 // because we'll do the same thing (re-calculate the restrictions and apply)
1346 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001347 synchronized (mRestrictionsLock) {
1348 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001349 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001350 }
1351 }
1352 }
1353 };
1354 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001355 }
1356
Amith Yamasani258848d2012-08-10 17:06:33 -07001357 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001358 * Check if we've hit the limit of how many users can be created.
1359 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001360 private boolean isUserLimitReached() {
1361 int count;
1362 synchronized (mUsersLock) {
1363 count = getAliveUsersExcludingGuestsCountLU();
1364 }
1365 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001366 }
1367
1368 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001369 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001370 checkManageUsersPermission("check if more managed profiles can be added.");
1371 if (ActivityManager.isLowRamDeviceStatic()) {
1372 return false;
1373 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001374 if (!mContext.getPackageManager().hasSystemFeature(
1375 PackageManager.FEATURE_MANAGED_USERS)) {
1376 return false;
1377 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001378 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001379 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1380 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1381 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001382 return false;
1383 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001384 synchronized(mUsersLock) {
1385 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001386 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001387 return false;
1388 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001389 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1390 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001391 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001392 return usersCountAfterRemoving == 1
1393 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001394 }
1395 }
1396
Fyodor Kupolov82402752015-10-28 14:54:51 -07001397 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001398 int aliveUserCount = 0;
1399 final int totalUserCount = mUsers.size();
1400 // Skip over users being removed
1401 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001402 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001403 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001404 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001405 aliveUserCount++;
1406 }
1407 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001408 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001409 }
1410
1411 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001412 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001413 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1414 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1415 * permissions can make certain calls to the UserManager.
1416 *
1417 * @param message used as message if SecurityException is thrown
1418 * @throws SecurityException if the caller does not have enough privilege.
1419 */
1420 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1421 final int uid = Binder.getCallingUid();
1422 if (uid != Process.SYSTEM_UID && uid != 0
1423 && ActivityManager.checkComponentPermission(
1424 Manifest.permission.MANAGE_USERS,
1425 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1426 && ActivityManager.checkComponentPermission(
1427 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1428 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1429 throw new SecurityException(
1430 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1431 + message);
1432 }
1433 }
1434
1435 /**
1436 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001437 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001438 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001439 *
1440 * @param message used as message if SecurityException is thrown
1441 * @throws SecurityException if the caller is not system or root
Tony Mak4dc008c2016-03-16 10:46:49 +00001442 * @see #hasManageUsersPermission()
Amith Yamasani258848d2012-08-10 17:06:33 -07001443 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001444 private static final void checkManageUsersPermission(String message) {
Tony Mak4dc008c2016-03-16 10:46:49 +00001445 if (!hasManageUsersPermission()) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001446 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1447 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001448 }
1449
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001450 /**
Tony Mak4dc008c2016-03-16 10:46:49 +00001451 * @return whether the calling UID is system UID or root's UID or the calling app has the
1452 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
1453 */
1454 private static final boolean hasManageUsersPermission() {
1455 final int callingUid = Binder.getCallingUid();
1456 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
1457 || callingUid == Process.ROOT_UID
1458 || ActivityManager.checkComponentPermission(
1459 android.Manifest.permission.MANAGE_USERS,
1460 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
1461 }
1462
1463 /**
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001464 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1465 * UserManager.
1466 *
1467 * @param message used as message if SecurityException is thrown
1468 * @throws SecurityException if the caller is not system or root
1469 */
1470 private static void checkSystemOrRoot(String message) {
1471 final int uid = Binder.getCallingUid();
1472 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1473 throw new SecurityException("Only system may: " + message);
1474 }
1475 }
1476
Fyodor Kupolov82402752015-10-28 14:54:51 -07001477 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001478 try {
1479 File dir = new File(mUsersDir, Integer.toString(info.id));
1480 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001481 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001482 if (!dir.exists()) {
1483 dir.mkdir();
1484 FileUtils.setPermissions(
1485 dir.getPath(),
1486 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1487 -1, -1);
1488 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001489 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001490 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
Oleksandr Peletskyicd6fa302016-02-25 16:28:39 +01001491 && tmp.renameTo(file) && SELinux.restorecon(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001492 info.iconPath = file.getAbsolutePath();
1493 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001494 try {
1495 os.close();
1496 } catch (IOException ioe) {
1497 // What the ... !
1498 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001499 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001500 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001501 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001502 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001503 }
1504
Amith Yamasani0b285492011-04-14 17:35:23 -07001505 /**
1506 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1507 * cache it elsewhere.
1508 * @return the array of user ids.
1509 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001510 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001511 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001512 return mUserIds;
1513 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001514 }
1515
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001516 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001517 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001518 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001519 return;
1520 }
1521 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001522 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001523 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001524 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001525 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001526 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001527 int type;
1528 while ((type = parser.next()) != XmlPullParser.START_TAG
1529 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001530 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001531 }
1532
1533 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001534 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001535 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001536 return;
1537 }
1538
Amith Yamasani2a003292012-08-14 18:25:45 -07001539 mNextSerialNumber = -1;
1540 if (parser.getName().equals(TAG_USERS)) {
1541 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1542 if (lastSerialNumber != null) {
1543 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1544 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001545 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1546 if (versionNumber != null) {
1547 mUserVersion = Integer.parseInt(versionNumber);
1548 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001549 }
1550
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001551 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1552
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001553 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301554 if (type == XmlPullParser.START_TAG) {
1555 final String name = parser.getName();
1556 if (name.equals(TAG_USER)) {
1557 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001558
Amith Yamasani12747872015-12-07 14:19:49 -08001559 UserData userData = readUserLP(Integer.parseInt(id));
1560
1561 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001562 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001563 mUsers.put(userData.info.id, userData);
1564 if (mNextSerialNumber < 0
1565 || mNextSerialNumber <= userData.info.id) {
1566 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001567 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301568 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001569 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301570 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001571 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1572 && type != XmlPullParser.END_TAG) {
1573 if (type == XmlPullParser.START_TAG) {
1574 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001575 synchronized (mGuestRestrictions) {
1576 UserRestrictionsUtils
1577 .readRestrictions(parser, mGuestRestrictions);
1578 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001579 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1580 ) {
1581 UserRestrictionsUtils.readRestrictions(parser,
1582 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001583 }
1584 break;
1585 }
1586 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001587 } else if (name.equals(TAG_GLOBAL_RESTRICTION_OWNER_ID)) {
1588 String ownerUserId = parser.getAttributeValue(null, ATTR_ID);
1589 if (ownerUserId != null) {
1590 mGlobalRestrictionOwnerUserId = Integer.parseInt(ownerUserId);
1591 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001592 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001593 }
1594 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001595 synchronized (mRestrictionsLock) {
1596 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1597 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001598 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001599 upgradeIfNecessaryLP();
1600 } catch (IOException | XmlPullParserException e) {
1601 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001602 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001603 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001604 }
1605 }
1606
Amith Yamasani6f34b412012-10-22 18:19:27 -07001607 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001608 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001609 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001610 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001611 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001612 int userVersion = mUserVersion;
1613 if (userVersion < 1) {
1614 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001615 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1616 if ("Primary".equals(userData.info.name)) {
1617 userData.info.name =
1618 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1619 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001620 }
1621 userVersion = 1;
1622 }
1623
Amith Yamasanibc9625052012-11-15 14:39:18 -08001624 if (userVersion < 2) {
1625 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001626 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1627 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1628 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1629 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001630 }
1631 userVersion = 2;
1632 }
1633
Amith Yamasani350962c2013-08-06 11:18:53 -07001634
Amith Yamasani5e486f52013-08-07 11:06:44 -07001635 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001636 userVersion = 4;
1637 }
1638
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001639 if (userVersion < 5) {
1640 initDefaultGuestRestrictions();
1641 userVersion = 5;
1642 }
1643
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001644 if (userVersion < 6) {
1645 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001646 synchronized (mUsersLock) {
1647 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001648 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001649 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001650 if (!splitSystemUser && userData.info.isRestricted()
1651 && (userData.info.restrictedProfileParentId
1652 == UserInfo.NO_PROFILE_GROUP_ID)) {
1653 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1654 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001655 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001656 }
1657 }
1658 userVersion = 6;
1659 }
1660
Amith Yamasani6f34b412012-10-22 18:19:27 -07001661 if (userVersion < USER_VERSION) {
1662 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1663 + USER_VERSION);
1664 } else {
1665 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001666
1667 if (originalVersion < mUserVersion) {
1668 writeUserListLP();
1669 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001670 }
1671 }
1672
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001673 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001674 int flags = UserInfo.FLAG_INITIALIZED;
1675 // In split system user mode, the admin and primary flags are assigned to the first human
1676 // user.
1677 if (!UserManager.isSplitSystemUser()) {
1678 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1679 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001680 // Create the system user
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001681 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM, null, null, flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001682 UserData userData = new UserData();
1683 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001684 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001685 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001686 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001687 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001688 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001689
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001690 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001691 synchronized (mRestrictionsLock) {
1692 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1693 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001694
Fyodor Kupolov82402752015-10-28 14:54:51 -07001695 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001696 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001697
Amith Yamasani12747872015-12-07 14:19:49 -08001698 writeUserLP(userData);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001699 writeUserListLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001700 }
1701
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001702 private String getOwnerName() {
1703 return mContext.getResources().getString(com.android.internal.R.string.owner_name);
1704 }
1705
Amith Yamasani12747872015-12-07 14:19:49 -08001706 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707 if (DBG) {
1708 debug("scheduleWriteUser");
1709 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001710 // No need to wrap it within a lock -- worst case, we'll just post the same message
1711 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001712 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1713 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001714 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1715 }
1716 }
1717
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001718 /*
1719 * Writes the user file in this format:
1720 *
1721 * <user flags="20039023" id="0">
1722 * <name>Primary</name>
1723 * </user>
1724 */
Amith Yamasani12747872015-12-07 14:19:49 -08001725 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001726 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001727 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001728 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001729 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001730 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001731 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001732 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001733 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1734
1735 // XmlSerializer serializer = XmlUtils.serializerInstance();
1736 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001737 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001738 serializer.startDocument(null, true);
1739 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1740
Amith Yamasani12747872015-12-07 14:19:49 -08001741 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001742 serializer.startTag(null, TAG_USER);
1743 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001744 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001745 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001746 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1747 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1748 Long.toString(userInfo.lastLoggedInTime));
Jeff Sharkeycd575992016-03-29 14:12:49 -06001749 if (userInfo.lastLoggedInFingerprint != null) {
1750 serializer.attribute(null, ATTR_LAST_LOGGED_IN_FINGERPRINT,
1751 userInfo.lastLoggedInFingerprint);
1752 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001753 if (userInfo.iconPath != null) {
1754 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1755 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001756 if (userInfo.partial) {
1757 serializer.attribute(null, ATTR_PARTIAL, "true");
1758 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001759 if (userInfo.guestToRemove) {
1760 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1761 }
Kenny Guy2a764942014-04-02 13:29:20 +01001762 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1763 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1764 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001765 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001766 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1767 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1768 Integer.toString(userInfo.restrictedProfileParentId));
1769 }
Amith Yamasani12747872015-12-07 14:19:49 -08001770 // Write seed data
1771 if (userData.persistSeedData) {
1772 if (userData.seedAccountName != null) {
1773 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1774 }
1775 if (userData.seedAccountType != null) {
1776 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1777 }
1778 }
Amith Yamasani6f48d6e2016-03-23 14:28:25 -07001779 if (userInfo.name != null) {
1780 serializer.startTag(null, TAG_NAME);
1781 serializer.text(userInfo.name);
1782 serializer.endTag(null, TAG_NAME);
1783 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001784 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001785 UserRestrictionsUtils.writeRestrictions(serializer,
1786 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1787 UserRestrictionsUtils.writeRestrictions(serializer,
1788 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1789 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001790 }
Amith Yamasani12747872015-12-07 14:19:49 -08001791
1792 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001793 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001794 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001795 serializer.endTag(null, TAG_ACCOUNT);
1796 }
1797
Amith Yamasani12747872015-12-07 14:19:49 -08001798 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1799 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1800 userData.seedAccountOptions.saveToXml(serializer);
1801 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1802 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001803 serializer.endTag(null, TAG_USER);
1804
1805 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001806 userFile.finishWrite(fos);
1807 } catch (Exception ioe) {
Jeff Sharkeycd575992016-03-29 14:12:49 -06001808 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id, ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001809 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001810 }
1811 }
1812
1813 /*
1814 * Writes the user list file in this format:
1815 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001816 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001817 * <user id="0"></user>
1818 * <user id="2"></user>
1819 * </users>
1820 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001821 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001822 if (DBG) {
1823 debug("writeUserList");
1824 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001825 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001826 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001827 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001828 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001829 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1830
1831 // XmlSerializer serializer = XmlUtils.serializerInstance();
1832 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001833 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001834 serializer.startDocument(null, true);
1835 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1836
1837 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001838 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001839 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001840
Adam Lesinskieddeb492014-09-08 17:50:03 -07001841 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001842 synchronized (mGuestRestrictions) {
1843 UserRestrictionsUtils
1844 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1845 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301846 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001847 synchronized (mRestrictionsLock) {
1848 UserRestrictionsUtils.writeRestrictions(serializer,
1849 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1850 }
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01001851 serializer.startTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
1852 serializer.attribute(null, ATTR_ID, Integer.toString(mGlobalRestrictionOwnerUserId));
1853 serializer.endTag(null, TAG_GLOBAL_RESTRICTION_OWNER_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001854 int[] userIdsToWrite;
1855 synchronized (mUsersLock) {
1856 userIdsToWrite = new int[mUsers.size()];
1857 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001858 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001859 userIdsToWrite[i] = user.id;
1860 }
1861 }
1862 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001863 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001864 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001865 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001866 }
1867
1868 serializer.endTag(null, TAG_USERS);
1869
1870 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001871 userListFile.finishWrite(fos);
1872 } catch (Exception e) {
1873 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001874 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001875 }
1876 }
1877
Amith Yamasani12747872015-12-07 14:19:49 -08001878 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001879 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001880 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001881 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001882 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001883 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001884 long creationTime = 0L;
1885 long lastLoggedInTime = 0L;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001886 String lastLoggedInFingerprint = null;
Kenny Guy2a764942014-04-02 13:29:20 +01001887 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001888 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001889 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001890 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001891 boolean persistSeedData = false;
1892 String seedAccountName = null;
1893 String seedAccountType = null;
1894 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001895 Bundle baseRestrictions = new Bundle();
1896 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001897
1898 FileInputStream fis = null;
1899 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001900 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001901 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001902 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001903 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001904 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001905 int type;
1906 while ((type = parser.next()) != XmlPullParser.START_TAG
1907 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001908 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001909 }
1910
1911 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001912 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001913 return null;
1914 }
1915
1916 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001917 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1918 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001919 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001920 return null;
1921 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001922 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1923 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001924 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001925 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1926 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001927 lastLoggedInFingerprint = parser.getAttributeValue(null,
1928 ATTR_LAST_LOGGED_IN_FINGERPRINT);
Kenny Guy2a764942014-04-02 13:29:20 +01001929 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1930 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001931 restrictedProfileParentId = readIntAttribute(parser,
1932 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001933 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1934 if ("true".equals(valueString)) {
1935 partial = true;
1936 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001937 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1938 if ("true".equals(valueString)) {
1939 guestToRemove = true;
1940 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001941
Amith Yamasani12747872015-12-07 14:19:49 -08001942 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1943 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1944 if (seedAccountName != null || seedAccountType != null) {
1945 persistSeedData = true;
1946 }
1947
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001948 int outerDepth = parser.getDepth();
1949 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1950 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1951 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1952 continue;
1953 }
1954 String tag = parser.getName();
1955 if (TAG_NAME.equals(tag)) {
1956 type = parser.next();
1957 if (type == XmlPullParser.TEXT) {
1958 name = parser.getText();
1959 }
1960 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001961 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1962 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1963 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001964 } else if (TAG_ACCOUNT.equals(tag)) {
1965 type = parser.next();
1966 if (type == XmlPullParser.TEXT) {
1967 account = parser.getText();
1968 }
Amith Yamasani12747872015-12-07 14:19:49 -08001969 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1970 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1971 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001972 }
1973 }
1974 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001975
Amith Yamasani12747872015-12-07 14:19:49 -08001976 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001977 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001978 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001979 userInfo.creationTime = creationTime;
1980 userInfo.lastLoggedInTime = lastLoggedInTime;
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06001981 userInfo.lastLoggedInFingerprint = lastLoggedInFingerprint;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001982 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001983 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001984 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001985 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001986
1987 // Create the UserData object that's internal to this class
1988 UserData userData = new UserData();
1989 userData.info = userInfo;
1990 userData.account = account;
1991 userData.seedAccountName = seedAccountName;
1992 userData.seedAccountType = seedAccountType;
1993 userData.persistSeedData = persistSeedData;
1994 userData.seedAccountOptions = seedAccountOptions;
1995
Makoto Onuki068c54a2015-10-13 14:34:03 -07001996 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001997 mBaseUserRestrictions.put(id, baseRestrictions);
1998 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001999 }
Amith Yamasani12747872015-12-07 14:19:49 -08002000 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002001 } catch (IOException ioe) {
2002 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08002003 } finally {
2004 if (fis != null) {
2005 try {
2006 fis.close();
2007 } catch (IOException e) {
2008 }
2009 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002010 }
2011 return null;
2012 }
2013
Amith Yamasani920ace02012-09-20 22:15:37 -07002014 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
2015 String valueString = parser.getAttributeValue(null, attr);
2016 if (valueString == null) return defaultValue;
2017 try {
2018 return Integer.parseInt(valueString);
2019 } catch (NumberFormatException nfe) {
2020 return defaultValue;
2021 }
2022 }
2023
2024 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
2025 String valueString = parser.getAttributeValue(null, attr);
2026 if (valueString == null) return defaultValue;
2027 try {
2028 return Long.parseLong(valueString);
2029 } catch (NumberFormatException nfe) {
2030 return defaultValue;
2031 }
2032 }
2033
Amith Yamasanib82add22013-07-09 11:24:44 -07002034 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002035 * Removes the app restrictions file for a specific package and user id, if it exists.
2036 */
2037 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
2038 synchronized (mPackagesLock) {
2039 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07002040 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002041 if (resFile.exists()) {
2042 resFile.delete();
2043 }
2044 }
2045 }
2046
Kenny Guya52dc3e2014-02-11 15:33:14 +00002047 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01002048 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00002049 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01002050 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002051 }
2052
Amith Yamasani258848d2012-08-10 17:06:33 -07002053 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07002054 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002055 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002056 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002057 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07002058
Jessica Hummelbe81c802014-04-22 15:49:22 +01002059 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002060 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04002061 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
2062 return null;
2063 }
phweisse9c44062016-02-10 12:57:38 +01002064 return createUserInternalUnchecked(name, flags, parentId);
2065 }
2066
2067 private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07002068 if (ActivityManager.isLowRamDeviceStatic()) {
2069 return null;
2070 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002071 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07002072 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002073 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002074 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002075 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002076 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07002077 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002078 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002079 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002080 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002081 if (parentId != UserHandle.USER_NULL) {
2082 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002083 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00002084 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002085 if (parent == null) return null;
2086 }
2087 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
2088 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
2089 return null;
2090 }
2091 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
2092 // If we're not adding a guest user or a managed profile and the limit has
2093 // been reached, cannot add a user.
2094 return null;
2095 }
2096 // If we're adding a guest and there already exists one, bail.
2097 if (isGuest && findCurrentGuestUser() != null) {
2098 return null;
2099 }
2100 // In legacy mode, restricted profile's parent can only be the owner user
2101 if (isRestricted && !UserManager.isSplitSystemUser()
2102 && (parentId != UserHandle.USER_SYSTEM)) {
2103 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
2104 return null;
2105 }
2106 if (isRestricted && UserManager.isSplitSystemUser()) {
2107 if (parent == null) {
2108 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
2109 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07002110 return null;
2111 }
Amith Yamasani12747872015-12-07 14:19:49 -08002112 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002113 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
2114 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07002115 return null;
2116 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002117 }
Lenka Trochtova024f9792016-02-17 13:55:17 +01002118 if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0) {
2119 Log.e(LOG_TAG,
2120 "Ephemeral users are supported on split-system-user systems only.");
2121 return null;
2122 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002123 // In split system user mode, we assign the first human user the primary flag.
2124 // And if there is no device owner, we also assign the admin flag to primary user.
2125 if (UserManager.isSplitSystemUser()
2126 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
2127 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08002128 synchronized (mUsersLock) {
2129 if (!mIsDeviceManaged) {
2130 flags |= UserInfo.FLAG_ADMIN;
2131 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07002132 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002133 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002134
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002135 userId = getNextAvailableId();
2136 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01002137 boolean ephemeralGuests = Resources.getSystem()
2138 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002139
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002140 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002141 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
2142 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
2143 || (parent != null && parent.info.isEphemeral())) {
2144 flags |= UserInfo.FLAG_EPHEMERAL;
2145 }
2146
2147 userInfo = new UserInfo(userId, name, null, flags);
2148 userInfo.serialNumber = mNextSerialNumber++;
2149 long now = System.currentTimeMillis();
2150 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
2151 userInfo.partial = true;
Fyodor Kupolov83c24242016-03-31 13:30:42 -07002152 userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002153 userData = new UserData();
2154 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08002155 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002156 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002157 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002158 writeUserListLP();
2159 if (parent != null) {
2160 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08002161 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
2162 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002163 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00002164 }
Amith Yamasani12747872015-12-07 14:19:49 -08002165 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002166 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08002167 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
2168 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002169 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002170 }
Amith Yamasani12747872015-12-07 14:19:49 -08002171 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07002172 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002173 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07002174 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002175 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002176 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002177 mPm.prepareUserData(userId, userInfo.serialNumber,
Jeff Sharkey47f71082016-02-01 17:03:54 -07002178 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002179 mPm.createNewUser(userId);
2180 userInfo.partial = false;
2181 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002182 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002183 }
2184 updateUserIds();
2185 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08002186 if (isGuest) {
2187 synchronized (mGuestRestrictions) {
2188 restrictions.putAll(mGuestRestrictions);
2189 }
2190 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002191 synchronized (mRestrictionsLock) {
2192 mBaseUserRestrictions.append(userId, restrictions);
2193 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002194 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
2195 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2196 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
2197 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08002198 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002199 } finally {
2200 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07002201 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002202 return userInfo;
2203 }
2204
Amith Yamasani0b285492011-04-14 17:35:23 -07002205 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002206 * @hide
2207 */
Amith Yamasani12747872015-12-07 14:19:49 -08002208 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002209 public UserInfo createRestrictedProfile(String name, int parentUserId) {
2210 checkManageUsersPermission("setupRestrictedProfile");
2211 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
2212 if (user == null) {
2213 return null;
2214 }
Fyodor Kupolov9e912ba2016-02-09 18:29:43 -08002215 long identity = Binder.clearCallingIdentity();
2216 try {
2217 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
2218 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
2219 // the putIntForUser() will fail.
2220 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
2221 android.provider.Settings.Secure.LOCATION_MODE,
2222 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
2223 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
2224 } finally {
2225 Binder.restoreCallingIdentity(identity);
2226 }
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002227 return user;
2228 }
2229
2230 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07002231 * Find the current guest user. If the Guest user is partial,
2232 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07002233 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002234 private UserInfo findCurrentGuestUser() {
2235 synchronized (mUsersLock) {
2236 final int size = mUsers.size();
2237 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002238 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002239 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
2240 return user;
2241 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002242 }
2243 }
2244 return null;
2245 }
2246
2247 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07002248 * Mark this guest user for deletion to allow us to create another guest
2249 * and switch to that user before actually removing this guest.
2250 * @param userHandle the userid of the current guest
2251 * @return whether the user could be marked for deletion
2252 */
Amith Yamasani12747872015-12-07 14:19:49 -08002253 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07002254 public boolean markGuestForDeletion(int userHandle) {
2255 checkManageUsersPermission("Only the system can remove users");
2256 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2257 UserManager.DISALLOW_REMOVE_USER, false)) {
2258 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2259 return false;
2260 }
2261
2262 long ident = Binder.clearCallingIdentity();
2263 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002264 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07002265 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002266 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002267 userData = mUsers.get(userHandle);
2268 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002269 return false;
2270 }
Amith Yamasani1df14732014-08-29 21:37:27 -07002271 }
Amith Yamasani12747872015-12-07 14:19:49 -08002272 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07002273 return false;
2274 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07002275 // We set this to a guest user that is to be removed. This is a temporary state
2276 // where we are allowed to add new Guest users, even if this one is still not
2277 // removed. This user will still show up in getUserInfo() calls.
2278 // If we don't get around to removing this Guest user, it will be purged on next
2279 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002280 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002281 // Mark it as disabled, so that it isn't returned any more when
2282 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002283 userData.info.flags |= UserInfo.FLAG_DISABLED;
2284 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002285 }
2286 } finally {
2287 Binder.restoreCallingIdentity(ident);
2288 }
2289 return true;
2290 }
2291
2292 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002293 * Removes a user and all data directories created for that user. This method should be called
2294 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002295 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002296 */
Amith Yamasani12747872015-12-07 14:19:49 -08002297 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002298 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002299 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002300 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2301 UserManager.DISALLOW_REMOVE_USER, false)) {
2302 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2303 return false;
2304 }
2305
Kenny Guyee58b4f2014-05-23 15:19:53 +01002306 long ident = Binder.clearCallingIdentity();
2307 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002308 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002309 int currentUser = ActivityManager.getCurrentUser();
2310 if (currentUser == userHandle) {
2311 Log.w(LOG_TAG, "Current user cannot be removed");
2312 return false;
2313 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002314 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002315 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002316 userData = mUsers.get(userHandle);
2317 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002318 return false;
2319 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002320
Fyodor Kupolov82402752015-10-28 14:54:51 -07002321 // We remember deleted user IDs to prevent them from being
2322 // reused during the current boot; they can still be reused
2323 // after a reboot.
2324 mRemovingUserIds.put(userHandle, true);
2325 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002326
Kenny Guyee58b4f2014-05-23 15:19:53 +01002327 try {
2328 mAppOpsService.removeUser(userHandle);
2329 } catch (RemoteException e) {
2330 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2331 }
2332 // Set this to a partially created user, so that the user will be purged
2333 // on next startup, in case the runtime stops now before stopping and
2334 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002335 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002336 // Mark it as disabled, so that it isn't returned any more when
2337 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002338 userData.info.flags |= UserInfo.FLAG_DISABLED;
2339 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002340 }
2341
Amith Yamasani12747872015-12-07 14:19:49 -08002342 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2343 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002344 // Send broadcast to notify system that the user removed was a
2345 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002346 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002347 }
2348
2349 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2350 int res;
2351 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002352 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2353 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002354 @Override
2355 public void userStopped(int userId) {
2356 finishRemoveUser(userId);
2357 }
2358 @Override
2359 public void userStopAborted(int userId) {
2360 }
2361 });
2362 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002363 return false;
2364 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002365 return res == ActivityManager.USER_OP_SUCCESS;
2366 } finally {
2367 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002368 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002369 }
2370
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002371 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002372 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002373 // Let other services shutdown any activity and clean up their state before completely
2374 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002375 long ident = Binder.clearCallingIdentity();
2376 try {
2377 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2378 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002379 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2380 android.Manifest.permission.MANAGE_USERS,
2381
2382 new BroadcastReceiver() {
2383 @Override
2384 public void onReceive(Context context, Intent intent) {
2385 if (DBG) {
2386 Slog.i(LOG_TAG,
2387 "USER_REMOVED broadcast sent, cleaning up user data "
2388 + userHandle);
2389 }
2390 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002391 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002392 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002393 // Clean up any ActivityManager state
2394 LocalServices.getService(ActivityManagerInternal.class)
2395 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002396 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002397 }
2398 }.start();
2399 }
2400 },
2401
2402 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002403 } finally {
2404 Binder.restoreCallingIdentity(ident);
2405 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002406 }
2407
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002408 private void removeUserState(final int userHandle) {
Paul Crowley91293792016-03-25 15:23:07 -07002409 try {
2410 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
2411 } catch (IllegalStateException e) {
2412 // This may be simply because the user was partially created.
2413 Slog.i(LOG_TAG,
2414 "Destroying key for user " + userHandle + " failed, continuing anyway", e);
2415 }
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002416
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002417 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002418 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002419 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002420 synchronized (mUsersLock) {
2421 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002422 mIsUserManaged.delete(userHandle);
Fyodor Kupolovac06a492016-05-25 14:45:29 -07002423 }
2424 synchronized (mUserStates) {
2425 mUserStates.delete(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002426 }
2427 synchronized (mRestrictionsLock) {
2428 mBaseUserRestrictions.remove(userHandle);
2429 mAppliedUserRestrictions.remove(userHandle);
2430 mCachedEffectiveUserRestrictions.remove(userHandle);
2431 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002432 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002433 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002434 synchronized (mPackagesLock) {
2435 writeUserListLP();
2436 }
Jeff Sharkeycd575992016-03-29 14:12:49 -06002437 // Remove user file
2438 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
2439 userFile.delete();
Fyodor Kupolov82402752015-10-28 14:54:51 -07002440 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002441
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002442 // Now that we've purged all the metadata above, destroy the actual data
2443 // on disk; if we battery pull in here we'll finish cleaning up when
2444 // reconciling after reboot.
2445 mPm.destroyUserData(userHandle,
2446 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
Amith Yamasani61f57372012-08-31 12:12:28 -07002447 }
2448
Kenny Guyf8d3a232014-05-15 16:09:52 +01002449 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002450 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002451 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2452 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002453 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002454 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002455 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002456 }
2457
Amith Yamasani2a003292012-08-14 18:25:45 -07002458 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002459 public Bundle getApplicationRestrictions(String packageName) {
2460 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2461 }
2462
2463 @Override
2464 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002465 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002466 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002467 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002468 }
2469 synchronized (mPackagesLock) {
2470 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002471 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002472 }
2473 }
2474
2475 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002476 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002477 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002478 checkSystemOrRoot("set application restrictions");
Fyodor Kupolov0d88d542016-04-19 11:37:22 -07002479 if (restrictions != null) {
2480 restrictions.setDefusable(true);
2481 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002482 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002483 if (restrictions == null || restrictions.isEmpty()) {
2484 cleanAppRestrictionsForPackage(packageName, userId);
2485 } else {
2486 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002487 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002488 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002489 }
Robin Lee66e5d962014-04-09 16:44:21 +01002490
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002491 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2492 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2493 changeIntent.setPackage(packageName);
2494 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2495 mContext.sendBroadcastAsUser(changeIntent, UserHandle.of(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002496 }
2497
2498 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002499 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002500 try {
2501 return mContext.getPackageManager().getApplicationInfo(packageName,
Fyodor Kupolovd2846122016-02-11 18:06:34 -08002502 PackageManager.MATCH_UNINSTALLED_PACKAGES).uid;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002503 } catch (NameNotFoundException nnfe) {
2504 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002505 } finally {
2506 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002507 }
2508 }
2509
Fyodor Kupolov82402752015-10-28 14:54:51 -07002510 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002511 AtomicFile restrictionsFile =
2512 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2513 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002514 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002515 }
2516
2517 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002518 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002519 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002520 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002521 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002522 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002523 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002524
2525 FileInputStream fis = null;
2526 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002527 fis = restrictionsFile.openRead();
2528 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002529 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002530 XmlUtils.nextElement(parser);
2531 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002532 Slog.e(LOG_TAG, "Unable to read restrictions file "
2533 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002534 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002535 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002536 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2537 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002538 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002539 } catch (IOException|XmlPullParserException e) {
2540 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002541 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002542 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002543 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002544 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002545 }
2546
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002547 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2548 XmlPullParser parser) throws XmlPullParserException, IOException {
2549 int type = parser.getEventType();
2550 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2551 String key = parser.getAttributeValue(null, ATTR_KEY);
2552 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2553 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2554 if (multiple != null) {
2555 values.clear();
2556 int count = Integer.parseInt(multiple);
2557 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2558 if (type == XmlPullParser.START_TAG
2559 && parser.getName().equals(TAG_VALUE)) {
2560 values.add(parser.nextText().trim());
2561 count--;
2562 }
2563 }
2564 String [] valueStrings = new String[values.size()];
2565 values.toArray(valueStrings);
2566 restrictions.putStringArray(key, valueStrings);
2567 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2568 restrictions.putBundle(key, readBundleEntry(parser, values));
2569 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2570 final int outerDepth = parser.getDepth();
2571 ArrayList<Bundle> bundleList = new ArrayList<>();
2572 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2573 Bundle childBundle = readBundleEntry(parser, values);
2574 bundleList.add(childBundle);
2575 }
2576 restrictions.putParcelableArray(key,
2577 bundleList.toArray(new Bundle[bundleList.size()]));
2578 } else {
2579 String value = parser.nextText().trim();
2580 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2581 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2582 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2583 restrictions.putInt(key, Integer.parseInt(value));
2584 } else {
2585 restrictions.putString(key, value);
2586 }
2587 }
2588 }
2589 }
2590
2591 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2592 throws IOException, XmlPullParserException {
2593 Bundle childBundle = new Bundle();
2594 final int outerDepth = parser.getDepth();
2595 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2596 readEntry(childBundle, values, parser);
2597 }
2598 return childBundle;
2599 }
2600
Fyodor Kupolov82402752015-10-28 14:54:51 -07002601 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002602 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002603 AtomicFile restrictionsFile = new AtomicFile(
2604 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002605 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002606 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002607 }
2608
2609 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002610 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002611 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002612 try {
2613 fos = restrictionsFile.startWrite();
2614 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2615
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002616 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002617 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002618 serializer.startDocument(null, true);
2619 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2620
2621 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002622 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002623 serializer.endTag(null, TAG_RESTRICTIONS);
2624
2625 serializer.endDocument();
2626 restrictionsFile.finishWrite(fos);
2627 } catch (Exception e) {
2628 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002629 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2630 }
2631 }
2632
2633 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2634 throws IOException {
2635 for (String key : restrictions.keySet()) {
2636 Object value = restrictions.get(key);
2637 serializer.startTag(null, TAG_ENTRY);
2638 serializer.attribute(null, ATTR_KEY, key);
2639
2640 if (value instanceof Boolean) {
2641 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2642 serializer.text(value.toString());
2643 } else if (value instanceof Integer) {
2644 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2645 serializer.text(value.toString());
2646 } else if (value == null || value instanceof String) {
2647 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2648 serializer.text(value != null ? (String) value : "");
2649 } else if (value instanceof Bundle) {
2650 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2651 writeBundle((Bundle) value, serializer);
2652 } else if (value instanceof Parcelable[]) {
2653 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2654 Parcelable[] array = (Parcelable[]) value;
2655 for (Parcelable parcelable : array) {
2656 if (!(parcelable instanceof Bundle)) {
2657 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2658 }
2659 serializer.startTag(null, TAG_ENTRY);
2660 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2661 writeBundle((Bundle) parcelable, serializer);
2662 serializer.endTag(null, TAG_ENTRY);
2663 }
2664 } else {
2665 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2666 String[] values = (String[]) value;
2667 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2668 for (String choice : values) {
2669 serializer.startTag(null, TAG_VALUE);
2670 serializer.text(choice != null ? choice : "");
2671 serializer.endTag(null, TAG_VALUE);
2672 }
2673 }
2674 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002675 }
2676 }
2677
2678 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002679 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002680 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002681 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002682 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002683 }
2684 }
2685
2686 @Override
2687 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002688 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002689 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002690 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002691 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002692 }
2693 // Not found
2694 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002695 }
2696 }
2697
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002698 @Override
2699 public long getUserCreationTime(int userHandle) {
2700 int callingUserId = UserHandle.getCallingUserId();
2701 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002702 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002703 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002704 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002705 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002706 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002707 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002708 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002709 }
2710 }
2711 }
2712 if (userInfo == null) {
2713 throw new SecurityException("userHandle can only be the calling user or a managed "
2714 + "profile associated with this user");
2715 }
2716 return userInfo.creationTime;
2717 }
2718
Amith Yamasani0b285492011-04-14 17:35:23 -07002719 /**
2720 * Caches the list of user ids in an array, adjusting the array size when necessary.
2721 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002722 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002723 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002724 synchronized (mUsersLock) {
2725 final int userSize = mUsers.size();
2726 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002727 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002728 num++;
2729 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002730 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002731 final int[] newUsers = new int[num];
2732 int n = 0;
2733 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002734 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002735 newUsers[n++] = mUsers.keyAt(i);
2736 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002737 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002738 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002739 }
2740 }
2741
2742 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002743 * Called right before a user is started. This gives us a chance to prepare
2744 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002745 */
2746 public void onBeforeStartUser(int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002747 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002748 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002749 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_DE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002750
2751 if (userId != UserHandle.USER_SYSTEM) {
2752 synchronized (mRestrictionsLock) {
2753 applyUserRestrictionsLR(userId);
2754 }
Fyodor Kupolovb45d9832016-05-16 13:25:34 -07002755 UserInfo userInfo = getUserInfoNoChecks(userId);
2756 if (userInfo != null && !userInfo.isInitialized()) {
2757 mPm.onBeforeUserStartUninitialized(userId);
2758 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002759 }
2760 }
2761
2762 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002763 * Called right before a user is unlocked. This gives us a chance to prepare
2764 * app storage.
2765 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002766 public void onBeforeUnlockUser(@UserIdInt int userId) {
Jeff Sharkey47f71082016-02-01 17:03:54 -07002767 final int userSerial = getUserSerialNumber(userId);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002768 mPm.prepareUserData(userId, userSerial, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey47f71082016-02-01 17:03:54 -07002769 mPm.reconcileAppsData(userId, StorageManager.FLAG_STORAGE_CE);
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002770 }
2771
2772 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002773 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002774 * @param userId the user that was just foregrounded
2775 */
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002776 public void onUserLoggedIn(@UserIdInt int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002777 UserData userData = getUserDataNoChecks(userId);
2778 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002779 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2780 return;
2781 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002782
2783 final long now = System.currentTimeMillis();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002784 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002785 userData.info.lastLoggedInTime = now;
Amith Yamasani920ace02012-09-20 22:15:37 -07002786 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06002787 userData.info.lastLoggedInFingerprint = Build.FINGERPRINT;
2788 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002789 }
2790
2791 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002792 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002793 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2794 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002795 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002796 private int getNextAvailableId() {
2797 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002798 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002799 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002800 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002801 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002802 }
2803 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002804 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002805 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002806 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002807 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002808
Amith Yamasanifc95e702013-09-26 13:20:17 -07002809 private String packageToRestrictionsFileName(String packageName) {
2810 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2811 }
2812
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002813 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002814 * Enforce that serial number stored in user directory inode matches the
2815 * given expected value. Gracefully sets the serial number if currently
2816 * undefined.
2817 *
2818 * @throws IOException when problem extracting serial number, or serial
2819 * number is mismatched.
2820 */
2821 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2822 final int foundSerial = getSerialNumber(file);
2823 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2824
2825 if (foundSerial == -1) {
2826 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2827 try {
2828 setSerialNumber(file, serialNumber);
2829 } catch (IOException e) {
2830 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2831 }
2832
2833 } else if (foundSerial != serialNumber) {
2834 throw new IOException("Found serial number " + foundSerial
2835 + " doesn't match expected " + serialNumber);
2836 }
2837 }
2838
2839 /**
2840 * Set serial number stored in user directory inode.
2841 *
2842 * @throws IOException if serial number was already set
2843 */
2844 private static void setSerialNumber(File file, int serialNumber)
2845 throws IOException {
2846 try {
2847 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2848 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2849 } catch (ErrnoException e) {
2850 throw e.rethrowAsIOException();
2851 }
2852 }
2853
2854 /**
2855 * Return serial number stored in user directory inode.
2856 *
2857 * @return parsed serial number, or -1 if not set
2858 */
2859 private static int getSerialNumber(File file) throws IOException {
2860 try {
2861 final byte[] buf = new byte[256];
2862 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2863 final String serial = new String(buf, 0, len);
2864 try {
2865 return Integer.parseInt(serial);
2866 } catch (NumberFormatException e) {
2867 throw new IOException("Bad serial number: " + serial);
2868 }
2869 } catch (ErrnoException e) {
2870 if (e.errno == OsConstants.ENODATA) {
2871 return -1;
2872 } else {
2873 throw e.rethrowAsIOException();
2874 }
2875 }
2876 }
2877
Amith Yamasani920ace02012-09-20 22:15:37 -07002878 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002879 public void setSeedAccountData(int userId, String accountName, String accountType,
2880 PersistableBundle accountOptions, boolean persist) {
2881 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2882 synchronized (mPackagesLock) {
2883 final UserData userData;
2884 synchronized (mUsersLock) {
2885 userData = getUserDataLU(userId);
2886 if (userData == null) {
2887 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2888 return;
2889 }
2890 userData.seedAccountName = accountName;
2891 userData.seedAccountType = accountType;
2892 userData.seedAccountOptions = accountOptions;
2893 userData.persistSeedData = persist;
2894 }
2895 if (persist) {
2896 writeUserLP(userData);
2897 }
2898 }
2899 }
2900
2901 @Override
2902 public String getSeedAccountName() throws RemoteException {
2903 checkManageUsersPermission("Cannot get seed account information");
2904 synchronized (mUsersLock) {
2905 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2906 return userData.seedAccountName;
2907 }
2908 }
2909
2910 @Override
2911 public String getSeedAccountType() throws RemoteException {
2912 checkManageUsersPermission("Cannot get seed account information");
2913 synchronized (mUsersLock) {
2914 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2915 return userData.seedAccountType;
2916 }
2917 }
2918
2919 @Override
2920 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2921 checkManageUsersPermission("Cannot get seed account information");
2922 synchronized (mUsersLock) {
2923 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2924 return userData.seedAccountOptions;
2925 }
2926 }
2927
2928 @Override
2929 public void clearSeedAccountData() throws RemoteException {
2930 checkManageUsersPermission("Cannot clear seed account information");
2931 synchronized (mPackagesLock) {
2932 UserData userData;
2933 synchronized (mUsersLock) {
2934 userData = getUserDataLU(UserHandle.getCallingUserId());
2935 if (userData == null) return;
2936 userData.clearSeedAccountData();
2937 }
2938 writeUserLP(userData);
2939 }
2940 }
2941
2942 @Override
2943 public boolean someUserHasSeedAccount(String accountName, String accountType)
2944 throws RemoteException {
2945 checkManageUsersPermission("Cannot check seed account information");
2946 synchronized (mUsersLock) {
2947 final int userSize = mUsers.size();
2948 for (int i = 0; i < userSize; i++) {
2949 final UserData data = mUsers.valueAt(i);
2950 if (data.info.isInitialized()) continue;
2951 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2952 continue;
2953 }
2954 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2955 continue;
2956 }
2957 return true;
2958 }
2959 }
2960 return false;
2961 }
2962
2963 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002964 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2965 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2966 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2967 }
2968
2969 int onShellCommand(Shell shell, String cmd) {
2970 if (cmd == null) {
2971 return shell.handleDefaultCommands(cmd);
2972 }
2973
2974 final PrintWriter pw = shell.getOutPrintWriter();
2975 try {
2976 switch(cmd) {
2977 case "list":
2978 return runList(pw);
2979 }
2980 } catch (RemoteException e) {
2981 pw.println("Remote exception: " + e);
2982 }
2983 return -1;
2984 }
2985
2986 private int runList(PrintWriter pw) throws RemoteException {
2987 final IActivityManager am = ActivityManagerNative.getDefault();
2988 final List<UserInfo> users = getUsers(false);
2989 if (users == null) {
2990 pw.println("Error: couldn't get users");
2991 return 1;
2992 } else {
2993 pw.println("Users:");
2994 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002995 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002996 pw.println("\t" + users.get(i).toString() + running);
2997 }
2998 return 0;
2999 }
3000 }
3001
3002 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07003003 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3004 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3005 != PackageManager.PERMISSION_GRANTED) {
3006 pw.println("Permission Denial: can't dump UserManager from from pid="
3007 + Binder.getCallingPid()
3008 + ", uid=" + Binder.getCallingUid()
3009 + " without permission "
3010 + android.Manifest.permission.DUMP);
3011 return;
3012 }
3013
3014 long now = System.currentTimeMillis();
3015 StringBuilder sb = new StringBuilder();
3016 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003017 synchronized (mUsersLock) {
3018 pw.println("Users:");
3019 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08003020 UserData userData = mUsers.valueAt(i);
3021 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003022 continue;
3023 }
Amith Yamasani12747872015-12-07 14:19:49 -08003024 UserInfo userInfo = userData.info;
3025 final int userId = userInfo.id;
3026 pw.print(" "); pw.print(userInfo);
3027 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08003028 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003029 pw.print(" <removing> ");
3030 }
Amith Yamasani12747872015-12-07 14:19:49 -08003031 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003032 pw.print(" <partial>");
3033 }
3034 pw.println();
3035 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003036 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003037 pw.println("<unknown>");
3038 } else {
3039 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003040 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003041 sb.append(" ago");
3042 pw.println(sb);
3043 }
3044 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08003045 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07003046 pw.println("<unknown>");
3047 } else {
3048 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08003049 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07003050 sb.append(" ago");
3051 pw.println(sb);
3052 }
Jeff Sharkeybd91e2f2016-03-22 15:32:31 -06003053 pw.print(" Last logged in fingerprint: ");
3054 pw.println(userInfo.lastLoggedInFingerprint);
Makoto Onukie7927da2015-11-25 10:05:17 -08003055 pw.print(" Has profile owner: ");
3056 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003057 pw.println(" Restrictions:");
3058 synchronized (mRestrictionsLock) {
3059 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003060 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003061 pw.println(" Device policy local restrictions:");
3062 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003063 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003064 pw.println(" Effective restrictions:");
3065 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08003066 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003067 }
Amith Yamasani12747872015-12-07 14:19:49 -08003068
3069 if (userData.account != null) {
3070 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08003071 pw.println();
3072 }
Amith Yamasani12747872015-12-07 14:19:49 -08003073
3074 if (userData.seedAccountName != null) {
3075 pw.print(" Seed account name: " + userData.seedAccountName);
3076 pw.println();
3077 if (userData.seedAccountType != null) {
3078 pw.print(" account type: " + userData.seedAccountType);
3079 pw.println();
3080 }
3081 if (userData.seedAccountOptions != null) {
3082 pw.print(" account options exist");
3083 pw.println();
3084 }
3085 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003086 }
Amith Yamasani920ace02012-09-20 22:15:37 -07003087 }
Amith Yamasani12747872015-12-07 14:19:49 -08003088 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003089 pw.println(" Device policy global restrictions:");
3090 synchronized (mRestrictionsLock) {
3091 UserRestrictionsUtils
3092 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
3093 }
Makoto Onukia4f11972015-10-01 13:19:58 -07003094 pw.println();
Zoltan Szatmary-Bane7834602016-04-08 18:41:11 +01003095 pw.println(" Global restrictions owner id:" + mGlobalRestrictionOwnerUserId);
3096 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003097 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003098 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003099 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08003100 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003101 synchronized (mUsersLock) {
3102 pw.println();
3103 pw.println(" Device managed: " + mIsDeviceManaged);
3104 }
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003105 synchronized (mUserStates) {
3106 pw.println(" Started users state: " + mUserStates);
3107 }
Amith Yamasani12747872015-12-07 14:19:49 -08003108 // Dump some capabilities
3109 pw.println();
3110 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
3111 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01003112 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
3113 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07003114 }
3115 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003116
3117 final class MainHandler extends Handler {
3118
3119 @Override
3120 public void handleMessage(Message msg) {
3121 switch (msg.what) {
3122 case WRITE_USER_MSG:
3123 removeMessages(WRITE_USER_MSG, msg.obj);
3124 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003125 int userId = ((UserData) msg.obj).info.id;
3126 UserData userData = getUserDataNoChecks(userId);
3127 if (userData != null) {
3128 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08003129 }
3130 }
3131 }
3132 }
3133 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07003134
3135 /**
3136 * @param userId
3137 * @return whether the user has been initialized yet
3138 */
3139 boolean isInitialized(int userId) {
3140 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
3141 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003142
3143 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07003144 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003145 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
3146 @Nullable Bundle globalRestrictions) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003147 UserManagerService.this.setDevicePolicyUserRestrictionsInner(userId, localRestrictions,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003148 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003149 }
3150
3151 @Override
3152 public Bundle getBaseUserRestrictions(int userId) {
3153 synchronized (mRestrictionsLock) {
3154 return mBaseUserRestrictions.get(userId);
3155 }
3156 }
3157
3158 @Override
3159 public void setBaseUserRestrictionsByDpmsForMigration(
3160 int userId, Bundle baseRestrictions) {
3161 synchronized (mRestrictionsLock) {
3162 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07003163 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003164 }
3165
Amith Yamasani12747872015-12-07 14:19:49 -08003166 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003167 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08003168 if (userData != null) {
3169 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07003170 } else {
3171 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
3172 }
3173 }
3174 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08003175
3176 @Override
3177 public boolean getUserRestriction(int userId, String key) {
3178 return getUserRestrictions(userId).getBoolean(key);
3179 }
3180
3181 @Override
3182 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
3183 synchronized (mUserRestrictionsListeners) {
3184 mUserRestrictionsListeners.add(listener);
3185 }
3186 }
3187
3188 @Override
3189 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
3190 synchronized (mUserRestrictionsListeners) {
3191 mUserRestrictionsListeners.remove(listener);
3192 }
3193 }
Makoto Onukie7927da2015-11-25 10:05:17 -08003194
3195 @Override
3196 public void setDeviceManaged(boolean isManaged) {
3197 synchronized (mUsersLock) {
3198 mIsDeviceManaged = isManaged;
3199 }
3200 }
3201
3202 @Override
3203 public void setUserManaged(int userId, boolean isManaged) {
3204 synchronized (mUsersLock) {
3205 mIsUserManaged.put(userId, isManaged);
3206 }
3207 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01003208
3209 @Override
3210 public void setUserIcon(int userId, Bitmap bitmap) {
3211 long ident = Binder.clearCallingIdentity();
3212 try {
3213 synchronized (mPackagesLock) {
3214 UserData userData = getUserDataNoChecks(userId);
3215 if (userData == null || userData.info.partial) {
3216 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
3217 return;
3218 }
3219 writeBitmapLP(userData.info, bitmap);
3220 writeUserLP(userData);
3221 }
3222 sendUserInfoChangedBroadcast(userId);
3223 } finally {
3224 Binder.restoreCallingIdentity(ident);
3225 }
3226 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003227
3228 @Override
3229 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
3230 synchronized (mUsersLock) {
3231 mForceEphemeralUsers = forceEphemeralUsers;
3232 }
3233 }
3234
3235 @Override
3236 public void removeAllUsers() {
3237 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
3238 // Remove the non-system users straight away.
3239 removeNonSystemUsers();
3240 } else {
3241 // Switch to the system user first and then remove the other users.
3242 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
3243 @Override
3244 public void onReceive(Context context, Intent intent) {
3245 int userId =
3246 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3247 if (userId != UserHandle.USER_SYSTEM) {
3248 return;
3249 }
3250 mContext.unregisterReceiver(this);
3251 removeNonSystemUsers();
3252 }
3253 };
3254 IntentFilter userSwitchedFilter = new IntentFilter();
3255 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
3256 mContext.registerReceiver(
3257 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
3258
3259 // Switch to the system user.
3260 ActivityManager am =
3261 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
3262 am.switchUser(UserHandle.USER_SYSTEM);
3263 }
3264 }
phweisse9c44062016-02-10 12:57:38 +01003265
3266 @Override
Lenka Trochtova1ddda472016-02-12 10:42:12 +01003267 public void onEphemeralUserStop(int userId) {
3268 synchronized (mUsersLock) {
3269 UserInfo userInfo = getUserInfoLU(userId);
3270 if (userInfo != null && userInfo.isEphemeral()) {
3271 // Do not allow switching back to the ephemeral user again as the user is going
3272 // to be deleted.
3273 userInfo.flags |= UserInfo.FLAG_DISABLED;
3274 if (userInfo.isGuest()) {
3275 // Indicate that the guest will be deleted after it stops.
3276 userInfo.guestToRemove = true;
3277 }
3278 }
3279 }
3280 }
3281
3282 @Override
phweisse9c44062016-02-10 12:57:38 +01003283 public UserInfo createUserEvenWhenDisallowed(String name, int flags) {
3284 UserInfo user = createUserInternalUnchecked(name, flags, UserHandle.USER_NULL);
3285 // Keep this in sync with UserManager.createUser
3286 if (user != null && !user.isAdmin()) {
3287 setUserRestriction(UserManager.DISALLOW_SMS, true, user.id);
3288 setUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS, true, user.id);
3289 }
3290 return user;
3291 }
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003292
3293 @Override
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003294 public boolean isUserRunning(int userId) {
3295 synchronized (mUserStates) {
3296 return mUserStates.get(userId, -1) >= 0;
3297 }
3298 }
3299
3300 @Override
3301 public void setUserState(int userId, int userState) {
3302 synchronized (mUserStates) {
3303 mUserStates.put(userId, userState);
3304 }
3305 }
3306
3307 @Override
3308 public void removeUserState(int userId) {
3309 synchronized (mUserStates) {
3310 mUserStates.delete(userId);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003311 }
3312 }
3313
3314 @Override
3315 public boolean isUserUnlockingOrUnlocked(int userId) {
Fyodor Kupolovac06a492016-05-25 14:45:29 -07003316 synchronized (mUserStates) {
3317 int state = mUserStates.get(userId, -1);
3318 return (state == UserState.STATE_RUNNING_UNLOCKING)
3319 || (state == UserState.STATE_RUNNING_UNLOCKED);
Fyodor Kupolov6c915ea2016-05-09 19:10:53 -07003320 }
3321 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01003322 }
3323
3324 /* Remove all the users except of the system one. */
3325 private void removeNonSystemUsers() {
3326 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
3327 synchronized (mUsersLock) {
3328 final int userSize = mUsers.size();
3329 for (int i = 0; i < userSize; i++) {
3330 UserInfo ui = mUsers.valueAt(i).info;
3331 if (ui.id != UserHandle.USER_SYSTEM) {
3332 usersToRemove.add(ui);
3333 }
3334 }
3335 }
3336 for (UserInfo ui: usersToRemove) {
3337 removeUser(ui.id);
3338 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07003339 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07003340
3341 private class Shell extends ShellCommand {
3342 @Override
3343 public int onCommand(String cmd) {
3344 return onShellCommand(this, cmd);
3345 }
3346
3347 @Override
3348 public void onHelp() {
3349 final PrintWriter pw = getOutPrintWriter();
3350 pw.println("User manager (user) commands:");
3351 pw.println(" help");
3352 pw.println(" Print this help text.");
3353 pw.println("");
3354 pw.println(" list");
3355 pw.println(" Prints all users on the system.");
3356 }
3357 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003358
3359 private static void debug(String message) {
3360 Log.d(LOG_TAG, message +
3361 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3362 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003363}