blob: 5f4656742e058fa4f266f00db348aec6d1e78204 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chenb3b92582015-12-07 11:22:13 -080019import android.Manifest;
Xiaohui Chen594f2082015-08-18 11:04:20 -070020import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070021import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070022import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070023import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070024import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070026import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070027import android.app.IStopUserCallback;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010028import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070029import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070030import android.content.Context;
31import android.content.Intent;
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +010032import android.content.IntentFilter;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070033import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070034import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080035import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.content.pm.UserInfo;
Lenka Trochtova02fee152015-12-22 14:26:18 +010037import android.content.res.Resources;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070038import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080040import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080041import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070042import android.os.Environment;
43import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080044import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080046import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010047import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070048import android.os.Parcelable;
Amith Yamasani12747872015-12-07 14:19:49 -080049import android.os.PersistableBundle;
Amith Yamasani258848d2012-08-10 17:06:33 -070050import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070051import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070052import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040053import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070054import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070055import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070056import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070057import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080058import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010059import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070060import android.os.storage.VolumeInfo;
61import android.system.ErrnoException;
62import android.system.Os;
63import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070064import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070065import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import android.util.Slog;
67import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080068import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070069import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070070import android.util.Xml;
71
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070073import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040074import com.android.internal.app.IAppOpsService;
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -080075import com.android.internal.logging.MetricsLogger;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080076import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070077import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070078import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000079import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070080import com.android.server.LocalServices;
Jeff Sharkey0e62384c2016-01-13 18:52:55 -070081import com.android.server.pm.Installer.StorageFlags;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080082
83import org.xmlpull.v1.XmlPullParser;
84import org.xmlpull.v1.XmlPullParserException;
85import org.xmlpull.v1.XmlSerializer;
86
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087import java.io.BufferedOutputStream;
88import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070089import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070091import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070092import java.io.FileOutputStream;
93import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070094import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010095import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096import java.util.ArrayList;
97import java.util.List;
98
Fyodor Kupolov262f9952015-03-23 18:55:11 -070099import libcore.io.IoUtils;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800100import libcore.util.Objects;
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700101
Makoto Onuki068c54a2015-10-13 14:34:03 -0700102/**
103 * Service for {@link UserManager}.
104 *
105 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -0700106 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800107 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700108 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
109 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
110 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700111 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700112public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700113 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki81c61ea2016-01-22 11:22:26 -0800114 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800115 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700116
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700117 private static final String TAG_NAME = "name";
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800118 private static final String TAG_ACCOUNT = "account";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700119 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700120 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700122 private static final String ATTR_CREATION_TIME = "created";
123 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700124 private static final String ATTR_SERIAL_NO = "serialNumber";
125 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700126 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700127 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700128 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100129 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700130 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasani12747872015-12-07 14:19:49 -0800131 private static final String ATTR_SEED_ACCOUNT_NAME = "seedAccountName";
132 private static final String ATTR_SEED_ACCOUNT_TYPE = "seedAccountType";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530133 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800136 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800137 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800138 private static final String TAG_ENTRY = "entry";
139 private static final String TAG_VALUE = "value";
Amith Yamasani12747872015-12-07 14:19:49 -0800140 private static final String TAG_SEED_ACCOUNT_OPTIONS = "seedAccountOptions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700142 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800143 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700145 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
146 private static final String ATTR_TYPE_STRING = "s";
147 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700148 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700149 private static final String ATTR_TYPE_BUNDLE = "B";
150 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700151
Amith Yamasani0b285492011-04-14 17:35:23 -0700152 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700153 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700154 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100155 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700156
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800157 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700158 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800159
Amith Yamasani634cf312012-10-04 17:34:21 -0700160 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700161 // We need to keep process uid within Integer.MAX_VALUE.
162 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700163
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700164 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700165
Amith Yamasani920ace02012-09-20 22:15:37 -0700166 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
167
Nicolas Prevotb8186812015-08-06 15:00:03 +0100168 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700169 // without first making sure that the rest of the framework is prepared for it.
170 private static final int MAX_MANAGED_PROFILES = 1;
171
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800172 static final int WRITE_USER_MSG = 1;
173 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530174
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700175 private static final String XATTR_SERIAL = "user.serial";
176
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -0800177 // Tron counters
178 private static final String TRON_GUEST_CREATED = "users_guest_created";
179 private static final String TRON_USER_CREATED = "users_user_created";
180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 private final Context mContext;
182 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700183 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700184 // Short-term lock for internal state, when interaction/sync with PM is not required
185 private final Object mUsersLock = new Object();
186 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700187
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800188 private final Handler mHandler;
189
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190 private final File mUsersDir;
191 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192
Makoto Onuki068c54a2015-10-13 14:34:03 -0700193 /**
Amith Yamasani12747872015-12-07 14:19:49 -0800194 * User-related information that is used for persisting to flash. Only UserInfo is
195 * directly exposed to other system apps.
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800196 */
Amith Yamasani12747872015-12-07 14:19:49 -0800197 private static class UserData {
198 // Basic user information and properties
199 UserInfo info;
200 // Account name used when there is a strong association between a user and an account
201 String account;
202 // Account information for seeding into a newly created user. This could also be
203 // used for login validation for an existing user, for updating their credentials.
204 // In the latter case, data may not need to be persisted as it is only valid for the
205 // current login session.
206 String seedAccountName;
207 String seedAccountType;
208 PersistableBundle seedAccountOptions;
209 // Whether to perist the seed account information to be available after a boot
210 boolean persistSeedData;
211
212 void clearSeedAccountData() {
213 seedAccountName = null;
214 seedAccountType = null;
215 seedAccountOptions = null;
216 persistSeedData = false;
217 }
218 }
219
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800220 @GuardedBy("mUsersLock")
Amith Yamasani12747872015-12-07 14:19:49 -0800221 private final SparseArray<UserData> mUsers = new SparseArray<>();
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800222
223 /**
Makoto Onuki068c54a2015-10-13 14:34:03 -0700224 * User restrictions set via UserManager. This doesn't include restrictions set by
225 * device owner / profile owners.
226 *
227 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
228 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
229 * maybe shared between {@link #mBaseUserRestrictions} and
230 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
231 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700232 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700233 */
234 @GuardedBy("mRestrictionsLock")
235 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
236
237 /**
238 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
239 * with device / profile owner restrictions. We'll initialize it lazily; use
240 * {@link #getEffectiveUserRestrictions} to access it.
241 *
242 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
243 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
244 * maybe shared between {@link #mBaseUserRestrictions} and
245 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
246 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700247 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700248 */
249 @GuardedBy("mRestrictionsLock")
250 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
251
Makoto Onuki4f160732015-10-27 17:15:38 -0700252 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800253 * User restrictions that have already been applied in
254 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
255 * that have changed since the last
256 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700257 */
258 @GuardedBy("mRestrictionsLock")
259 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
260
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800261 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800262 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
263 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800264 */
265 @GuardedBy("mRestrictionsLock")
266 private Bundle mDevicePolicyGlobalUserRestrictions;
267
268 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800269 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
270 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800271 */
272 @GuardedBy("mRestrictionsLock")
273 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
274
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800275 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530276 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800277
278 /**
279 * Set of user IDs being actively removed. Removed IDs linger in this set
280 * for several seconds to work around a VFS caching issue.
281 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700282 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800283 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700284
Fyodor Kupolov82402752015-10-28 14:54:51 -0700285 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700286 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800287 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700288 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700289 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700290
Jason Monk62062992014-05-06 09:55:28 -0400291 private IAppOpsService mAppOpsService;
292
Makoto Onuki068c54a2015-10-13 14:34:03 -0700293 private final LocalService mLocalService;
294
Makoto Onukie7927da2015-11-25 10:05:17 -0800295 @GuardedBy("mUsersLock")
296 private boolean mIsDeviceManaged;
297
298 @GuardedBy("mUsersLock")
299 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
300
Makoto Onukid45a4a22015-11-02 17:17:38 -0800301 @GuardedBy("mUserRestrictionsListeners")
302 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
303 new ArrayList<>();
304
Clara Bayarria1771112015-12-18 16:29:18 +0000305 private final LockPatternUtils mLockPatternUtils;
306
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +0100307 /**
308 * Whether all users should be created ephemeral.
309 */
310 @GuardedBy("mUsersLock")
311 private boolean mForceEphemeralUsers;
312
Amith Yamasani258848d2012-08-10 17:06:33 -0700313 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700314
Dianne Hackborn4428e172012-08-24 17:43:05 -0700315 public static UserManagerService getInstance() {
316 synchronized (UserManagerService.class) {
317 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700318 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700319 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700320
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800321 @VisibleForTesting
322 UserManagerService(File dataDir) {
323 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700324 }
325
Dianne Hackborn4428e172012-08-24 17:43:05 -0700326 /**
327 * Called by package manager to create the service. This is closely
328 * associated with the package manager, and the given lock is the
329 * package manager's own lock.
330 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800331 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
332 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700333 }
334
Dianne Hackborn4428e172012-08-24 17:43:05 -0700335 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800336 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700337 mContext = context;
338 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700339 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800340 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800341 synchronized (mPackagesLock) {
342 mUsersDir = new File(dataDir, USER_INFO_DIR);
343 mUsersDir.mkdirs();
344 // Make zeroth user directory, for services to migrate their files to that location
345 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
346 userZeroDir.mkdirs();
347 FileUtils.setPermissions(mUsersDir.toString(),
348 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
349 -1, -1);
350 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
351 initDefaultGuestRestrictions();
352 readUserListLP();
353 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700354 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700355 mLocalService = new LocalService();
356 LocalServices.addService(UserManagerInternal.class, mLocalService);
Clara Bayarria1771112015-12-18 16:29:18 +0000357 mLockPatternUtils = new LockPatternUtils(mContext);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700358 }
359
360 void systemReady() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100361 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800362 ArrayList<UserInfo> partials = new ArrayList<>();
363 synchronized (mUsersLock) {
364 final int userSize = mUsers.size();
365 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800366 UserInfo ui = mUsers.valueAt(i).info;
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100367 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800368 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700369 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700370 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700371 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800372 final int partialsSize = partials.size();
373 for (int i = 0; i < partialsSize; i++) {
374 UserInfo ui = partials.get(i);
375 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
376 + " (name=" + ui.name + ")");
377 removeUserState(ui.id);
378 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800379
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700380 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800381
Jason Monk62062992014-05-06 09:55:28 -0400382 mAppOpsService = IAppOpsService.Stub.asInterface(
383 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800384
385 synchronized (mRestrictionsLock) {
386 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400387 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700388 }
389
390 @Override
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800391 public String getUserAccount(int userId) {
392 checkManageUserAndAcrossUsersFullPermission("get user account");
393 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800394 return mUsers.get(userId).account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800395 }
396 }
397
398 @Override
399 public void setUserAccount(int userId, String accountName) {
400 checkManageUserAndAcrossUsersFullPermission("set user account");
Amith Yamasani12747872015-12-07 14:19:49 -0800401 UserData userToUpdate = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800402 synchronized (mPackagesLock) {
403 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800404 final UserData userData = mUsers.get(userId);
405 if (userData == null) {
406 Slog.e(LOG_TAG, "User not found for setting user account: u" + userId);
407 return;
408 }
409 String currentAccount = userData.account;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800410 if (!Objects.equal(currentAccount, accountName)) {
Amith Yamasani12747872015-12-07 14:19:49 -0800411 userData.account = accountName;
412 userToUpdate = userData;
Xiaohui Chenb3b92582015-12-07 11:22:13 -0800413 }
414 }
415
416 if (userToUpdate != null) {
417 writeUserLP(userToUpdate);
418 }
419 }
420 }
421
422 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700423 public UserInfo getPrimaryUser() {
424 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700425 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700426 final int userSize = mUsers.size();
427 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800428 UserInfo ui = mUsers.valueAt(i).info;
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800429 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700430 return ui;
431 }
432 }
433 }
434 return null;
435 }
436
437 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700438 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700439 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700440 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700441 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700442 final int userSize = mUsers.size();
443 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800444 UserInfo ui = mUsers.valueAt(i).info;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700445 if (ui.partial) {
446 continue;
447 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800448 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700449 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700450 }
Amith Yamasani13593602012-03-22 16:16:17 -0700451 }
452 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700453 }
Amith Yamasani13593602012-03-22 16:16:17 -0700454 }
455
Amith Yamasani258848d2012-08-10 17:06:33 -0700456 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100457 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800458 if (userId != UserHandle.getCallingUserId()) {
459 checkManageUsersPermission("getting profiles related to user " + userId);
460 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700461 final long ident = Binder.clearCallingIdentity();
462 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700463 synchronized (mUsersLock) {
464 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100465 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700466 } finally {
467 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000468 }
469 }
470
Amith Yamasanibe465322014-04-24 13:45:17 -0700471 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700472 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
473 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700474 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700475 if (user == null) {
476 // Probably a dying user
477 return users;
478 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700479 final int userSize = mUsers.size();
480 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -0800481 UserInfo profile = mUsers.valueAt(i).info;
Amith Yamasanibe465322014-04-24 13:45:17 -0700482 if (!isProfileOf(user, profile)) {
483 continue;
484 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100485 if (enabledOnly && !profile.isEnabled()) {
486 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700487 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700488 if (mRemovingUserIds.get(profile.id)) {
489 continue;
490 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700491 users.add(profile);
492 }
493 return users;
494 }
495
Jessica Hummelbe81c802014-04-22 15:49:22 +0100496 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700497 public int getCredentialOwnerProfile(int userHandle) {
498 checkManageUsersPermission("get the credential owner");
Clara Bayarria1771112015-12-18 16:29:18 +0000499 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700500 synchronized (mUsersLock) {
501 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700502 if (profileParent != null) {
503 return profileParent.id;
504 }
505 }
506 }
507
508 return userHandle;
509 }
510
511 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700512 public boolean isSameProfileGroup(int userId, int otherUserId) {
513 if (userId == otherUserId) return true;
514 checkManageUsersPermission("check if in the same profile group");
515 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700516 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700517 }
518 }
519
Fyodor Kupolov82402752015-10-28 14:54:51 -0700520 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
521 synchronized (mUsersLock) {
522 UserInfo userInfo = getUserInfoLU(userId);
523 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
524 return false;
525 }
526 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
527 if (otherUserInfo == null
528 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
529 return false;
530 }
531 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700532 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700533 }
534
535 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100536 public UserInfo getProfileParent(int userHandle) {
537 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700538 synchronized (mUsersLock) {
539 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700540 }
541 }
542
Fyodor Kupolov82402752015-10-28 14:54:51 -0700543 private UserInfo getProfileParentLU(int userHandle) {
544 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700545 if (profile == null) {
546 return null;
547 }
548 int parentUserId = profile.profileGroupId;
549 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
550 return null;
551 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700552 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100553 }
554 }
555
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100557 return user.id == profile.id ||
558 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
559 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000560 }
561
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000562 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
Rubin Xuf13c9802016-01-21 18:06:00 +0000563 UserHandle parentHandle, boolean inQuietMode) {
564 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
565 intent.putExtra(Intent.EXTRA_QUIET_MODE, inQuietMode);
566 intent.putExtra(Intent.EXTRA_USER, profileHandle);
567 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileHandle.getIdentifier());
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000568 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Rubin Xuf13c9802016-01-21 18:06:00 +0000569 mContext.sendBroadcastAsUser(intent, parentHandle);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000570 }
571
572 @Override
573 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
574 checkManageUsersPermission("silence profile");
575 boolean changed = false;
576 UserInfo profile, parent;
577 synchronized (mPackagesLock) {
578 synchronized (mUsersLock) {
579 profile = getUserInfoLU(userHandle);
580 parent = getProfileParentLU(userHandle);
581
582 }
583 if (profile == null || !profile.isManagedProfile()) {
584 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
585 }
586 if (profile.isQuietModeEnabled() != enableQuietMode) {
587 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
Amith Yamasani12747872015-12-07 14:19:49 -0800588 writeUserLP(getUserDataLU(profile.id));
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000589 changed = true;
590 }
591 }
592 if (changed) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000593 long identity = Binder.clearCallingIdentity();
594 try {
595 if (enableQuietMode) {
596 ActivityManagerNative.getDefault().stopUser(userHandle, /* force */true, null);
597 } else {
598 ActivityManagerNative.getDefault().startUserInBackground(userHandle);
599 }
600 } catch (RemoteException e) {
601 Slog.e(LOG_TAG, "fail to start/stop user for quiet mode", e);
602 } finally {
603 Binder.restoreCallingIdentity(identity);
604 }
605
606 broadcastProfileAvailabilityChanges(profile.getUserHandle(), parent.getUserHandle(),
607 enableQuietMode);
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000608 }
609 }
610
611 @Override
612 public boolean isQuietModeEnabled(int userHandle) {
613 synchronized (mPackagesLock) {
614 UserInfo info;
615 synchronized (mUsersLock) {
616 info = getUserInfoLU(userHandle);
617 }
618 if (info == null || !info.isManagedProfile()) {
Rubin Xuf13c9802016-01-21 18:06:00 +0000619 return false;
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000620 }
621 return info.isQuietModeEnabled();
622 }
623 }
624
Kenny Guya52dc3e2014-02-11 15:33:14 +0000625 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100626 public void setUserEnabled(int userId) {
627 checkManageUsersPermission("enable user");
628 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700629 UserInfo info;
630 synchronized (mUsersLock) {
631 info = getUserInfoLU(userId);
632 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100633 if (info != null && !info.isEnabled()) {
634 info.flags ^= UserInfo.FLAG_DISABLED;
Amith Yamasani12747872015-12-07 14:19:49 -0800635 writeUserLP(getUserDataLU(info.id));
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100636 }
637 }
638 }
639
640 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700641 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700642 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700643 synchronized (mUsersLock) {
644 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700645 }
646 }
647
Amith Yamasani71e6c692013-03-24 17:39:28 -0700648 @Override
649 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700650 synchronized (mUsersLock) {
651 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700652 }
653 }
654
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700655 @Override
656 public boolean canHaveRestrictedProfile(int userId) {
657 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700658 synchronized (mUsersLock) {
659 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700660 if (userInfo == null || !userInfo.canHaveProfile()) {
661 return false;
662 }
663 if (!userInfo.isAdmin()) {
664 return false;
665 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800666 // restricted profile can be created if there is no DO set and the admin user has no PO;
667 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700668 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700669 }
670
Amith Yamasani195263742012-08-21 15:40:12 -0700671 /*
672 * Should be locked on mUsers before calling this.
673 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700674 private UserInfo getUserInfoLU(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -0800675 final UserData userData = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700676 // If it is partial and not in the process of being removed, return as unknown user.
Amith Yamasani12747872015-12-07 14:19:49 -0800677 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700678 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
679 return null;
680 }
Amith Yamasani12747872015-12-07 14:19:49 -0800681 return userData != null ? userData.info : null;
682 }
683
684 private UserData getUserDataLU(int userId) {
685 final UserData userData = mUsers.get(userId);
686 // If it is partial and not in the process of being removed, return as unknown user.
687 if (userData != null && userData.info.partial && !mRemovingUserIds.get(userId)) {
688 return null;
689 }
690 return userData;
Amith Yamasani195263742012-08-21 15:40:12 -0700691 }
692
Fyodor Kupolov82402752015-10-28 14:54:51 -0700693 /**
694 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
695 * <p>No permissions checking or any addition checks are made</p>
696 */
697 private UserInfo getUserInfoNoChecks(int userId) {
698 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800699 final UserData userData = mUsers.get(userId);
700 return userData != null ? userData.info : null;
701 }
702 }
703
704 /**
705 * Obtains {@link #mUsersLock} and return UserData from mUsers.
706 * <p>No permissions checking or any addition checks are made</p>
707 */
708 private UserData getUserDataNoChecks(int userId) {
709 synchronized (mUsersLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700710 return mUsers.get(userId);
711 }
712 }
713
Amith Yamasani236b2b52015-08-18 14:32:14 -0700714 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700715 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700716 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700717 }
718
Amith Yamasani258848d2012-08-10 17:06:33 -0700719 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700720 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700721 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700722 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700723 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800724 UserData userData = getUserDataNoChecks(userId);
725 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700726 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
727 return;
728 }
Amith Yamasani12747872015-12-07 14:19:49 -0800729 if (name != null && !name.equals(userData.info.name)) {
730 userData.info.name = name;
731 writeUserLP(userData);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700732 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700733 }
734 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700735 if (changed) {
736 sendUserInfoChangedBroadcast(userId);
737 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700738 }
739
Amith Yamasani258848d2012-08-10 17:06:33 -0700740 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700741 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700742 checkManageUsersPermission("update users");
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100743 if (hasUserRestriction(UserManager.DISALLOW_SET_USER_ICON, userId)) {
744 Log.w(LOG_TAG, "Cannot set user icon. DISALLOW_SET_USER_ICON is enabled.");
745 return;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700746 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100747 mLocalService.setUserIcon(userId, bitmap);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700748 }
749
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +0100750
751
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700752 private void sendUserInfoChangedBroadcast(int userId) {
753 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
754 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
755 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700756 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700757 }
758
Amith Yamasani258848d2012-08-10 17:06:33 -0700759 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100760 public ParcelFileDescriptor getUserIcon(int userId) {
761 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700762 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700763 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700764 if (info == null || info.partial) {
765 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
766 return null;
767 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700768 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100769 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
770 || callingGroupId != info.profileGroupId) {
771 checkManageUsersPermission("get the icon of a user who is not related");
772 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700773 if (info.iconPath == null) {
774 return null;
775 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100776 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700777 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100778
779 try {
780 return ParcelFileDescriptor.open(
781 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
782 } catch (FileNotFoundException e) {
783 Log.e(LOG_TAG, "Couldn't find icon file", e);
784 }
785 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700786 }
787
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700788 public void makeInitialized(int userId) {
789 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800790 boolean scheduleWriteUser = false;
Amith Yamasani12747872015-12-07 14:19:49 -0800791 UserData userData;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800792 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -0800793 userData = mUsers.get(userId);
794 if (userData == null || userData.info.partial) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700795 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800796 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700797 }
Amith Yamasani12747872015-12-07 14:19:49 -0800798 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
799 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800800 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700801 }
802 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800803 if (scheduleWriteUser) {
Amith Yamasani12747872015-12-07 14:19:49 -0800804 scheduleWriteUser(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800805 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700806 }
807
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700808 /**
809 * If default guest restrictions haven't been initialized yet, add the basic
810 * restrictions.
811 */
812 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800813 synchronized (mGuestRestrictions) {
814 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800815 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800816 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
817 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
818 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700819 }
820 }
821
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800822 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530823 public Bundle getDefaultGuestRestrictions() {
824 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800825 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530826 return new Bundle(mGuestRestrictions);
827 }
828 }
829
830 @Override
831 public void setDefaultGuestRestrictions(Bundle restrictions) {
832 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800833 synchronized (mGuestRestrictions) {
834 mGuestRestrictions.clear();
835 mGuestRestrictions.putAll(restrictions);
836 }
837 synchronized (mPackagesLock) {
838 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530839 }
840 }
841
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800842 /**
843 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
844 */
845 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
846 @Nullable Bundle global) {
847 Preconditions.checkNotNull(local);
848 boolean globalChanged = false;
849 boolean localChanged;
850 synchronized (mRestrictionsLock) {
851 if (global != null) {
852 // Update global.
853 globalChanged = !UserRestrictionsUtils.areEqual(
854 mDevicePolicyGlobalUserRestrictions, global);
855 if (globalChanged) {
856 mDevicePolicyGlobalUserRestrictions = global;
857 }
858 }
859 {
860 // Update local.
861 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
862 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
863 if (localChanged) {
864 mDevicePolicyLocalUserRestrictions.put(userId, local);
865 }
866 }
867 }
868 if (DBG) {
869 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
870 + " global=" + global + (globalChanged ? " (changed)" : "")
871 + " local=" + local + (localChanged ? " (changed)" : "")
872 );
873 }
874 // Don't call them within the mRestrictionsLock.
875 synchronized (mPackagesLock) {
876 if (globalChanged) {
877 writeUserListLP();
878 }
879 if (localChanged) {
Amith Yamasani12747872015-12-07 14:19:49 -0800880 writeUserLP(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800881 }
882 }
883
884 synchronized (mRestrictionsLock) {
885 if (globalChanged) {
886 applyUserRestrictionsForAllUsersLR();
887 } else if (localChanged) {
888 applyUserRestrictionsLR(userId);
889 }
890 }
891 }
892
Makoto Onuki068c54a2015-10-13 14:34:03 -0700893 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700894 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800895 final Bundle baseRestrictions =
896 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
897 final Bundle global = mDevicePolicyGlobalUserRestrictions;
898 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700899
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800900 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
901 // Common case first.
902 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700903 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800904 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
905 UserRestrictionsUtils.merge(effective, global);
906 UserRestrictionsUtils.merge(effective, local);
907
Makoto Onuki068c54a2015-10-13 14:34:03 -0700908 return effective;
909 }
910
911 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700912 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700913 if (DBG) {
914 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
915 }
916 mCachedEffectiveUserRestrictions.remove(userId);
917 }
918
919 private Bundle getEffectiveUserRestrictions(int userId) {
920 synchronized (mRestrictionsLock) {
921 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
922 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700923 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700924 mCachedEffectiveUserRestrictions.put(userId, restrictions);
925 }
926 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700927 }
928 }
929
Makoto Onuki068c54a2015-10-13 14:34:03 -0700930 /** @return a specific user restriction that's in effect currently. */
931 @Override
932 public boolean hasUserRestriction(String restrictionKey, int userId) {
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800933 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
934 return false;
935 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700936 Bundle restrictions = getEffectiveUserRestrictions(userId);
937 return restrictions != null && restrictions.getBoolean(restrictionKey);
938 }
939
940 /**
941 * @return UserRestrictions that are in effect currently. This always returns a new
942 * {@link Bundle}.
943 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700944 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800945 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800946 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800947 }
948
949 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000950 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
951 checkManageUsersPermission("hasBaseUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800952 if (!UserRestrictionsUtils.isValidRestriction(restrictionKey)) {
953 return false;
954 }
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000955 synchronized (mRestrictionsLock) {
956 Bundle bundle = mBaseUserRestrictions.get(userId);
957 return (bundle != null && bundle.getBoolean(restrictionKey, false));
958 }
959 }
960
961 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700962 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700963 checkManageUsersPermission("setUserRestriction");
Makoto Onuki1f1ceef2016-01-28 11:32:32 -0800964 if (!UserRestrictionsUtils.isValidRestriction(key)) {
965 return;
966 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700967 synchronized (mRestrictionsLock) {
968 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
969 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800970 final Bundle newRestrictions = UserRestrictionsUtils.clone(
971 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700972 newRestrictions.putBoolean(key, value);
973
Fyodor Kupolov82402752015-10-28 14:54:51 -0700974 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700975 }
976 }
977
Makoto Onuki068c54a2015-10-13 14:34:03 -0700978 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800979 * Optionally updating user restrictions, calculate the effective user restrictions and also
980 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700981 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800982 * @param newRestrictions User restrictions to set.
983 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700984 * @param userId target user ID.
985 */
986 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700987 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700988 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800989
990 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
991 mAppliedUserRestrictions.get(userId));
992
993 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700994 if (newRestrictions != null) {
995 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800996 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
997
998 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700999 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
1000 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001001
1002 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
1003 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -08001004 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001005 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001006 }
1007
Fyodor Kupolov82402752015-10-28 14:54:51 -07001008 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001009
Makoto Onuki759a7632015-10-28 16:43:10 -07001010 mCachedEffectiveUserRestrictions.put(userId, effective);
1011
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001012 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001013 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001014 debug("Applying user restrictions: userId=" + userId
1015 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001016 }
1017
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001018 if (mAppOpsService != null) { // We skip it until system-ready.
1019 final long token = Binder.clearCallingIdentity();
1020 try {
1021 mAppOpsService.setUserRestrictions(effective, userId);
1022 } catch (RemoteException e) {
1023 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1024 } finally {
1025 Binder.restoreCallingIdentity(token);
1026 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001027 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001028
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001029 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001030
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001031 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001032 }
1033
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001034 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001035 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001036 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1037 // actually, but we still need some kind of synchronization otherwise we might end up
1038 // calling listeners out-of-order, thus "LR".
1039
1040 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1041 return;
1042 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001043
1044 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1045 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1046
1047 mHandler.post(new Runnable() {
1048 @Override
1049 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001050 UserRestrictionsUtils.applyUserRestrictions(
1051 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001052
Makoto Onukid45a4a22015-11-02 17:17:38 -08001053 final UserRestrictionsListener[] listeners;
1054 synchronized (mUserRestrictionsListeners) {
1055 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1056 mUserRestrictionsListeners.toArray(listeners);
1057 }
1058 for (int i = 0; i < listeners.length; i++) {
1059 listeners[i].onUserRestrictionsChanged(userId,
1060 newRestrictionsFinal, prevRestrictionsFinal);
1061 }
1062 }
1063 });
1064 }
1065
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001066 // Package private for the inner class.
1067 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001068 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001069 }
1070
1071 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001072 // Package private for the inner class.
1073 void applyUserRestrictionsForAllUsersLR() {
1074 if (DBG) {
1075 debug("applyUserRestrictionsForAllUsersLR");
1076 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001077 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001078 mCachedEffectiveUserRestrictions.clear();
1079
Makoto Onuki068c54a2015-10-13 14:34:03 -07001080 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1081 // it on a handler.
1082 final Runnable r = new Runnable() {
1083 @Override
1084 public void run() {
1085 // Then get the list of running users.
1086 final int[] runningUsers;
1087 try {
1088 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1089 } catch (RemoteException e) {
1090 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1091 return;
1092 }
1093 // Then re-calculate the effective restrictions and apply, only for running users.
1094 // It's okay if a new user has started after the getRunningUserIds() call,
1095 // because we'll do the same thing (re-calculate the restrictions and apply)
1096 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001097 synchronized (mRestrictionsLock) {
1098 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001099 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001100 }
1101 }
1102 }
1103 };
1104 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001105 }
1106
Amith Yamasani258848d2012-08-10 17:06:33 -07001107 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001108 * Check if we've hit the limit of how many users can be created.
1109 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001110 private boolean isUserLimitReached() {
1111 int count;
1112 synchronized (mUsersLock) {
1113 count = getAliveUsersExcludingGuestsCountLU();
1114 }
1115 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001116 }
1117
1118 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001119 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001120 checkManageUsersPermission("check if more managed profiles can be added.");
1121 if (ActivityManager.isLowRamDeviceStatic()) {
1122 return false;
1123 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001124 if (!mContext.getPackageManager().hasSystemFeature(
1125 PackageManager.FEATURE_MANAGED_USERS)) {
1126 return false;
1127 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001128 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001129 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1130 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1131 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001132 return false;
1133 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001134 synchronized(mUsersLock) {
1135 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001136 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001137 return false;
1138 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001139 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1140 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001141 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001142 return usersCountAfterRemoving == 1
1143 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001144 }
1145 }
1146
Fyodor Kupolov82402752015-10-28 14:54:51 -07001147 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001148 int aliveUserCount = 0;
1149 final int totalUserCount = mUsers.size();
1150 // Skip over users being removed
1151 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001152 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001153 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001154 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001155 aliveUserCount++;
1156 }
1157 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001158 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001159 }
1160
1161 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001162 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001163 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1164 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1165 * permissions can make certain calls to the UserManager.
1166 *
1167 * @param message used as message if SecurityException is thrown
1168 * @throws SecurityException if the caller does not have enough privilege.
1169 */
1170 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1171 final int uid = Binder.getCallingUid();
1172 if (uid != Process.SYSTEM_UID && uid != 0
1173 && ActivityManager.checkComponentPermission(
1174 Manifest.permission.MANAGE_USERS,
1175 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1176 && ActivityManager.checkComponentPermission(
1177 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1178 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1179 throw new SecurityException(
1180 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1181 + message);
1182 }
1183 }
1184
1185 /**
1186 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001187 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001188 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001189 *
1190 * @param message used as message if SecurityException is thrown
1191 * @throws SecurityException if the caller is not system or root
1192 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001193 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001194 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001195 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001196 && ActivityManager.checkComponentPermission(
1197 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001198 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1199 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1200 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001201 }
1202
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001203 /**
1204 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1205 * UserManager.
1206 *
1207 * @param message used as message if SecurityException is thrown
1208 * @throws SecurityException if the caller is not system or root
1209 */
1210 private static void checkSystemOrRoot(String message) {
1211 final int uid = Binder.getCallingUid();
1212 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1213 throw new SecurityException("Only system may: " + message);
1214 }
1215 }
1216
Fyodor Kupolov82402752015-10-28 14:54:51 -07001217 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001218 try {
1219 File dir = new File(mUsersDir, Integer.toString(info.id));
1220 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001221 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001222 if (!dir.exists()) {
1223 dir.mkdir();
1224 FileUtils.setPermissions(
1225 dir.getPath(),
1226 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1227 -1, -1);
1228 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001229 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001230 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1231 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001232 info.iconPath = file.getAbsolutePath();
1233 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001234 try {
1235 os.close();
1236 } catch (IOException ioe) {
1237 // What the ... !
1238 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001239 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001240 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001241 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001242 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001243 }
1244
Amith Yamasani0b285492011-04-14 17:35:23 -07001245 /**
1246 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1247 * cache it elsewhere.
1248 * @return the array of user ids.
1249 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001250 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001251 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001252 return mUserIds;
1253 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001254 }
1255
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001256 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001257 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001258 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001259 return;
1260 }
1261 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001262 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001263 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001264 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001265 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001266 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001267 int type;
1268 while ((type = parser.next()) != XmlPullParser.START_TAG
1269 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001270 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001271 }
1272
1273 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001274 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001275 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001276 return;
1277 }
1278
Amith Yamasani2a003292012-08-14 18:25:45 -07001279 mNextSerialNumber = -1;
1280 if (parser.getName().equals(TAG_USERS)) {
1281 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1282 if (lastSerialNumber != null) {
1283 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1284 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001285 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1286 if (versionNumber != null) {
1287 mUserVersion = Integer.parseInt(versionNumber);
1288 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001289 }
1290
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001291 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1292
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001293 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301294 if (type == XmlPullParser.START_TAG) {
1295 final String name = parser.getName();
1296 if (name.equals(TAG_USER)) {
1297 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001298
Amith Yamasani12747872015-12-07 14:19:49 -08001299 UserData userData = readUserLP(Integer.parseInt(id));
1300
1301 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001302 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001303 mUsers.put(userData.info.id, userData);
1304 if (mNextSerialNumber < 0
1305 || mNextSerialNumber <= userData.info.id) {
1306 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001307 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301308 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001309 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301310 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001311 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1312 && type != XmlPullParser.END_TAG) {
1313 if (type == XmlPullParser.START_TAG) {
1314 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001315 synchronized (mGuestRestrictions) {
1316 UserRestrictionsUtils
1317 .readRestrictions(parser, mGuestRestrictions);
1318 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001319 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1320 ) {
1321 UserRestrictionsUtils.readRestrictions(parser,
1322 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001323 }
1324 break;
1325 }
1326 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001327 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001328 }
1329 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001330 synchronized (mRestrictionsLock) {
1331 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1332 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001333 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001334 upgradeIfNecessaryLP();
1335 } catch (IOException | XmlPullParserException e) {
1336 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001337 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001338 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001339 }
1340 }
1341
Amith Yamasani6f34b412012-10-22 18:19:27 -07001342 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001343 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001344 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001345 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001346 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001347 int userVersion = mUserVersion;
1348 if (userVersion < 1) {
1349 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001350 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1351 if ("Primary".equals(userData.info.name)) {
1352 userData.info.name =
1353 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1354 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001355 }
1356 userVersion = 1;
1357 }
1358
Amith Yamasanibc9625052012-11-15 14:39:18 -08001359 if (userVersion < 2) {
1360 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001361 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1362 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1363 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1364 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001365 }
1366 userVersion = 2;
1367 }
1368
Amith Yamasani350962c2013-08-06 11:18:53 -07001369
Amith Yamasani5e486f52013-08-07 11:06:44 -07001370 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001371 userVersion = 4;
1372 }
1373
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001374 if (userVersion < 5) {
1375 initDefaultGuestRestrictions();
1376 userVersion = 5;
1377 }
1378
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001379 if (userVersion < 6) {
1380 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001381 synchronized (mUsersLock) {
1382 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001383 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001384 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001385 if (!splitSystemUser && userData.info.isRestricted()
1386 && (userData.info.restrictedProfileParentId
1387 == UserInfo.NO_PROFILE_GROUP_ID)) {
1388 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1389 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001390 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001391 }
1392 }
1393 userVersion = 6;
1394 }
1395
Amith Yamasani6f34b412012-10-22 18:19:27 -07001396 if (userVersion < USER_VERSION) {
1397 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1398 + USER_VERSION);
1399 } else {
1400 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001401
1402 if (originalVersion < mUserVersion) {
1403 writeUserListLP();
1404 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001405 }
1406 }
1407
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001408 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001409 int flags = UserInfo.FLAG_INITIALIZED;
1410 // In split system user mode, the admin and primary flags are assigned to the first human
1411 // user.
1412 if (!UserManager.isSplitSystemUser()) {
1413 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1414 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001415 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001416 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001417 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001418 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001419 UserData userData = new UserData();
1420 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001421 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001422 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001423 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001424 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001425 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001426
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001427 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001428 synchronized (mRestrictionsLock) {
1429 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1430 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001431
Fyodor Kupolov82402752015-10-28 14:54:51 -07001432 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001433 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001434
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001435 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001436 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001437 }
1438
Amith Yamasani12747872015-12-07 14:19:49 -08001439 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001440 if (DBG) {
1441 debug("scheduleWriteUser");
1442 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001443 // No need to wrap it within a lock -- worst case, we'll just post the same message
1444 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001445 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1446 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001447 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1448 }
1449 }
1450
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001451 /*
1452 * Writes the user file in this format:
1453 *
1454 * <user flags="20039023" id="0">
1455 * <name>Primary</name>
1456 * </user>
1457 */
Amith Yamasani12747872015-12-07 14:19:49 -08001458 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001459 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001460 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001461 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001462 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001463 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001464 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001465 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001466 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1467
1468 // XmlSerializer serializer = XmlUtils.serializerInstance();
1469 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001470 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001471 serializer.startDocument(null, true);
1472 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1473
Amith Yamasani12747872015-12-07 14:19:49 -08001474 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001475 serializer.startTag(null, TAG_USER);
1476 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001477 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001478 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001479 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1480 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1481 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001482 if (userInfo.iconPath != null) {
1483 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1484 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001485 if (userInfo.partial) {
1486 serializer.attribute(null, ATTR_PARTIAL, "true");
1487 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001488 if (userInfo.guestToRemove) {
1489 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1490 }
Kenny Guy2a764942014-04-02 13:29:20 +01001491 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1492 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1493 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001494 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001495 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1496 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1497 Integer.toString(userInfo.restrictedProfileParentId));
1498 }
Amith Yamasani12747872015-12-07 14:19:49 -08001499 // Write seed data
1500 if (userData.persistSeedData) {
1501 if (userData.seedAccountName != null) {
1502 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1503 }
1504 if (userData.seedAccountType != null) {
1505 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1506 }
1507 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001508 serializer.startTag(null, TAG_NAME);
1509 serializer.text(userInfo.name);
1510 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001511 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001512 UserRestrictionsUtils.writeRestrictions(serializer,
1513 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1514 UserRestrictionsUtils.writeRestrictions(serializer,
1515 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1516 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001517 }
Amith Yamasani12747872015-12-07 14:19:49 -08001518
1519 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001520 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001521 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001522 serializer.endTag(null, TAG_ACCOUNT);
1523 }
1524
Amith Yamasani12747872015-12-07 14:19:49 -08001525 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1526 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1527 userData.seedAccountOptions.saveToXml(serializer);
1528 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1529 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001530 serializer.endTag(null, TAG_USER);
1531
1532 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001533 userFile.finishWrite(fos);
1534 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001535 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001536 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001537 }
1538 }
1539
1540 /*
1541 * Writes the user list file in this format:
1542 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001543 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001544 * <user id="0"></user>
1545 * <user id="2"></user>
1546 * </users>
1547 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001548 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001549 if (DBG) {
1550 debug("writeUserList");
1551 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001552 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001553 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001554 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001555 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001556 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1557
1558 // XmlSerializer serializer = XmlUtils.serializerInstance();
1559 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001560 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001561 serializer.startDocument(null, true);
1562 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1563
1564 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001565 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001566 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001567
Adam Lesinskieddeb492014-09-08 17:50:03 -07001568 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001569 synchronized (mGuestRestrictions) {
1570 UserRestrictionsUtils
1571 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1572 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301573 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001574 synchronized (mRestrictionsLock) {
1575 UserRestrictionsUtils.writeRestrictions(serializer,
1576 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1577 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001578 int[] userIdsToWrite;
1579 synchronized (mUsersLock) {
1580 userIdsToWrite = new int[mUsers.size()];
1581 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001582 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001583 userIdsToWrite[i] = user.id;
1584 }
1585 }
1586 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001587 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001588 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001589 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001590 }
1591
1592 serializer.endTag(null, TAG_USERS);
1593
1594 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001595 userListFile.finishWrite(fos);
1596 } catch (Exception e) {
1597 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001598 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001599 }
1600 }
1601
Amith Yamasani12747872015-12-07 14:19:49 -08001602 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001603 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001604 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001605 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001606 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001607 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001608 long creationTime = 0L;
1609 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001610 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001611 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001612 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001613 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001614 boolean persistSeedData = false;
1615 String seedAccountName = null;
1616 String seedAccountType = null;
1617 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001618 Bundle baseRestrictions = new Bundle();
1619 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001620
1621 FileInputStream fis = null;
1622 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001623 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001624 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001625 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001626 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001627 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001628 int type;
1629 while ((type = parser.next()) != XmlPullParser.START_TAG
1630 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001631 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001632 }
1633
1634 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001635 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001636 return null;
1637 }
1638
1639 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001640 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1641 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001642 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001643 return null;
1644 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001645 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1646 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001647 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001648 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1649 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001650 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1651 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001652 restrictedProfileParentId = readIntAttribute(parser,
1653 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001654 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1655 if ("true".equals(valueString)) {
1656 partial = true;
1657 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001658 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1659 if ("true".equals(valueString)) {
1660 guestToRemove = true;
1661 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001662
Amith Yamasani12747872015-12-07 14:19:49 -08001663 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1664 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1665 if (seedAccountName != null || seedAccountType != null) {
1666 persistSeedData = true;
1667 }
1668
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001669 int outerDepth = parser.getDepth();
1670 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1671 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1672 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1673 continue;
1674 }
1675 String tag = parser.getName();
1676 if (TAG_NAME.equals(tag)) {
1677 type = parser.next();
1678 if (type == XmlPullParser.TEXT) {
1679 name = parser.getText();
1680 }
1681 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1683 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1684 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001685 } else if (TAG_ACCOUNT.equals(tag)) {
1686 type = parser.next();
1687 if (type == XmlPullParser.TEXT) {
1688 account = parser.getText();
1689 }
Amith Yamasani12747872015-12-07 14:19:49 -08001690 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1691 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1692 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001693 }
1694 }
1695 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001696
Amith Yamasani12747872015-12-07 14:19:49 -08001697 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001698 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001699 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001700 userInfo.creationTime = creationTime;
1701 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001702 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001703 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001704 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001705 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001706
1707 // Create the UserData object that's internal to this class
1708 UserData userData = new UserData();
1709 userData.info = userInfo;
1710 userData.account = account;
1711 userData.seedAccountName = seedAccountName;
1712 userData.seedAccountType = seedAccountType;
1713 userData.persistSeedData = persistSeedData;
1714 userData.seedAccountOptions = seedAccountOptions;
1715
Makoto Onuki068c54a2015-10-13 14:34:03 -07001716 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717 mBaseUserRestrictions.put(id, baseRestrictions);
1718 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001719 }
Amith Yamasani12747872015-12-07 14:19:49 -08001720 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001721 } catch (IOException ioe) {
1722 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001723 } finally {
1724 if (fis != null) {
1725 try {
1726 fis.close();
1727 } catch (IOException e) {
1728 }
1729 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001730 }
1731 return null;
1732 }
1733
Amith Yamasani920ace02012-09-20 22:15:37 -07001734 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1735 String valueString = parser.getAttributeValue(null, attr);
1736 if (valueString == null) return defaultValue;
1737 try {
1738 return Integer.parseInt(valueString);
1739 } catch (NumberFormatException nfe) {
1740 return defaultValue;
1741 }
1742 }
1743
1744 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1745 String valueString = parser.getAttributeValue(null, attr);
1746 if (valueString == null) return defaultValue;
1747 try {
1748 return Long.parseLong(valueString);
1749 } catch (NumberFormatException nfe) {
1750 return defaultValue;
1751 }
1752 }
1753
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001754 private boolean isPackageInstalled(String pkg, int userId) {
1755 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1756 PackageManager.GET_UNINSTALLED_PACKAGES,
1757 userId);
1758 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1759 return false;
1760 }
1761 return true;
1762 }
1763
Amith Yamasanib82add22013-07-09 11:24:44 -07001764 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001765 * Removes the app restrictions file for a specific package and user id, if it exists.
1766 */
1767 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1768 synchronized (mPackagesLock) {
1769 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001770 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001771 if (resFile.exists()) {
1772 resFile.delete();
1773 }
1774 }
1775 }
1776
Kenny Guya52dc3e2014-02-11 15:33:14 +00001777 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001778 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001779 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001780 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001781 }
1782
Amith Yamasani258848d2012-08-10 17:06:33 -07001783 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001784 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001785 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001786 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001787 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001788
Jessica Hummelbe81c802014-04-22 15:49:22 +01001789 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001790 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001791 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1792 return null;
1793 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001794 if (ActivityManager.isLowRamDeviceStatic()) {
1795 return null;
1796 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001797 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001798 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001799 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001800 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001801 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001802 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001803 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001804 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001805 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001806 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001807 if (parentId != UserHandle.USER_NULL) {
1808 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001809 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001810 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001811 if (parent == null) return null;
1812 }
1813 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1814 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1815 return null;
1816 }
1817 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1818 // If we're not adding a guest user or a managed profile and the limit has
1819 // been reached, cannot add a user.
1820 return null;
1821 }
1822 // If we're adding a guest and there already exists one, bail.
1823 if (isGuest && findCurrentGuestUser() != null) {
1824 return null;
1825 }
1826 // In legacy mode, restricted profile's parent can only be the owner user
1827 if (isRestricted && !UserManager.isSplitSystemUser()
1828 && (parentId != UserHandle.USER_SYSTEM)) {
1829 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1830 return null;
1831 }
1832 if (isRestricted && UserManager.isSplitSystemUser()) {
1833 if (parent == null) {
1834 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1835 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001836 return null;
1837 }
Amith Yamasani12747872015-12-07 14:19:49 -08001838 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001839 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1840 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001841 return null;
1842 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001843 }
1844 // In split system user mode, we assign the first human user the primary flag.
1845 // And if there is no device owner, we also assign the admin flag to primary user.
1846 if (UserManager.isSplitSystemUser()
1847 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1848 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001849 synchronized (mUsersLock) {
1850 if (!mIsDeviceManaged) {
1851 flags |= UserInfo.FLAG_ADMIN;
1852 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001853 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001854 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001855
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001856 userId = getNextAvailableId();
1857 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001858 boolean ephemeralGuests = Resources.getSystem()
1859 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001860
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001861 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001862 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1863 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1864 || (parent != null && parent.info.isEphemeral())) {
1865 flags |= UserInfo.FLAG_EPHEMERAL;
1866 }
1867
1868 userInfo = new UserInfo(userId, name, null, flags);
1869 userInfo.serialNumber = mNextSerialNumber++;
1870 long now = System.currentTimeMillis();
1871 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1872 userInfo.partial = true;
1873 userData = new UserData();
1874 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001875 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001876 }
1877 writeUserListLP();
1878 if (parent != null) {
1879 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001880 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1881 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001882 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001883 }
Amith Yamasani12747872015-12-07 14:19:49 -08001884 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001885 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001886 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1887 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001888 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001889 }
Amith Yamasani12747872015-12-07 14:19:49 -08001890 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001891 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001892 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001893 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001894 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001895 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001896 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1897 final String volumeUuid = vol.getFsUuid();
1898 try {
1899 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001900 storage.prepareUserStorage(
1901 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001902 enforceSerialNumber(userDir, userInfo.serialNumber);
1903 } catch (IOException e) {
1904 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1905 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001906 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001907 mPm.createNewUser(userId);
1908 userInfo.partial = false;
1909 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001910 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001911 }
1912 updateUserIds();
1913 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001914 if (isGuest) {
1915 synchronized (mGuestRestrictions) {
1916 restrictions.putAll(mGuestRestrictions);
1917 }
1918 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001919 synchronized (mRestrictionsLock) {
1920 mBaseUserRestrictions.append(userId, restrictions);
1921 }
1922 mPm.newUserCreated(userId);
1923 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1924 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1925 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1926 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001927 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001928 } finally {
1929 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001930 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001931 return userInfo;
1932 }
1933
Amith Yamasani0b285492011-04-14 17:35:23 -07001934 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001935 * @hide
1936 */
Amith Yamasani12747872015-12-07 14:19:49 -08001937 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001938 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1939 checkManageUsersPermission("setupRestrictedProfile");
1940 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1941 if (user == null) {
1942 return null;
1943 }
1944 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1945 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1946 // the putIntForUser() will fail.
1947 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1948 android.provider.Settings.Secure.LOCATION_MODE,
1949 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1950 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1951 return user;
1952 }
1953
1954 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001955 * Find the current guest user. If the Guest user is partial,
1956 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001957 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001958 private UserInfo findCurrentGuestUser() {
1959 synchronized (mUsersLock) {
1960 final int size = mUsers.size();
1961 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001962 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001963 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1964 return user;
1965 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001966 }
1967 }
1968 return null;
1969 }
1970
1971 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001972 * Mark this guest user for deletion to allow us to create another guest
1973 * and switch to that user before actually removing this guest.
1974 * @param userHandle the userid of the current guest
1975 * @return whether the user could be marked for deletion
1976 */
Amith Yamasani12747872015-12-07 14:19:49 -08001977 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001978 public boolean markGuestForDeletion(int userHandle) {
1979 checkManageUsersPermission("Only the system can remove users");
1980 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1981 UserManager.DISALLOW_REMOVE_USER, false)) {
1982 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1983 return false;
1984 }
1985
1986 long ident = Binder.clearCallingIdentity();
1987 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001988 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001989 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001990 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001991 userData = mUsers.get(userHandle);
1992 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001993 return false;
1994 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001995 }
Amith Yamasani12747872015-12-07 14:19:49 -08001996 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001997 return false;
1998 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001999 // We set this to a guest user that is to be removed. This is a temporary state
2000 // where we are allowed to add new Guest users, even if this one is still not
2001 // removed. This user will still show up in getUserInfo() calls.
2002 // If we don't get around to removing this Guest user, it will be purged on next
2003 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08002004 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07002005 // Mark it as disabled, so that it isn't returned any more when
2006 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002007 userData.info.flags |= UserInfo.FLAG_DISABLED;
2008 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002009 }
2010 } finally {
2011 Binder.restoreCallingIdentity(ident);
2012 }
2013 return true;
2014 }
2015
2016 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002017 * Removes a user and all data directories created for that user. This method should be called
2018 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002019 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002020 */
Amith Yamasani12747872015-12-07 14:19:49 -08002021 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002022 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002023 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002024 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2025 UserManager.DISALLOW_REMOVE_USER, false)) {
2026 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2027 return false;
2028 }
2029
Kenny Guyee58b4f2014-05-23 15:19:53 +01002030 long ident = Binder.clearCallingIdentity();
2031 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002032 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002033 int currentUser = ActivityManager.getCurrentUser();
2034 if (currentUser == userHandle) {
2035 Log.w(LOG_TAG, "Current user cannot be removed");
2036 return false;
2037 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002038 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002039 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002040 userData = mUsers.get(userHandle);
2041 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002042 return false;
2043 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002044
Fyodor Kupolov82402752015-10-28 14:54:51 -07002045 // We remember deleted user IDs to prevent them from being
2046 // reused during the current boot; they can still be reused
2047 // after a reboot.
2048 mRemovingUserIds.put(userHandle, true);
2049 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002050
Kenny Guyee58b4f2014-05-23 15:19:53 +01002051 try {
2052 mAppOpsService.removeUser(userHandle);
2053 } catch (RemoteException e) {
2054 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2055 }
2056 // Set this to a partially created user, so that the user will be purged
2057 // on next startup, in case the runtime stops now before stopping and
2058 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002059 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002060 // Mark it as disabled, so that it isn't returned any more when
2061 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002062 userData.info.flags |= UserInfo.FLAG_DISABLED;
2063 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002064 }
2065
Amith Yamasani12747872015-12-07 14:19:49 -08002066 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2067 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002068 // Send broadcast to notify system that the user removed was a
2069 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002070 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002071 }
2072
2073 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2074 int res;
2075 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002076 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2077 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002078 @Override
2079 public void userStopped(int userId) {
2080 finishRemoveUser(userId);
2081 }
2082 @Override
2083 public void userStopAborted(int userId) {
2084 }
2085 });
2086 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002087 return false;
2088 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002089 return res == ActivityManager.USER_OP_SUCCESS;
2090 } finally {
2091 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002092 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002093 }
2094
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002095 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002096 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002097 // Let other services shutdown any activity and clean up their state before completely
2098 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002099 long ident = Binder.clearCallingIdentity();
2100 try {
2101 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2102 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002103 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2104 android.Manifest.permission.MANAGE_USERS,
2105
2106 new BroadcastReceiver() {
2107 @Override
2108 public void onReceive(Context context, Intent intent) {
2109 if (DBG) {
2110 Slog.i(LOG_TAG,
2111 "USER_REMOVED broadcast sent, cleaning up user data "
2112 + userHandle);
2113 }
2114 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002115 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002116 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002117 // Clean up any ActivityManager state
2118 LocalServices.getService(ActivityManagerInternal.class)
2119 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002120 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002121 }
2122 }.start();
2123 }
2124 },
2125
2126 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002127 } finally {
2128 Binder.restoreCallingIdentity(ident);
2129 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002130 }
2131
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002132 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002133 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002134 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002135 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002136
2137 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002138 synchronized (mUsersLock) {
2139 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002140 mIsUserManaged.delete(userHandle);
2141 }
2142 synchronized (mRestrictionsLock) {
2143 mBaseUserRestrictions.remove(userHandle);
2144 mAppliedUserRestrictions.remove(userHandle);
2145 mCachedEffectiveUserRestrictions.remove(userHandle);
2146 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002147 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002148 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002149 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002150 userFile.delete();
2151 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002152 synchronized (mPackagesLock) {
2153 writeUserListLP();
2154 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002155 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002156 File userDir = Environment.getUserSystemDirectory(userHandle);
2157 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2158 if (userDir.renameTo(renamedUserDir)) {
2159 removeDirectoryRecursive(renamedUserDir);
2160 } else {
2161 removeDirectoryRecursive(userDir);
2162 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002163 }
2164
Amith Yamasani61f57372012-08-31 12:12:28 -07002165 private void removeDirectoryRecursive(File parent) {
2166 if (parent.isDirectory()) {
2167 String[] files = parent.list();
2168 for (String filename : files) {
2169 File child = new File(parent, filename);
2170 removeDirectoryRecursive(child);
2171 }
2172 }
2173 parent.delete();
2174 }
2175
Kenny Guyf8d3a232014-05-15 16:09:52 +01002176 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002177 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002178 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2179 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002180 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002181 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002182 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002183 }
2184
Amith Yamasani2a003292012-08-14 18:25:45 -07002185 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002186 public Bundle getApplicationRestrictions(String packageName) {
2187 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2188 }
2189
2190 @Override
2191 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002192 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002193 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002194 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002195 }
2196 synchronized (mPackagesLock) {
2197 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002198 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002199 }
2200 }
2201
2202 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002203 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002204 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002205 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002206 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002207 if (restrictions == null || restrictions.isEmpty()) {
2208 cleanAppRestrictionsForPackage(packageName, userId);
2209 } else {
2210 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002211 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002212 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002213 }
Robin Lee66e5d962014-04-09 16:44:21 +01002214
Kenny Guyd21b2182014-07-17 16:38:55 +01002215 if (isPackageInstalled(packageName, userId)) {
2216 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2217 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2218 changeIntent.setPackage(packageName);
2219 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2220 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2221 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002222 }
2223
2224 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002225 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002226 try {
2227 return mContext.getPackageManager().getApplicationInfo(packageName,
2228 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2229 } catch (NameNotFoundException nnfe) {
2230 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002231 } finally {
2232 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002233 }
2234 }
2235
Fyodor Kupolov82402752015-10-28 14:54:51 -07002236 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002237 AtomicFile restrictionsFile =
2238 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2239 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002240 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002241 }
2242
2243 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002244 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002245 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002246 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002247 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002248 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002249 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002250
2251 FileInputStream fis = null;
2252 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002253 fis = restrictionsFile.openRead();
2254 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002255 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002256 XmlUtils.nextElement(parser);
2257 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002258 Slog.e(LOG_TAG, "Unable to read restrictions file "
2259 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002260 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002261 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002262 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2263 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002264 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002265 } catch (IOException|XmlPullParserException e) {
2266 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002267 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002268 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002269 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002270 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002271 }
2272
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002273 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2274 XmlPullParser parser) throws XmlPullParserException, IOException {
2275 int type = parser.getEventType();
2276 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2277 String key = parser.getAttributeValue(null, ATTR_KEY);
2278 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2279 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2280 if (multiple != null) {
2281 values.clear();
2282 int count = Integer.parseInt(multiple);
2283 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2284 if (type == XmlPullParser.START_TAG
2285 && parser.getName().equals(TAG_VALUE)) {
2286 values.add(parser.nextText().trim());
2287 count--;
2288 }
2289 }
2290 String [] valueStrings = new String[values.size()];
2291 values.toArray(valueStrings);
2292 restrictions.putStringArray(key, valueStrings);
2293 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2294 restrictions.putBundle(key, readBundleEntry(parser, values));
2295 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2296 final int outerDepth = parser.getDepth();
2297 ArrayList<Bundle> bundleList = new ArrayList<>();
2298 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2299 Bundle childBundle = readBundleEntry(parser, values);
2300 bundleList.add(childBundle);
2301 }
2302 restrictions.putParcelableArray(key,
2303 bundleList.toArray(new Bundle[bundleList.size()]));
2304 } else {
2305 String value = parser.nextText().trim();
2306 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2307 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2308 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2309 restrictions.putInt(key, Integer.parseInt(value));
2310 } else {
2311 restrictions.putString(key, value);
2312 }
2313 }
2314 }
2315 }
2316
2317 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2318 throws IOException, XmlPullParserException {
2319 Bundle childBundle = new Bundle();
2320 final int outerDepth = parser.getDepth();
2321 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2322 readEntry(childBundle, values, parser);
2323 }
2324 return childBundle;
2325 }
2326
Fyodor Kupolov82402752015-10-28 14:54:51 -07002327 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002328 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002329 AtomicFile restrictionsFile = new AtomicFile(
2330 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002331 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002332 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002333 }
2334
2335 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002336 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002337 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002338 try {
2339 fos = restrictionsFile.startWrite();
2340 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2341
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002342 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002343 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002344 serializer.startDocument(null, true);
2345 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2346
2347 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002348 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002349 serializer.endTag(null, TAG_RESTRICTIONS);
2350
2351 serializer.endDocument();
2352 restrictionsFile.finishWrite(fos);
2353 } catch (Exception e) {
2354 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002355 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2356 }
2357 }
2358
2359 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2360 throws IOException {
2361 for (String key : restrictions.keySet()) {
2362 Object value = restrictions.get(key);
2363 serializer.startTag(null, TAG_ENTRY);
2364 serializer.attribute(null, ATTR_KEY, key);
2365
2366 if (value instanceof Boolean) {
2367 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2368 serializer.text(value.toString());
2369 } else if (value instanceof Integer) {
2370 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2371 serializer.text(value.toString());
2372 } else if (value == null || value instanceof String) {
2373 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2374 serializer.text(value != null ? (String) value : "");
2375 } else if (value instanceof Bundle) {
2376 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2377 writeBundle((Bundle) value, serializer);
2378 } else if (value instanceof Parcelable[]) {
2379 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2380 Parcelable[] array = (Parcelable[]) value;
2381 for (Parcelable parcelable : array) {
2382 if (!(parcelable instanceof Bundle)) {
2383 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2384 }
2385 serializer.startTag(null, TAG_ENTRY);
2386 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2387 writeBundle((Bundle) parcelable, serializer);
2388 serializer.endTag(null, TAG_ENTRY);
2389 }
2390 } else {
2391 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2392 String[] values = (String[]) value;
2393 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2394 for (String choice : values) {
2395 serializer.startTag(null, TAG_VALUE);
2396 serializer.text(choice != null ? choice : "");
2397 serializer.endTag(null, TAG_VALUE);
2398 }
2399 }
2400 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002401 }
2402 }
2403
2404 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002405 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002406 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002407 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002408 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002409 }
2410 }
2411
2412 @Override
2413 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002414 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002415 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002416 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002417 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002418 }
2419 // Not found
2420 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002421 }
2422 }
2423
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002424 @Override
2425 public long getUserCreationTime(int userHandle) {
2426 int callingUserId = UserHandle.getCallingUserId();
2427 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002428 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002429 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002430 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002431 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002432 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002433 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002434 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002435 }
2436 }
2437 }
2438 if (userInfo == null) {
2439 throw new SecurityException("userHandle can only be the calling user or a managed "
2440 + "profile associated with this user");
2441 }
2442 return userInfo.creationTime;
2443 }
2444
Amith Yamasani0b285492011-04-14 17:35:23 -07002445 /**
2446 * Caches the list of user ids in an array, adjusting the array size when necessary.
2447 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002449 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002450 synchronized (mUsersLock) {
2451 final int userSize = mUsers.size();
2452 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002453 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002454 num++;
2455 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002456 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002457 final int[] newUsers = new int[num];
2458 int n = 0;
2459 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002460 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002461 newUsers[n++] = mUsers.keyAt(i);
2462 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002463 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002464 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002465 }
2466 }
2467
2468 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002469 * Called right before a user is started. This gives us a chance to prepare
2470 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002471 */
2472 public void onBeforeStartUser(int userId) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002473 mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
2474
2475 if (userId != UserHandle.USER_SYSTEM) {
2476 synchronized (mRestrictionsLock) {
2477 applyUserRestrictionsLR(userId);
2478 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002479 }
2480 }
2481
2482 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002483 * Called right before a user is unlocked. This gives us a chance to prepare
2484 * app storage.
2485 */
2486 public void onBeforeUnlockUser(int userId) {
2487 mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
2488 }
2489
2490 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002491 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002492 * @param userId the user that was just foregrounded
2493 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002494 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002495 UserData userData = getUserDataNoChecks(userId);
2496 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002497 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2498 return;
2499 }
2500 long now = System.currentTimeMillis();
2501 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002502 userData.info.lastLoggedInTime = now;
2503 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002504 }
2505 }
2506
2507 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002508 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002509 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2510 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002511 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002512 private int getNextAvailableId() {
2513 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002514 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002515 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002516 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002517 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002518 }
2519 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002520 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002521 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002522 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002523 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002524
Amith Yamasanifc95e702013-09-26 13:20:17 -07002525 private String packageToRestrictionsFileName(String packageName) {
2526 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2527 }
2528
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002529 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002530 * Enforce that serial number stored in user directory inode matches the
2531 * given expected value. Gracefully sets the serial number if currently
2532 * undefined.
2533 *
2534 * @throws IOException when problem extracting serial number, or serial
2535 * number is mismatched.
2536 */
2537 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2538 final int foundSerial = getSerialNumber(file);
2539 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2540
2541 if (foundSerial == -1) {
2542 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2543 try {
2544 setSerialNumber(file, serialNumber);
2545 } catch (IOException e) {
2546 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2547 }
2548
2549 } else if (foundSerial != serialNumber) {
2550 throw new IOException("Found serial number " + foundSerial
2551 + " doesn't match expected " + serialNumber);
2552 }
2553 }
2554
2555 /**
2556 * Set serial number stored in user directory inode.
2557 *
2558 * @throws IOException if serial number was already set
2559 */
2560 private static void setSerialNumber(File file, int serialNumber)
2561 throws IOException {
2562 try {
2563 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2564 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2565 } catch (ErrnoException e) {
2566 throw e.rethrowAsIOException();
2567 }
2568 }
2569
2570 /**
2571 * Return serial number stored in user directory inode.
2572 *
2573 * @return parsed serial number, or -1 if not set
2574 */
2575 private static int getSerialNumber(File file) throws IOException {
2576 try {
2577 final byte[] buf = new byte[256];
2578 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2579 final String serial = new String(buf, 0, len);
2580 try {
2581 return Integer.parseInt(serial);
2582 } catch (NumberFormatException e) {
2583 throw new IOException("Bad serial number: " + serial);
2584 }
2585 } catch (ErrnoException e) {
2586 if (e.errno == OsConstants.ENODATA) {
2587 return -1;
2588 } else {
2589 throw e.rethrowAsIOException();
2590 }
2591 }
2592 }
2593
Amith Yamasani920ace02012-09-20 22:15:37 -07002594 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002595 public void setSeedAccountData(int userId, String accountName, String accountType,
2596 PersistableBundle accountOptions, boolean persist) {
2597 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2598 synchronized (mPackagesLock) {
2599 final UserData userData;
2600 synchronized (mUsersLock) {
2601 userData = getUserDataLU(userId);
2602 if (userData == null) {
2603 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2604 return;
2605 }
2606 userData.seedAccountName = accountName;
2607 userData.seedAccountType = accountType;
2608 userData.seedAccountOptions = accountOptions;
2609 userData.persistSeedData = persist;
2610 }
2611 if (persist) {
2612 writeUserLP(userData);
2613 }
2614 }
2615 }
2616
2617 @Override
2618 public String getSeedAccountName() throws RemoteException {
2619 checkManageUsersPermission("Cannot get seed account information");
2620 synchronized (mUsersLock) {
2621 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2622 return userData.seedAccountName;
2623 }
2624 }
2625
2626 @Override
2627 public String getSeedAccountType() throws RemoteException {
2628 checkManageUsersPermission("Cannot get seed account information");
2629 synchronized (mUsersLock) {
2630 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2631 return userData.seedAccountType;
2632 }
2633 }
2634
2635 @Override
2636 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2637 checkManageUsersPermission("Cannot get seed account information");
2638 synchronized (mUsersLock) {
2639 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2640 return userData.seedAccountOptions;
2641 }
2642 }
2643
2644 @Override
2645 public void clearSeedAccountData() throws RemoteException {
2646 checkManageUsersPermission("Cannot clear seed account information");
2647 synchronized (mPackagesLock) {
2648 UserData userData;
2649 synchronized (mUsersLock) {
2650 userData = getUserDataLU(UserHandle.getCallingUserId());
2651 if (userData == null) return;
2652 userData.clearSeedAccountData();
2653 }
2654 writeUserLP(userData);
2655 }
2656 }
2657
2658 @Override
2659 public boolean someUserHasSeedAccount(String accountName, String accountType)
2660 throws RemoteException {
2661 checkManageUsersPermission("Cannot check seed account information");
2662 synchronized (mUsersLock) {
2663 final int userSize = mUsers.size();
2664 for (int i = 0; i < userSize; i++) {
2665 final UserData data = mUsers.valueAt(i);
2666 if (data.info.isInitialized()) continue;
2667 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2668 continue;
2669 }
2670 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2671 continue;
2672 }
2673 return true;
2674 }
2675 }
2676 return false;
2677 }
2678
2679 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002680 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2681 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2682 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2683 }
2684
2685 int onShellCommand(Shell shell, String cmd) {
2686 if (cmd == null) {
2687 return shell.handleDefaultCommands(cmd);
2688 }
2689
2690 final PrintWriter pw = shell.getOutPrintWriter();
2691 try {
2692 switch(cmd) {
2693 case "list":
2694 return runList(pw);
2695 }
2696 } catch (RemoteException e) {
2697 pw.println("Remote exception: " + e);
2698 }
2699 return -1;
2700 }
2701
2702 private int runList(PrintWriter pw) throws RemoteException {
2703 final IActivityManager am = ActivityManagerNative.getDefault();
2704 final List<UserInfo> users = getUsers(false);
2705 if (users == null) {
2706 pw.println("Error: couldn't get users");
2707 return 1;
2708 } else {
2709 pw.println("Users:");
2710 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002711 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002712 pw.println("\t" + users.get(i).toString() + running);
2713 }
2714 return 0;
2715 }
2716 }
2717
2718 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002719 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2720 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2721 != PackageManager.PERMISSION_GRANTED) {
2722 pw.println("Permission Denial: can't dump UserManager from from pid="
2723 + Binder.getCallingPid()
2724 + ", uid=" + Binder.getCallingUid()
2725 + " without permission "
2726 + android.Manifest.permission.DUMP);
2727 return;
2728 }
2729
2730 long now = System.currentTimeMillis();
2731 StringBuilder sb = new StringBuilder();
2732 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002733 synchronized (mUsersLock) {
2734 pw.println("Users:");
2735 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002736 UserData userData = mUsers.valueAt(i);
2737 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002738 continue;
2739 }
Amith Yamasani12747872015-12-07 14:19:49 -08002740 UserInfo userInfo = userData.info;
2741 final int userId = userInfo.id;
2742 pw.print(" "); pw.print(userInfo);
2743 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002744 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002745 pw.print(" <removing> ");
2746 }
Amith Yamasani12747872015-12-07 14:19:49 -08002747 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002748 pw.print(" <partial>");
2749 }
2750 pw.println();
2751 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002752 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002753 pw.println("<unknown>");
2754 } else {
2755 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002756 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002757 sb.append(" ago");
2758 pw.println(sb);
2759 }
2760 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002761 if (userInfo.lastLoggedInTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002762 pw.println("<unknown>");
2763 } else {
2764 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002765 TimeUtils.formatDuration(now - userInfo.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002766 sb.append(" ago");
2767 pw.println(sb);
2768 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002769 pw.print(" Has profile owner: ");
2770 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002771 pw.println(" Restrictions:");
2772 synchronized (mRestrictionsLock) {
2773 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002774 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002775 pw.println(" Device policy local restrictions:");
2776 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002777 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002778 pw.println(" Effective restrictions:");
2779 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002780 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002781 }
Amith Yamasani12747872015-12-07 14:19:49 -08002782
2783 if (userData.account != null) {
2784 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002785 pw.println();
2786 }
Amith Yamasani12747872015-12-07 14:19:49 -08002787
2788 if (userData.seedAccountName != null) {
2789 pw.print(" Seed account name: " + userData.seedAccountName);
2790 pw.println();
2791 if (userData.seedAccountType != null) {
2792 pw.print(" account type: " + userData.seedAccountType);
2793 pw.println();
2794 }
2795 if (userData.seedAccountOptions != null) {
2796 pw.print(" account options exist");
2797 pw.println();
2798 }
2799 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002800 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002801 }
Amith Yamasani12747872015-12-07 14:19:49 -08002802 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002803 pw.println(" Device policy global restrictions:");
2804 synchronized (mRestrictionsLock) {
2805 UserRestrictionsUtils
2806 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2807 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002808 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002809 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002810 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002811 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002812 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002813 synchronized (mUsersLock) {
2814 pw.println();
2815 pw.println(" Device managed: " + mIsDeviceManaged);
2816 }
Amith Yamasani12747872015-12-07 14:19:49 -08002817 // Dump some capabilities
2818 pw.println();
2819 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2820 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002821 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2822 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002823 }
2824 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002825
2826 final class MainHandler extends Handler {
2827
2828 @Override
2829 public void handleMessage(Message msg) {
2830 switch (msg.what) {
2831 case WRITE_USER_MSG:
2832 removeMessages(WRITE_USER_MSG, msg.obj);
2833 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002834 int userId = ((UserData) msg.obj).info.id;
2835 UserData userData = getUserDataNoChecks(userId);
2836 if (userData != null) {
2837 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002838 }
2839 }
2840 }
2841 }
2842 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002843
2844 /**
2845 * @param userId
2846 * @return whether the user has been initialized yet
2847 */
2848 boolean isInitialized(int userId) {
2849 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2850 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002851
2852 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002853 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002854 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2855 @Nullable Bundle globalRestrictions) {
2856 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2857 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002858 }
2859
2860 @Override
2861 public Bundle getBaseUserRestrictions(int userId) {
2862 synchronized (mRestrictionsLock) {
2863 return mBaseUserRestrictions.get(userId);
2864 }
2865 }
2866
2867 @Override
2868 public void setBaseUserRestrictionsByDpmsForMigration(
2869 int userId, Bundle baseRestrictions) {
2870 synchronized (mRestrictionsLock) {
2871 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002872 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002873 }
2874
Amith Yamasani12747872015-12-07 14:19:49 -08002875 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002876 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002877 if (userData != null) {
2878 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002879 } else {
2880 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2881 }
2882 }
2883 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002884
2885 @Override
2886 public boolean getUserRestriction(int userId, String key) {
2887 return getUserRestrictions(userId).getBoolean(key);
2888 }
2889
2890 @Override
2891 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2892 synchronized (mUserRestrictionsListeners) {
2893 mUserRestrictionsListeners.add(listener);
2894 }
2895 }
2896
2897 @Override
2898 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2899 synchronized (mUserRestrictionsListeners) {
2900 mUserRestrictionsListeners.remove(listener);
2901 }
2902 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002903
2904 @Override
2905 public void setDeviceManaged(boolean isManaged) {
2906 synchronized (mUsersLock) {
2907 mIsDeviceManaged = isManaged;
2908 }
2909 }
2910
2911 @Override
2912 public void setUserManaged(int userId, boolean isManaged) {
2913 synchronized (mUsersLock) {
2914 mIsUserManaged.put(userId, isManaged);
2915 }
2916 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002917
2918 @Override
2919 public void setUserIcon(int userId, Bitmap bitmap) {
2920 long ident = Binder.clearCallingIdentity();
2921 try {
2922 synchronized (mPackagesLock) {
2923 UserData userData = getUserDataNoChecks(userId);
2924 if (userData == null || userData.info.partial) {
2925 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2926 return;
2927 }
2928 writeBitmapLP(userData.info, bitmap);
2929 writeUserLP(userData);
2930 }
2931 sendUserInfoChangedBroadcast(userId);
2932 } finally {
2933 Binder.restoreCallingIdentity(ident);
2934 }
2935 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002936
2937 @Override
2938 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
2939 synchronized (mUsersLock) {
2940 mForceEphemeralUsers = forceEphemeralUsers;
2941 }
2942 }
2943
2944 @Override
2945 public void removeAllUsers() {
2946 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
2947 // Remove the non-system users straight away.
2948 removeNonSystemUsers();
2949 } else {
2950 // Switch to the system user first and then remove the other users.
2951 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
2952 @Override
2953 public void onReceive(Context context, Intent intent) {
2954 int userId =
2955 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2956 if (userId != UserHandle.USER_SYSTEM) {
2957 return;
2958 }
2959 mContext.unregisterReceiver(this);
2960 removeNonSystemUsers();
2961 }
2962 };
2963 IntentFilter userSwitchedFilter = new IntentFilter();
2964 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
2965 mContext.registerReceiver(
2966 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
2967
2968 // Switch to the system user.
2969 ActivityManager am =
2970 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
2971 am.switchUser(UserHandle.USER_SYSTEM);
2972 }
2973 }
2974 }
2975
2976 /* Remove all the users except of the system one. */
2977 private void removeNonSystemUsers() {
2978 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
2979 synchronized (mUsersLock) {
2980 final int userSize = mUsers.size();
2981 for (int i = 0; i < userSize; i++) {
2982 UserInfo ui = mUsers.valueAt(i).info;
2983 if (ui.id != UserHandle.USER_SYSTEM) {
2984 usersToRemove.add(ui);
2985 }
2986 }
2987 }
2988 for (UserInfo ui: usersToRemove) {
2989 removeUser(ui.id);
2990 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002991 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002992
2993 private class Shell extends ShellCommand {
2994 @Override
2995 public int onCommand(String cmd) {
2996 return onShellCommand(this, cmd);
2997 }
2998
2999 @Override
3000 public void onHelp() {
3001 final PrintWriter pw = getOutPrintWriter();
3002 pw.println("User manager (user) commands:");
3003 pw.println(" help");
3004 pw.println(" Print this help text.");
3005 pw.println("");
3006 pw.println(" list");
3007 pw.println(" Prints all users on the system.");
3008 }
3009 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003010
3011 private static void debug(String message) {
3012 Log.d(LOG_TAG, message +
3013 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3014 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003015}