blob: 0f614cad112741f051ea4d589608860b55a3f636 [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) {
933 Bundle restrictions = getEffectiveUserRestrictions(userId);
934 return restrictions != null && restrictions.getBoolean(restrictionKey);
935 }
936
937 /**
938 * @return UserRestrictions that are in effect currently. This always returns a new
939 * {@link Bundle}.
940 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700941 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800942 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800943 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800944 }
945
946 @Override
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000947 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
948 checkManageUsersPermission("hasBaseUserRestriction");
949 synchronized (mRestrictionsLock) {
950 Bundle bundle = mBaseUserRestrictions.get(userId);
951 return (bundle != null && bundle.getBoolean(restrictionKey, false));
952 }
953 }
954
955 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700956 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700957 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700958 synchronized (mRestrictionsLock) {
959 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
960 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800961 final Bundle newRestrictions = UserRestrictionsUtils.clone(
962 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700963 newRestrictions.putBoolean(key, value);
964
Fyodor Kupolov82402752015-10-28 14:54:51 -0700965 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700966 }
967 }
968
Makoto Onuki068c54a2015-10-13 14:34:03 -0700969 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800970 * Optionally updating user restrictions, calculate the effective user restrictions and also
971 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700972 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800973 * @param newRestrictions User restrictions to set.
974 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700975 * @param userId target user ID.
976 */
977 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700978 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700979 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800980
981 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
982 mAppliedUserRestrictions.get(userId));
983
984 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700985 if (newRestrictions != null) {
986 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800987 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
988
989 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700990 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
991 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800992
993 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
994 mBaseUserRestrictions.put(userId, newRestrictions);
Amith Yamasani12747872015-12-07 14:19:49 -0800995 scheduleWriteUser(getUserDataNoChecks(userId));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800996 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700997 }
998
Fyodor Kupolov82402752015-10-28 14:54:51 -0700999 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001000
Makoto Onuki759a7632015-10-28 16:43:10 -07001001 mCachedEffectiveUserRestrictions.put(userId, effective);
1002
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001003 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -07001004 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001005 debug("Applying user restrictions: userId=" + userId
1006 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001007 }
1008
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001009 if (mAppOpsService != null) { // We skip it until system-ready.
1010 final long token = Binder.clearCallingIdentity();
1011 try {
1012 mAppOpsService.setUserRestrictions(effective, userId);
1013 } catch (RemoteException e) {
1014 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
1015 } finally {
1016 Binder.restoreCallingIdentity(token);
1017 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001018 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001019
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001020 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -07001021
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001022 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001023 }
1024
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001025 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -08001026 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001027 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
1028 // actually, but we still need some kind of synchronization otherwise we might end up
1029 // calling listeners out-of-order, thus "LR".
1030
1031 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
1032 return;
1033 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08001034
1035 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
1036 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
1037
1038 mHandler.post(new Runnable() {
1039 @Override
1040 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001041 UserRestrictionsUtils.applyUserRestrictions(
1042 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001043
Makoto Onukid45a4a22015-11-02 17:17:38 -08001044 final UserRestrictionsListener[] listeners;
1045 synchronized (mUserRestrictionsListeners) {
1046 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
1047 mUserRestrictionsListeners.toArray(listeners);
1048 }
1049 for (int i = 0; i < listeners.length; i++) {
1050 listeners[i].onUserRestrictionsChanged(userId,
1051 newRestrictionsFinal, prevRestrictionsFinal);
1052 }
1053 }
1054 });
1055 }
1056
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001057 // Package private for the inner class.
1058 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001059 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001060 }
1061
1062 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001063 // Package private for the inner class.
1064 void applyUserRestrictionsForAllUsersLR() {
1065 if (DBG) {
1066 debug("applyUserRestrictionsForAllUsersLR");
1067 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07001068 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -07001069 mCachedEffectiveUserRestrictions.clear();
1070
Makoto Onuki068c54a2015-10-13 14:34:03 -07001071 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
1072 // it on a handler.
1073 final Runnable r = new Runnable() {
1074 @Override
1075 public void run() {
1076 // Then get the list of running users.
1077 final int[] runningUsers;
1078 try {
1079 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
1080 } catch (RemoteException e) {
1081 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
1082 return;
1083 }
1084 // Then re-calculate the effective restrictions and apply, only for running users.
1085 // It's okay if a new user has started after the getRunningUserIds() call,
1086 // because we'll do the same thing (re-calculate the restrictions and apply)
1087 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001088 synchronized (mRestrictionsLock) {
1089 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001090 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001091 }
1092 }
1093 }
1094 };
1095 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001096 }
1097
Amith Yamasani258848d2012-08-10 17:06:33 -07001098 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001099 * Check if we've hit the limit of how many users can be created.
1100 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001101 private boolean isUserLimitReached() {
1102 int count;
1103 synchronized (mUsersLock) {
1104 count = getAliveUsersExcludingGuestsCountLU();
1105 }
1106 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001107 }
1108
1109 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001110 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001111 checkManageUsersPermission("check if more managed profiles can be added.");
1112 if (ActivityManager.isLowRamDeviceStatic()) {
1113 return false;
1114 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001115 if (!mContext.getPackageManager().hasSystemFeature(
1116 PackageManager.FEATURE_MANAGED_USERS)) {
1117 return false;
1118 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001119 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001120 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1121 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1122 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001123 return false;
1124 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001125 synchronized(mUsersLock) {
1126 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001127 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001128 return false;
1129 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001130 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1131 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001132 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001133 return usersCountAfterRemoving == 1
1134 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001135 }
1136 }
1137
Fyodor Kupolov82402752015-10-28 14:54:51 -07001138 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001139 int aliveUserCount = 0;
1140 final int totalUserCount = mUsers.size();
1141 // Skip over users being removed
1142 for (int i = 0; i < totalUserCount; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001143 UserInfo user = mUsers.valueAt(i).info;
Amith Yamasani95ab7842014-08-11 17:09:26 -07001144 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001145 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001146 aliveUserCount++;
1147 }
1148 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001149 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001150 }
1151
1152 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001153 * Enforces that only the system UID or root's UID or apps that have the
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001154 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} and
1155 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL INTERACT_ACROSS_USERS_FULL}
1156 * permissions can make certain calls to the UserManager.
1157 *
1158 * @param message used as message if SecurityException is thrown
1159 * @throws SecurityException if the caller does not have enough privilege.
1160 */
1161 private static final void checkManageUserAndAcrossUsersFullPermission(String message) {
1162 final int uid = Binder.getCallingUid();
1163 if (uid != Process.SYSTEM_UID && uid != 0
1164 && ActivityManager.checkComponentPermission(
1165 Manifest.permission.MANAGE_USERS,
1166 uid, -1, true) != PackageManager.PERMISSION_GRANTED
1167 && ActivityManager.checkComponentPermission(
1168 Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1169 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1170 throw new SecurityException(
1171 "You need MANAGE_USERS and INTERACT_ACROSS_USERS_FULL permission to: "
1172 + message);
1173 }
1174 }
1175
1176 /**
1177 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001178 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001179 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001180 *
1181 * @param message used as message if SecurityException is thrown
1182 * @throws SecurityException if the caller is not system or root
1183 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001184 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001185 final int uid = Binder.getCallingUid();
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001186 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001187 && ActivityManager.checkComponentPermission(
1188 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001189 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1190 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1191 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001192 }
1193
Esteban Talavera5b9f1672015-12-11 15:22:34 +00001194 /**
1195 * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
1196 * UserManager.
1197 *
1198 * @param message used as message if SecurityException is thrown
1199 * @throws SecurityException if the caller is not system or root
1200 */
1201 private static void checkSystemOrRoot(String message) {
1202 final int uid = Binder.getCallingUid();
1203 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
1204 throw new SecurityException("Only system may: " + message);
1205 }
1206 }
1207
Fyodor Kupolov82402752015-10-28 14:54:51 -07001208 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001209 try {
1210 File dir = new File(mUsersDir, Integer.toString(info.id));
1211 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001212 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001213 if (!dir.exists()) {
1214 dir.mkdir();
1215 FileUtils.setPermissions(
1216 dir.getPath(),
1217 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1218 -1, -1);
1219 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001220 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001221 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1222 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001223 info.iconPath = file.getAbsolutePath();
1224 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001225 try {
1226 os.close();
1227 } catch (IOException ioe) {
1228 // What the ... !
1229 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001230 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001231 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001232 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001233 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001234 }
1235
Amith Yamasani0b285492011-04-14 17:35:23 -07001236 /**
1237 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1238 * cache it elsewhere.
1239 * @return the array of user ids.
1240 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001241 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001242 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001243 return mUserIds;
1244 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001245 }
1246
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001247 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001248 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001249 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001250 return;
1251 }
1252 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001253 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001254 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001255 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001256 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001257 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001258 int type;
1259 while ((type = parser.next()) != XmlPullParser.START_TAG
1260 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001261 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001262 }
1263
1264 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001265 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001266 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001267 return;
1268 }
1269
Amith Yamasani2a003292012-08-14 18:25:45 -07001270 mNextSerialNumber = -1;
1271 if (parser.getName().equals(TAG_USERS)) {
1272 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1273 if (lastSerialNumber != null) {
1274 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1275 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001276 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1277 if (versionNumber != null) {
1278 mUserVersion = Integer.parseInt(versionNumber);
1279 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001280 }
1281
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001282 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1283
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001284 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301285 if (type == XmlPullParser.START_TAG) {
1286 final String name = parser.getName();
1287 if (name.equals(TAG_USER)) {
1288 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001289
Amith Yamasani12747872015-12-07 14:19:49 -08001290 UserData userData = readUserLP(Integer.parseInt(id));
1291
1292 if (userData != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001293 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001294 mUsers.put(userData.info.id, userData);
1295 if (mNextSerialNumber < 0
1296 || mNextSerialNumber <= userData.info.id) {
1297 mNextSerialNumber = userData.info.id + 1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001298 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301299 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001300 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301301 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001302 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1303 && type != XmlPullParser.END_TAG) {
1304 if (type == XmlPullParser.START_TAG) {
1305 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001306 synchronized (mGuestRestrictions) {
1307 UserRestrictionsUtils
1308 .readRestrictions(parser, mGuestRestrictions);
1309 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001310 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1311 ) {
1312 UserRestrictionsUtils.readRestrictions(parser,
1313 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001314 }
1315 break;
1316 }
1317 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001318 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001319 }
1320 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001321 synchronized (mRestrictionsLock) {
1322 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1323 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001324 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001325 upgradeIfNecessaryLP();
1326 } catch (IOException | XmlPullParserException e) {
1327 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001328 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001329 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001330 }
1331 }
1332
Amith Yamasani6f34b412012-10-22 18:19:27 -07001333 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001334 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001335 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001336 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001337 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001338 int userVersion = mUserVersion;
1339 if (userVersion < 1) {
1340 // Assign a proper name for the owner, if not initialized correctly before
Amith Yamasani12747872015-12-07 14:19:49 -08001341 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1342 if ("Primary".equals(userData.info.name)) {
1343 userData.info.name =
1344 mContext.getResources().getString(com.android.internal.R.string.owner_name);
1345 scheduleWriteUser(userData);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001346 }
1347 userVersion = 1;
1348 }
1349
Amith Yamasanibc9625052012-11-15 14:39:18 -08001350 if (userVersion < 2) {
1351 // Owner should be marked as initialized
Amith Yamasani12747872015-12-07 14:19:49 -08001352 UserData userData = getUserDataNoChecks(UserHandle.USER_SYSTEM);
1353 if ((userData.info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1354 userData.info.flags |= UserInfo.FLAG_INITIALIZED;
1355 scheduleWriteUser(userData);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001356 }
1357 userVersion = 2;
1358 }
1359
Amith Yamasani350962c2013-08-06 11:18:53 -07001360
Amith Yamasani5e486f52013-08-07 11:06:44 -07001361 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001362 userVersion = 4;
1363 }
1364
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001365 if (userVersion < 5) {
1366 initDefaultGuestRestrictions();
1367 userVersion = 5;
1368 }
1369
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001370 if (userVersion < 6) {
1371 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001372 synchronized (mUsersLock) {
1373 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001374 UserData userData = mUsers.valueAt(i);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001375 // In non-split mode, only user 0 can have restricted profiles
Amith Yamasani12747872015-12-07 14:19:49 -08001376 if (!splitSystemUser && userData.info.isRestricted()
1377 && (userData.info.restrictedProfileParentId
1378 == UserInfo.NO_PROFILE_GROUP_ID)) {
1379 userData.info.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1380 scheduleWriteUser(userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001381 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001382 }
1383 }
1384 userVersion = 6;
1385 }
1386
Amith Yamasani6f34b412012-10-22 18:19:27 -07001387 if (userVersion < USER_VERSION) {
1388 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1389 + USER_VERSION);
1390 } else {
1391 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001392
1393 if (originalVersion < mUserVersion) {
1394 writeUserListLP();
1395 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001396 }
1397 }
1398
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001399 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001400 int flags = UserInfo.FLAG_INITIALIZED;
1401 // In split system user mode, the admin and primary flags are assigned to the first human
1402 // user.
1403 if (!UserManager.isSplitSystemUser()) {
1404 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1405 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001406 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001407 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001408 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001409 flags);
Amith Yamasani12747872015-12-07 14:19:49 -08001410 UserData userData = new UserData();
1411 userData.info = system;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001412 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001413 mUsers.put(system.id, userData);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001414 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001415 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001416 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001417
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001418 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001419 synchronized (mRestrictionsLock) {
1420 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1421 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001422
Fyodor Kupolov82402752015-10-28 14:54:51 -07001423 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001424 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001425
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001426 writeUserListLP();
Amith Yamasani12747872015-12-07 14:19:49 -08001427 writeUserLP(userData);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001428 }
1429
Amith Yamasani12747872015-12-07 14:19:49 -08001430 private void scheduleWriteUser(UserData UserData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001431 if (DBG) {
1432 debug("scheduleWriteUser");
1433 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001434 // No need to wrap it within a lock -- worst case, we'll just post the same message
1435 // twice.
Amith Yamasani12747872015-12-07 14:19:49 -08001436 if (!mHandler.hasMessages(WRITE_USER_MSG, UserData)) {
1437 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, UserData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001438 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1439 }
1440 }
1441
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001442 /*
1443 * Writes the user file in this format:
1444 *
1445 * <user flags="20039023" id="0">
1446 * <name>Primary</name>
1447 * </user>
1448 */
Amith Yamasani12747872015-12-07 14:19:49 -08001449 private void writeUserLP(UserData userData) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001450 if (DBG) {
Amith Yamasani12747872015-12-07 14:19:49 -08001451 debug("writeUserLP " + userData);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001452 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001453 FileOutputStream fos = null;
Amith Yamasani12747872015-12-07 14:19:49 -08001454 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userData.info.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001455 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001456 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001457 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1458
1459 // XmlSerializer serializer = XmlUtils.serializerInstance();
1460 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001461 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001462 serializer.startDocument(null, true);
1463 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1464
Amith Yamasani12747872015-12-07 14:19:49 -08001465 final UserInfo userInfo = userData.info;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001466 serializer.startTag(null, TAG_USER);
1467 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001468 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001469 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001470 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1471 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1472 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001473 if (userInfo.iconPath != null) {
1474 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1475 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001476 if (userInfo.partial) {
1477 serializer.attribute(null, ATTR_PARTIAL, "true");
1478 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001479 if (userInfo.guestToRemove) {
1480 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1481 }
Kenny Guy2a764942014-04-02 13:29:20 +01001482 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1483 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1484 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001485 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001486 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1487 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1488 Integer.toString(userInfo.restrictedProfileParentId));
1489 }
Amith Yamasani12747872015-12-07 14:19:49 -08001490 // Write seed data
1491 if (userData.persistSeedData) {
1492 if (userData.seedAccountName != null) {
1493 serializer.attribute(null, ATTR_SEED_ACCOUNT_NAME, userData.seedAccountName);
1494 }
1495 if (userData.seedAccountType != null) {
1496 serializer.attribute(null, ATTR_SEED_ACCOUNT_TYPE, userData.seedAccountType);
1497 }
1498 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001499 serializer.startTag(null, TAG_NAME);
1500 serializer.text(userInfo.name);
1501 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001502 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001503 UserRestrictionsUtils.writeRestrictions(serializer,
1504 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1505 UserRestrictionsUtils.writeRestrictions(serializer,
1506 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1507 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001508 }
Amith Yamasani12747872015-12-07 14:19:49 -08001509
1510 if (userData.account != null) {
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001511 serializer.startTag(null, TAG_ACCOUNT);
Amith Yamasani12747872015-12-07 14:19:49 -08001512 serializer.text(userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001513 serializer.endTag(null, TAG_ACCOUNT);
1514 }
1515
Amith Yamasani12747872015-12-07 14:19:49 -08001516 if (userData.persistSeedData && userData.seedAccountOptions != null) {
1517 serializer.startTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1518 userData.seedAccountOptions.saveToXml(serializer);
1519 serializer.endTag(null, TAG_SEED_ACCOUNT_OPTIONS);
1520 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001521 serializer.endTag(null, TAG_USER);
1522
1523 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001524 userFile.finishWrite(fos);
1525 } catch (Exception ioe) {
Amith Yamasani12747872015-12-07 14:19:49 -08001526 Slog.e(LOG_TAG, "Error writing user info " + userData.info.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001527 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001528 }
1529 }
1530
1531 /*
1532 * Writes the user list file in this format:
1533 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001534 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001535 * <user id="0"></user>
1536 * <user id="2"></user>
1537 * </users>
1538 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001539 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001540 if (DBG) {
1541 debug("writeUserList");
1542 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001543 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001544 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001545 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001546 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001547 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1548
1549 // XmlSerializer serializer = XmlUtils.serializerInstance();
1550 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001551 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001552 serializer.startDocument(null, true);
1553 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1554
1555 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001556 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001557 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001558
Adam Lesinskieddeb492014-09-08 17:50:03 -07001559 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001560 synchronized (mGuestRestrictions) {
1561 UserRestrictionsUtils
1562 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1563 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301564 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001565 synchronized (mRestrictionsLock) {
1566 UserRestrictionsUtils.writeRestrictions(serializer,
1567 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1568 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001569 int[] userIdsToWrite;
1570 synchronized (mUsersLock) {
1571 userIdsToWrite = new int[mUsers.size()];
1572 for (int i = 0; i < userIdsToWrite.length; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001573 UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001574 userIdsToWrite[i] = user.id;
1575 }
1576 }
1577 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001578 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001579 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001580 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001581 }
1582
1583 serializer.endTag(null, TAG_USERS);
1584
1585 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001586 userListFile.finishWrite(fos);
1587 } catch (Exception e) {
1588 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001589 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001590 }
1591 }
1592
Amith Yamasani12747872015-12-07 14:19:49 -08001593 private UserData readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001594 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001595 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001596 String name = null;
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001597 String account = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001598 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001599 long creationTime = 0L;
1600 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001601 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001602 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001603 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001604 boolean guestToRemove = false;
Amith Yamasani12747872015-12-07 14:19:49 -08001605 boolean persistSeedData = false;
1606 String seedAccountName = null;
1607 String seedAccountType = null;
1608 PersistableBundle seedAccountOptions = null;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001609 Bundle baseRestrictions = new Bundle();
1610 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001611
1612 FileInputStream fis = null;
1613 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001614 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001615 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001616 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001617 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001618 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001619 int type;
1620 while ((type = parser.next()) != XmlPullParser.START_TAG
1621 && type != XmlPullParser.END_DOCUMENT) {
Amith Yamasani12747872015-12-07 14:19:49 -08001622 // Skip
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001623 }
1624
1625 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001626 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001627 return null;
1628 }
1629
1630 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001631 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1632 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001633 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001634 return null;
1635 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001636 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1637 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001638 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001639 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1640 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001641 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1642 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001643 restrictedProfileParentId = readIntAttribute(parser,
1644 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001645 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1646 if ("true".equals(valueString)) {
1647 partial = true;
1648 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001649 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1650 if ("true".equals(valueString)) {
1651 guestToRemove = true;
1652 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001653
Amith Yamasani12747872015-12-07 14:19:49 -08001654 seedAccountName = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_NAME);
1655 seedAccountType = parser.getAttributeValue(null, ATTR_SEED_ACCOUNT_TYPE);
1656 if (seedAccountName != null || seedAccountType != null) {
1657 persistSeedData = true;
1658 }
1659
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001660 int outerDepth = parser.getDepth();
1661 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1662 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1663 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1664 continue;
1665 }
1666 String tag = parser.getName();
1667 if (TAG_NAME.equals(tag)) {
1668 type = parser.next();
1669 if (type == XmlPullParser.TEXT) {
1670 name = parser.getText();
1671 }
1672 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1674 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1675 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08001676 } else if (TAG_ACCOUNT.equals(tag)) {
1677 type = parser.next();
1678 if (type == XmlPullParser.TEXT) {
1679 account = parser.getText();
1680 }
Amith Yamasani12747872015-12-07 14:19:49 -08001681 } else if (TAG_SEED_ACCOUNT_OPTIONS.equals(tag)) {
1682 seedAccountOptions = PersistableBundle.restoreFromXml(parser);
1683 persistSeedData = true;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001684 }
1685 }
1686 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001687
Amith Yamasani12747872015-12-07 14:19:49 -08001688 // Create the UserInfo object that gets passed around
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001689 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001690 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001691 userInfo.creationTime = creationTime;
1692 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001693 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001694 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001695 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001696 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Amith Yamasani12747872015-12-07 14:19:49 -08001697
1698 // Create the UserData object that's internal to this class
1699 UserData userData = new UserData();
1700 userData.info = userInfo;
1701 userData.account = account;
1702 userData.seedAccountName = seedAccountName;
1703 userData.seedAccountType = seedAccountType;
1704 userData.persistSeedData = persistSeedData;
1705 userData.seedAccountOptions = seedAccountOptions;
1706
Makoto Onuki068c54a2015-10-13 14:34:03 -07001707 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001708 mBaseUserRestrictions.put(id, baseRestrictions);
1709 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001710 }
Amith Yamasani12747872015-12-07 14:19:49 -08001711 return userData;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001712 } catch (IOException ioe) {
1713 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001714 } finally {
1715 if (fis != null) {
1716 try {
1717 fis.close();
1718 } catch (IOException e) {
1719 }
1720 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001721 }
1722 return null;
1723 }
1724
Amith Yamasani920ace02012-09-20 22:15:37 -07001725 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1726 String valueString = parser.getAttributeValue(null, attr);
1727 if (valueString == null) return defaultValue;
1728 try {
1729 return Integer.parseInt(valueString);
1730 } catch (NumberFormatException nfe) {
1731 return defaultValue;
1732 }
1733 }
1734
1735 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1736 String valueString = parser.getAttributeValue(null, attr);
1737 if (valueString == null) return defaultValue;
1738 try {
1739 return Long.parseLong(valueString);
1740 } catch (NumberFormatException nfe) {
1741 return defaultValue;
1742 }
1743 }
1744
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001745 private boolean isPackageInstalled(String pkg, int userId) {
1746 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1747 PackageManager.GET_UNINSTALLED_PACKAGES,
1748 userId);
1749 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1750 return false;
1751 }
1752 return true;
1753 }
1754
Amith Yamasanib82add22013-07-09 11:24:44 -07001755 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001756 * Removes the app restrictions file for a specific package and user id, if it exists.
1757 */
1758 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1759 synchronized (mPackagesLock) {
1760 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001761 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001762 if (resFile.exists()) {
1763 resFile.delete();
1764 }
1765 }
1766 }
1767
Kenny Guya52dc3e2014-02-11 15:33:14 +00001768 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001769 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001770 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001771 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001772 }
1773
Amith Yamasani258848d2012-08-10 17:06:33 -07001774 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001775 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001776 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001777 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001778 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001779
Jessica Hummelbe81c802014-04-22 15:49:22 +01001780 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001781 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001782 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1783 return null;
1784 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001785 if (ActivityManager.isLowRamDeviceStatic()) {
1786 return null;
1787 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001788 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001789 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001790 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001791 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001792 UserInfo userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001793 UserData userData;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001794 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001795 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001796 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001797 UserData parent = null;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001798 if (parentId != UserHandle.USER_NULL) {
1799 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001800 parent = getUserDataLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001801 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001802 if (parent == null) return null;
1803 }
1804 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1805 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1806 return null;
1807 }
1808 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1809 // If we're not adding a guest user or a managed profile and the limit has
1810 // been reached, cannot add a user.
1811 return null;
1812 }
1813 // If we're adding a guest and there already exists one, bail.
1814 if (isGuest && findCurrentGuestUser() != null) {
1815 return null;
1816 }
1817 // In legacy mode, restricted profile's parent can only be the owner user
1818 if (isRestricted && !UserManager.isSplitSystemUser()
1819 && (parentId != UserHandle.USER_SYSTEM)) {
1820 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1821 return null;
1822 }
1823 if (isRestricted && UserManager.isSplitSystemUser()) {
1824 if (parent == null) {
1825 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1826 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001827 return null;
1828 }
Amith Yamasani12747872015-12-07 14:19:49 -08001829 if (!parent.info.canHaveProfile()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001830 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1831 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001832 return null;
1833 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001834 }
1835 // In split system user mode, we assign the first human user the primary flag.
1836 // And if there is no device owner, we also assign the admin flag to primary user.
1837 if (UserManager.isSplitSystemUser()
1838 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1839 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001840 synchronized (mUsersLock) {
1841 if (!mIsDeviceManaged) {
1842 flags |= UserInfo.FLAG_ADMIN;
1843 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001844 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001845 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001846
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001847 userId = getNextAvailableId();
1848 Environment.getUserSystemDirectory(userId).mkdirs();
Lenka Trochtova02fee152015-12-22 14:26:18 +01001849 boolean ephemeralGuests = Resources.getSystem()
1850 .getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001851
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001852 synchronized (mUsersLock) {
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01001853 // Add ephemeral flag to guests/users if required. Also inherit it from parent.
1854 if ((isGuest && ephemeralGuests) || mForceEphemeralUsers
1855 || (parent != null && parent.info.isEphemeral())) {
1856 flags |= UserInfo.FLAG_EPHEMERAL;
1857 }
1858
1859 userInfo = new UserInfo(userId, name, null, flags);
1860 userInfo.serialNumber = mNextSerialNumber++;
1861 long now = System.currentTimeMillis();
1862 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1863 userInfo.partial = true;
1864 userData = new UserData();
1865 userData.info = userInfo;
Amith Yamasani12747872015-12-07 14:19:49 -08001866 mUsers.put(userId, userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001867 }
1868 writeUserListLP();
1869 if (parent != null) {
1870 if (isManagedProfile) {
Amith Yamasani12747872015-12-07 14:19:49 -08001871 if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1872 parent.info.profileGroupId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001873 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001874 }
Amith Yamasani12747872015-12-07 14:19:49 -08001875 userInfo.profileGroupId = parent.info.profileGroupId;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001876 } else if (isRestricted) {
Amith Yamasani12747872015-12-07 14:19:49 -08001877 if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1878 parent.info.restrictedProfileParentId = parent.info.id;
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001879 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001880 }
Amith Yamasani12747872015-12-07 14:19:49 -08001881 userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001882 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001883 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001884 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001885 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001886 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001887 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1888 final String volumeUuid = vol.getFsUuid();
1889 try {
1890 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001891 storage.prepareUserStorage(
1892 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001893 enforceSerialNumber(userDir, userInfo.serialNumber);
1894 } catch (IOException e) {
1895 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1896 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001897 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001898 mPm.createNewUser(userId);
1899 userInfo.partial = false;
1900 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001901 writeUserLP(userData);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001902 }
1903 updateUserIds();
1904 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001905 if (isGuest) {
1906 synchronized (mGuestRestrictions) {
1907 restrictions.putAll(mGuestRestrictions);
1908 }
1909 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001910 synchronized (mRestrictionsLock) {
1911 mBaseUserRestrictions.append(userId, restrictions);
1912 }
1913 mPm.newUserCreated(userId);
1914 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1915 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1916 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1917 android.Manifest.permission.MANAGE_USERS);
Fyodor Kupolov8385e4b2015-12-29 18:15:32 -08001918 MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001919 } finally {
1920 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001921 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001922 return userInfo;
1923 }
1924
Amith Yamasani0b285492011-04-14 17:35:23 -07001925 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001926 * @hide
1927 */
Amith Yamasani12747872015-12-07 14:19:49 -08001928 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001929 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1930 checkManageUsersPermission("setupRestrictedProfile");
1931 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1932 if (user == null) {
1933 return null;
1934 }
1935 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1936 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1937 // the putIntForUser() will fail.
1938 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1939 android.provider.Settings.Secure.LOCATION_MODE,
1940 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1941 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1942 return user;
1943 }
1944
1945 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001946 * Find the current guest user. If the Guest user is partial,
1947 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001948 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001949 private UserInfo findCurrentGuestUser() {
1950 synchronized (mUsersLock) {
1951 final int size = mUsers.size();
1952 for (int i = 0; i < size; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08001953 final UserInfo user = mUsers.valueAt(i).info;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001954 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1955 return user;
1956 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001957 }
1958 }
1959 return null;
1960 }
1961
1962 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001963 * Mark this guest user for deletion to allow us to create another guest
1964 * and switch to that user before actually removing this guest.
1965 * @param userHandle the userid of the current guest
1966 * @return whether the user could be marked for deletion
1967 */
Amith Yamasani12747872015-12-07 14:19:49 -08001968 @Override
Amith Yamasani1df14732014-08-29 21:37:27 -07001969 public boolean markGuestForDeletion(int userHandle) {
1970 checkManageUsersPermission("Only the system can remove users");
1971 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1972 UserManager.DISALLOW_REMOVE_USER, false)) {
1973 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1974 return false;
1975 }
1976
1977 long ident = Binder.clearCallingIdentity();
1978 try {
Amith Yamasani12747872015-12-07 14:19:49 -08001979 final UserData userData;
Amith Yamasani1df14732014-08-29 21:37:27 -07001980 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001981 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08001982 userData = mUsers.get(userHandle);
1983 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001984 return false;
1985 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001986 }
Amith Yamasani12747872015-12-07 14:19:49 -08001987 if (!userData.info.isGuest()) {
Amith Yamasani1df14732014-08-29 21:37:27 -07001988 return false;
1989 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001990 // We set this to a guest user that is to be removed. This is a temporary state
1991 // where we are allowed to add new Guest users, even if this one is still not
1992 // removed. This user will still show up in getUserInfo() calls.
1993 // If we don't get around to removing this Guest user, it will be purged on next
1994 // startup.
Amith Yamasani12747872015-12-07 14:19:49 -08001995 userData.info.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001996 // Mark it as disabled, so that it isn't returned any more when
1997 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08001998 userData.info.flags |= UserInfo.FLAG_DISABLED;
1999 writeUserLP(userData);
Amith Yamasani1df14732014-08-29 21:37:27 -07002000 }
2001 } finally {
2002 Binder.restoreCallingIdentity(ident);
2003 }
2004 return true;
2005 }
2006
2007 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002008 * Removes a user and all data directories created for that user. This method should be called
2009 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07002010 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07002011 */
Amith Yamasani12747872015-12-07 14:19:49 -08002012 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -07002013 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002014 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04002015 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
2016 UserManager.DISALLOW_REMOVE_USER, false)) {
2017 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
2018 return false;
2019 }
2020
Kenny Guyee58b4f2014-05-23 15:19:53 +01002021 long ident = Binder.clearCallingIdentity();
2022 try {
Amith Yamasani12747872015-12-07 14:19:49 -08002023 final UserData userData;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07002024 int currentUser = ActivityManager.getCurrentUser();
2025 if (currentUser == userHandle) {
2026 Log.w(LOG_TAG, "Current user cannot be removed");
2027 return false;
2028 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002029 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002030 synchronized (mUsersLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002031 userData = mUsers.get(userHandle);
2032 if (userHandle == 0 || userData == null || mRemovingUserIds.get(userHandle)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002033 return false;
2034 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002035
Fyodor Kupolov82402752015-10-28 14:54:51 -07002036 // We remember deleted user IDs to prevent them from being
2037 // reused during the current boot; they can still be reused
2038 // after a reboot.
2039 mRemovingUserIds.put(userHandle, true);
2040 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08002041
Kenny Guyee58b4f2014-05-23 15:19:53 +01002042 try {
2043 mAppOpsService.removeUser(userHandle);
2044 } catch (RemoteException e) {
2045 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
2046 }
2047 // Set this to a partially created user, so that the user will be purged
2048 // on next startup, in case the runtime stops now before stopping and
2049 // removing the user completely.
Amith Yamasani12747872015-12-07 14:19:49 -08002050 userData.info.partial = true;
Kenny Guyee58b4f2014-05-23 15:19:53 +01002051 // Mark it as disabled, so that it isn't returned any more when
2052 // profiles are queried.
Amith Yamasani12747872015-12-07 14:19:49 -08002053 userData.info.flags |= UserInfo.FLAG_DISABLED;
2054 writeUserLP(userData);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002055 }
2056
Amith Yamasani12747872015-12-07 14:19:49 -08002057 if (userData.info.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
2058 && userData.info.isManagedProfile()) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002059 // Send broadcast to notify system that the user removed was a
2060 // managed user.
Amith Yamasani12747872015-12-07 14:19:49 -08002061 sendProfileRemovedBroadcast(userData.info.profileGroupId, userData.info.id);
Kenny Guyee58b4f2014-05-23 15:19:53 +01002062 }
2063
2064 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
2065 int res;
2066 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07002067 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
2068 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01002069 @Override
2070 public void userStopped(int userId) {
2071 finishRemoveUser(userId);
2072 }
2073 @Override
2074 public void userStopAborted(int userId) {
2075 }
2076 });
2077 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002078 return false;
2079 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01002080 return res == ActivityManager.USER_OP_SUCCESS;
2081 } finally {
2082 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002083 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002084 }
2085
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002086 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07002087 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002088 // Let other services shutdown any activity and clean up their state before completely
2089 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002090 long ident = Binder.clearCallingIdentity();
2091 try {
2092 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
2093 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002094 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
2095 android.Manifest.permission.MANAGE_USERS,
2096
2097 new BroadcastReceiver() {
2098 @Override
2099 public void onReceive(Context context, Intent intent) {
2100 if (DBG) {
2101 Slog.i(LOG_TAG,
2102 "USER_REMOVED broadcast sent, cleaning up user data "
2103 + userHandle);
2104 }
2105 new Thread() {
Amith Yamasani12747872015-12-07 14:19:49 -08002106 @Override
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002107 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07002108 // Clean up any ActivityManager state
2109 LocalServices.getService(ActivityManagerInternal.class)
2110 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002111 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07002112 }
2113 }.start();
2114 }
2115 },
2116
2117 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002118 } finally {
2119 Binder.restoreCallingIdentity(ident);
2120 }
Amith Yamasani2a003292012-08-14 18:25:45 -07002121 }
2122
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002123 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002124 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002125 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002126 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002127
2128 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07002129 synchronized (mUsersLock) {
2130 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08002131 mIsUserManaged.delete(userHandle);
2132 }
2133 synchronized (mRestrictionsLock) {
2134 mBaseUserRestrictions.remove(userHandle);
2135 mAppliedUserRestrictions.remove(userHandle);
2136 mCachedEffectiveUserRestrictions.remove(userHandle);
2137 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002138 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002139 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07002140 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002141 userFile.delete();
2142 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002143 synchronized (mPackagesLock) {
2144 writeUserListLP();
2145 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002146 updateUserIds();
Amith Yamasani12747872015-12-07 14:19:49 -08002147 File userDir = Environment.getUserSystemDirectory(userHandle);
2148 File renamedUserDir = Environment.getUserSystemDirectory(UserHandle.USER_NULL - userHandle);
2149 if (userDir.renameTo(renamedUserDir)) {
2150 removeDirectoryRecursive(renamedUserDir);
2151 } else {
2152 removeDirectoryRecursive(userDir);
2153 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002154 }
2155
Amith Yamasani61f57372012-08-31 12:12:28 -07002156 private void removeDirectoryRecursive(File parent) {
2157 if (parent.isDirectory()) {
2158 String[] files = parent.list();
2159 for (String filename : files) {
2160 File child = new File(parent, filename);
2161 removeDirectoryRecursive(child);
2162 }
2163 }
2164 parent.delete();
2165 }
2166
Kenny Guyf8d3a232014-05-15 16:09:52 +01002167 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01002168 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01002169 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
2170 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002171 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
Jeff Sharkeyaf6ec292015-12-17 11:19:00 -07002172 managedProfileIntent.putExtra(Intent.EXTRA_USER_HANDLE, removedUserId);
Kenny Guyf8d3a232014-05-15 16:09:52 +01002173 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01002174 }
2175
Amith Yamasani2a003292012-08-14 18:25:45 -07002176 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002177 public Bundle getApplicationRestrictions(String packageName) {
2178 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
2179 }
2180
2181 @Override
2182 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002183 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07002184 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002185 checkSystemOrRoot("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002186 }
2187 synchronized (mPackagesLock) {
2188 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002189 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002190 }
2191 }
2192
2193 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002194 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002195 int userId) {
Esteban Talavera5b9f1672015-12-11 15:22:34 +00002196 checkSystemOrRoot("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002197 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002198 if (restrictions == null || restrictions.isEmpty()) {
2199 cleanAppRestrictionsForPackage(packageName, userId);
2200 } else {
2201 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002202 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002203 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002204 }
Robin Lee66e5d962014-04-09 16:44:21 +01002205
Kenny Guyd21b2182014-07-17 16:38:55 +01002206 if (isPackageInstalled(packageName, userId)) {
2207 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2208 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2209 changeIntent.setPackage(packageName);
2210 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2211 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2212 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002213 }
2214
2215 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002216 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002217 try {
2218 return mContext.getPackageManager().getApplicationInfo(packageName,
2219 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2220 } catch (NameNotFoundException nnfe) {
2221 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002222 } finally {
2223 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002224 }
2225 }
2226
Fyodor Kupolov82402752015-10-28 14:54:51 -07002227 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002228 AtomicFile restrictionsFile =
2229 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2230 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002231 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002232 }
2233
2234 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002235 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002236 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002237 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002238 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002239 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002240 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002241
2242 FileInputStream fis = null;
2243 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002244 fis = restrictionsFile.openRead();
2245 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002246 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002247 XmlUtils.nextElement(parser);
2248 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002249 Slog.e(LOG_TAG, "Unable to read restrictions file "
2250 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002251 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002252 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002253 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2254 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002255 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002256 } catch (IOException|XmlPullParserException e) {
2257 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002258 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002259 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002260 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002261 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002262 }
2263
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002264 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2265 XmlPullParser parser) throws XmlPullParserException, IOException {
2266 int type = parser.getEventType();
2267 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2268 String key = parser.getAttributeValue(null, ATTR_KEY);
2269 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2270 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2271 if (multiple != null) {
2272 values.clear();
2273 int count = Integer.parseInt(multiple);
2274 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2275 if (type == XmlPullParser.START_TAG
2276 && parser.getName().equals(TAG_VALUE)) {
2277 values.add(parser.nextText().trim());
2278 count--;
2279 }
2280 }
2281 String [] valueStrings = new String[values.size()];
2282 values.toArray(valueStrings);
2283 restrictions.putStringArray(key, valueStrings);
2284 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2285 restrictions.putBundle(key, readBundleEntry(parser, values));
2286 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2287 final int outerDepth = parser.getDepth();
2288 ArrayList<Bundle> bundleList = new ArrayList<>();
2289 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2290 Bundle childBundle = readBundleEntry(parser, values);
2291 bundleList.add(childBundle);
2292 }
2293 restrictions.putParcelableArray(key,
2294 bundleList.toArray(new Bundle[bundleList.size()]));
2295 } else {
2296 String value = parser.nextText().trim();
2297 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2298 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2299 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2300 restrictions.putInt(key, Integer.parseInt(value));
2301 } else {
2302 restrictions.putString(key, value);
2303 }
2304 }
2305 }
2306 }
2307
2308 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2309 throws IOException, XmlPullParserException {
2310 Bundle childBundle = new Bundle();
2311 final int outerDepth = parser.getDepth();
2312 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2313 readEntry(childBundle, values, parser);
2314 }
2315 return childBundle;
2316 }
2317
Fyodor Kupolov82402752015-10-28 14:54:51 -07002318 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002319 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002320 AtomicFile restrictionsFile = new AtomicFile(
2321 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002322 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002323 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002324 }
2325
2326 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002327 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002328 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002329 try {
2330 fos = restrictionsFile.startWrite();
2331 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2332
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002333 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002334 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002335 serializer.startDocument(null, true);
2336 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2337
2338 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002339 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002340 serializer.endTag(null, TAG_RESTRICTIONS);
2341
2342 serializer.endDocument();
2343 restrictionsFile.finishWrite(fos);
2344 } catch (Exception e) {
2345 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002346 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2347 }
2348 }
2349
2350 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2351 throws IOException {
2352 for (String key : restrictions.keySet()) {
2353 Object value = restrictions.get(key);
2354 serializer.startTag(null, TAG_ENTRY);
2355 serializer.attribute(null, ATTR_KEY, key);
2356
2357 if (value instanceof Boolean) {
2358 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2359 serializer.text(value.toString());
2360 } else if (value instanceof Integer) {
2361 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2362 serializer.text(value.toString());
2363 } else if (value == null || value instanceof String) {
2364 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2365 serializer.text(value != null ? (String) value : "");
2366 } else if (value instanceof Bundle) {
2367 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2368 writeBundle((Bundle) value, serializer);
2369 } else if (value instanceof Parcelable[]) {
2370 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2371 Parcelable[] array = (Parcelable[]) value;
2372 for (Parcelable parcelable : array) {
2373 if (!(parcelable instanceof Bundle)) {
2374 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2375 }
2376 serializer.startTag(null, TAG_ENTRY);
2377 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2378 writeBundle((Bundle) parcelable, serializer);
2379 serializer.endTag(null, TAG_ENTRY);
2380 }
2381 } else {
2382 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2383 String[] values = (String[]) value;
2384 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2385 for (String choice : values) {
2386 serializer.startTag(null, TAG_VALUE);
2387 serializer.text(choice != null ? choice : "");
2388 serializer.endTag(null, TAG_VALUE);
2389 }
2390 }
2391 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002392 }
2393 }
2394
2395 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002396 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002397 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002398 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002399 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002400 }
2401 }
2402
2403 @Override
2404 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002405 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002406 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002407 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002408 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002409 }
2410 // Not found
2411 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002412 }
2413 }
2414
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002415 @Override
2416 public long getUserCreationTime(int userHandle) {
2417 int callingUserId = UserHandle.getCallingUserId();
2418 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002419 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002420 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002421 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002422 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002423 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002424 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002425 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002426 }
2427 }
2428 }
2429 if (userInfo == null) {
2430 throw new SecurityException("userHandle can only be the calling user or a managed "
2431 + "profile associated with this user");
2432 }
2433 return userInfo.creationTime;
2434 }
2435
Amith Yamasani0b285492011-04-14 17:35:23 -07002436 /**
2437 * Caches the list of user ids in an array, adjusting the array size when necessary.
2438 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002439 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002440 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002441 synchronized (mUsersLock) {
2442 final int userSize = mUsers.size();
2443 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002444 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002445 num++;
2446 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002447 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002448 final int[] newUsers = new int[num];
2449 int n = 0;
2450 for (int i = 0; i < userSize; i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002451 if (!mUsers.valueAt(i).info.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002452 newUsers[n++] = mUsers.keyAt(i);
2453 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002454 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002455 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002456 }
2457 }
2458
2459 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002460 * Called right before a user is started. This gives us a chance to prepare
2461 * app storage and apply any user restrictions.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002462 */
2463 public void onBeforeStartUser(int userId) {
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002464 mPm.reconcileAppsData(userId, Installer.FLAG_DE_STORAGE);
2465
2466 if (userId != UserHandle.USER_SYSTEM) {
2467 synchronized (mRestrictionsLock) {
2468 applyUserRestrictionsLR(userId);
2469 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002470 }
2471 }
2472
2473 /**
Jeff Sharkey0e62384c2016-01-13 18:52:55 -07002474 * Called right before a user is unlocked. This gives us a chance to prepare
2475 * app storage.
2476 */
2477 public void onBeforeUnlockUser(int userId) {
2478 mPm.reconcileAppsData(userId, Installer.FLAG_CE_STORAGE);
2479 }
2480
2481 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002482 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002483 * @param userId the user that was just foregrounded
2484 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002485 public void onUserForeground(int userId) {
Amith Yamasani12747872015-12-07 14:19:49 -08002486 UserData userData = getUserDataNoChecks(userId);
2487 if (userData == null || userData.info.partial) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002488 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2489 return;
2490 }
2491 long now = System.currentTimeMillis();
2492 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani12747872015-12-07 14:19:49 -08002493 userData.info.lastLoggedInTime = now;
2494 scheduleWriteUser(userData);
Amith Yamasani920ace02012-09-20 22:15:37 -07002495 }
2496 }
2497
2498 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002499 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002500 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2501 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002502 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002503 private int getNextAvailableId() {
2504 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002505 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002506 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002507 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002508 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002509 }
2510 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002511 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002512 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002513 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002514 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002515
Amith Yamasanifc95e702013-09-26 13:20:17 -07002516 private String packageToRestrictionsFileName(String packageName) {
2517 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2518 }
2519
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002520 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002521 * Enforce that serial number stored in user directory inode matches the
2522 * given expected value. Gracefully sets the serial number if currently
2523 * undefined.
2524 *
2525 * @throws IOException when problem extracting serial number, or serial
2526 * number is mismatched.
2527 */
2528 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2529 final int foundSerial = getSerialNumber(file);
2530 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2531
2532 if (foundSerial == -1) {
2533 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2534 try {
2535 setSerialNumber(file, serialNumber);
2536 } catch (IOException e) {
2537 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2538 }
2539
2540 } else if (foundSerial != serialNumber) {
2541 throw new IOException("Found serial number " + foundSerial
2542 + " doesn't match expected " + serialNumber);
2543 }
2544 }
2545
2546 /**
2547 * Set serial number stored in user directory inode.
2548 *
2549 * @throws IOException if serial number was already set
2550 */
2551 private static void setSerialNumber(File file, int serialNumber)
2552 throws IOException {
2553 try {
2554 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2555 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2556 } catch (ErrnoException e) {
2557 throw e.rethrowAsIOException();
2558 }
2559 }
2560
2561 /**
2562 * Return serial number stored in user directory inode.
2563 *
2564 * @return parsed serial number, or -1 if not set
2565 */
2566 private static int getSerialNumber(File file) throws IOException {
2567 try {
2568 final byte[] buf = new byte[256];
2569 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2570 final String serial = new String(buf, 0, len);
2571 try {
2572 return Integer.parseInt(serial);
2573 } catch (NumberFormatException e) {
2574 throw new IOException("Bad serial number: " + serial);
2575 }
2576 } catch (ErrnoException e) {
2577 if (e.errno == OsConstants.ENODATA) {
2578 return -1;
2579 } else {
2580 throw e.rethrowAsIOException();
2581 }
2582 }
2583 }
2584
Amith Yamasani920ace02012-09-20 22:15:37 -07002585 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08002586 public void setSeedAccountData(int userId, String accountName, String accountType,
2587 PersistableBundle accountOptions, boolean persist) {
2588 checkManageUsersPermission("Require MANAGE_USERS permission to set user seed data");
2589 synchronized (mPackagesLock) {
2590 final UserData userData;
2591 synchronized (mUsersLock) {
2592 userData = getUserDataLU(userId);
2593 if (userData == null) {
2594 Slog.e(LOG_TAG, "No such user for settings seed data u=" + userId);
2595 return;
2596 }
2597 userData.seedAccountName = accountName;
2598 userData.seedAccountType = accountType;
2599 userData.seedAccountOptions = accountOptions;
2600 userData.persistSeedData = persist;
2601 }
2602 if (persist) {
2603 writeUserLP(userData);
2604 }
2605 }
2606 }
2607
2608 @Override
2609 public String getSeedAccountName() throws RemoteException {
2610 checkManageUsersPermission("Cannot get seed account information");
2611 synchronized (mUsersLock) {
2612 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2613 return userData.seedAccountName;
2614 }
2615 }
2616
2617 @Override
2618 public String getSeedAccountType() throws RemoteException {
2619 checkManageUsersPermission("Cannot get seed account information");
2620 synchronized (mUsersLock) {
2621 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2622 return userData.seedAccountType;
2623 }
2624 }
2625
2626 @Override
2627 public PersistableBundle getSeedAccountOptions() throws RemoteException {
2628 checkManageUsersPermission("Cannot get seed account information");
2629 synchronized (mUsersLock) {
2630 UserData userData = getUserDataLU(UserHandle.getCallingUserId());
2631 return userData.seedAccountOptions;
2632 }
2633 }
2634
2635 @Override
2636 public void clearSeedAccountData() throws RemoteException {
2637 checkManageUsersPermission("Cannot clear seed account information");
2638 synchronized (mPackagesLock) {
2639 UserData userData;
2640 synchronized (mUsersLock) {
2641 userData = getUserDataLU(UserHandle.getCallingUserId());
2642 if (userData == null) return;
2643 userData.clearSeedAccountData();
2644 }
2645 writeUserLP(userData);
2646 }
2647 }
2648
2649 @Override
2650 public boolean someUserHasSeedAccount(String accountName, String accountType)
2651 throws RemoteException {
2652 checkManageUsersPermission("Cannot check seed account information");
2653 synchronized (mUsersLock) {
2654 final int userSize = mUsers.size();
2655 for (int i = 0; i < userSize; i++) {
2656 final UserData data = mUsers.valueAt(i);
2657 if (data.info.isInitialized()) continue;
2658 if (data.seedAccountName == null || !data.seedAccountName.equals(accountName)) {
2659 continue;
2660 }
2661 if (data.seedAccountType == null || !data.seedAccountType.equals(accountType)) {
2662 continue;
2663 }
2664 return true;
2665 }
2666 }
2667 return false;
2668 }
2669
2670 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002671 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2672 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2673 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2674 }
2675
2676 int onShellCommand(Shell shell, String cmd) {
2677 if (cmd == null) {
2678 return shell.handleDefaultCommands(cmd);
2679 }
2680
2681 final PrintWriter pw = shell.getOutPrintWriter();
2682 try {
2683 switch(cmd) {
2684 case "list":
2685 return runList(pw);
2686 }
2687 } catch (RemoteException e) {
2688 pw.println("Remote exception: " + e);
2689 }
2690 return -1;
2691 }
2692
2693 private int runList(PrintWriter pw) throws RemoteException {
2694 final IActivityManager am = ActivityManagerNative.getDefault();
2695 final List<UserInfo> users = getUsers(false);
2696 if (users == null) {
2697 pw.println("Error: couldn't get users");
2698 return 1;
2699 } else {
2700 pw.println("Users:");
2701 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002702 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002703 pw.println("\t" + users.get(i).toString() + running);
2704 }
2705 return 0;
2706 }
2707 }
2708
2709 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002710 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2711 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2712 != PackageManager.PERMISSION_GRANTED) {
2713 pw.println("Permission Denial: can't dump UserManager from from pid="
2714 + Binder.getCallingPid()
2715 + ", uid=" + Binder.getCallingUid()
2716 + " without permission "
2717 + android.Manifest.permission.DUMP);
2718 return;
2719 }
2720
2721 long now = System.currentTimeMillis();
2722 StringBuilder sb = new StringBuilder();
2723 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002724 synchronized (mUsersLock) {
2725 pw.println("Users:");
2726 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani12747872015-12-07 14:19:49 -08002727 UserData userData = mUsers.valueAt(i);
2728 if (userData == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002729 continue;
2730 }
Amith Yamasani12747872015-12-07 14:19:49 -08002731 UserInfo userInfo = userData.info;
2732 final int userId = userInfo.id;
2733 pw.print(" "); pw.print(userInfo);
2734 pw.print(" serialNo="); pw.print(userInfo.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002735 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002736 pw.print(" <removing> ");
2737 }
Amith Yamasani12747872015-12-07 14:19:49 -08002738 if (userInfo.partial) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002739 pw.print(" <partial>");
2740 }
2741 pw.println();
2742 pw.print(" Created: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002743 if (userInfo.creationTime == 0) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002744 pw.println("<unknown>");
2745 } else {
2746 sb.setLength(0);
Amith Yamasani12747872015-12-07 14:19:49 -08002747 TimeUtils.formatDuration(now - userInfo.creationTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002748 sb.append(" ago");
2749 pw.println(sb);
2750 }
2751 pw.print(" Last logged in: ");
Amith Yamasani12747872015-12-07 14:19:49 -08002752 if (userInfo.lastLoggedInTime == 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.lastLoggedInTime, sb);
Fyodor Kupolov82402752015-10-28 14:54:51 -07002757 sb.append(" ago");
2758 pw.println(sb);
2759 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002760 pw.print(" Has profile owner: ");
2761 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002762 pw.println(" Restrictions:");
2763 synchronized (mRestrictionsLock) {
2764 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002765 pw, " ", mBaseUserRestrictions.get(userInfo.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002766 pw.println(" Device policy local restrictions:");
2767 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002768 pw, " ", mDevicePolicyLocalUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002769 pw.println(" Effective restrictions:");
2770 UserRestrictionsUtils.dumpRestrictions(
Amith Yamasani12747872015-12-07 14:19:49 -08002771 pw, " ", mCachedEffectiveUserRestrictions.get(userInfo.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002772 }
Amith Yamasani12747872015-12-07 14:19:49 -08002773
2774 if (userData.account != null) {
2775 pw.print(" Account name: " + userData.account);
Xiaohui Chenb3b92582015-12-07 11:22:13 -08002776 pw.println();
2777 }
Amith Yamasani12747872015-12-07 14:19:49 -08002778
2779 if (userData.seedAccountName != null) {
2780 pw.print(" Seed account name: " + userData.seedAccountName);
2781 pw.println();
2782 if (userData.seedAccountType != null) {
2783 pw.print(" account type: " + userData.seedAccountType);
2784 pw.println();
2785 }
2786 if (userData.seedAccountOptions != null) {
2787 pw.print(" account options exist");
2788 pw.println();
2789 }
2790 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002791 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002792 }
Amith Yamasani12747872015-12-07 14:19:49 -08002793 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002794 pw.println(" Device policy global restrictions:");
2795 synchronized (mRestrictionsLock) {
2796 UserRestrictionsUtils
2797 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2798 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002799 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002800 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002801 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002802 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002803 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002804 synchronized (mUsersLock) {
2805 pw.println();
2806 pw.println(" Device managed: " + mIsDeviceManaged);
2807 }
Amith Yamasani12747872015-12-07 14:19:49 -08002808 // Dump some capabilities
2809 pw.println();
2810 pw.println(" Max users: " + UserManager.getMaxSupportedUsers());
2811 pw.println(" Supports switchable users: " + UserManager.supportsMultipleUsers());
Lenka Trochtova02fee152015-12-22 14:26:18 +01002812 pw.println(" All guests ephemeral: " + Resources.getSystem().getBoolean(
2813 com.android.internal.R.bool.config_guestUserEphemeral));
Amith Yamasani920ace02012-09-20 22:15:37 -07002814 }
2815 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002816
2817 final class MainHandler extends Handler {
2818
2819 @Override
2820 public void handleMessage(Message msg) {
2821 switch (msg.what) {
2822 case WRITE_USER_MSG:
2823 removeMessages(WRITE_USER_MSG, msg.obj);
2824 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002825 int userId = ((UserData) msg.obj).info.id;
2826 UserData userData = getUserDataNoChecks(userId);
2827 if (userData != null) {
2828 writeUserLP(userData);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002829 }
2830 }
2831 }
2832 }
2833 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002834
2835 /**
2836 * @param userId
2837 * @return whether the user has been initialized yet
2838 */
2839 boolean isInitialized(int userId) {
2840 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2841 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002842
2843 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002844 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002845 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2846 @Nullable Bundle globalRestrictions) {
2847 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2848 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002849 }
2850
2851 @Override
2852 public Bundle getBaseUserRestrictions(int userId) {
2853 synchronized (mRestrictionsLock) {
2854 return mBaseUserRestrictions.get(userId);
2855 }
2856 }
2857
2858 @Override
2859 public void setBaseUserRestrictionsByDpmsForMigration(
2860 int userId, Bundle baseRestrictions) {
2861 synchronized (mRestrictionsLock) {
2862 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002863 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002864 }
2865
Amith Yamasani12747872015-12-07 14:19:49 -08002866 final UserData userData = getUserDataNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002867 synchronized (mPackagesLock) {
Amith Yamasani12747872015-12-07 14:19:49 -08002868 if (userData != null) {
2869 writeUserLP(userData);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002870 } else {
2871 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2872 }
2873 }
2874 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002875
2876 @Override
2877 public boolean getUserRestriction(int userId, String key) {
2878 return getUserRestrictions(userId).getBoolean(key);
2879 }
2880
2881 @Override
2882 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2883 synchronized (mUserRestrictionsListeners) {
2884 mUserRestrictionsListeners.add(listener);
2885 }
2886 }
2887
2888 @Override
2889 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2890 synchronized (mUserRestrictionsListeners) {
2891 mUserRestrictionsListeners.remove(listener);
2892 }
2893 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002894
2895 @Override
2896 public void setDeviceManaged(boolean isManaged) {
2897 synchronized (mUsersLock) {
2898 mIsDeviceManaged = isManaged;
2899 }
2900 }
2901
2902 @Override
2903 public void setUserManaged(int userId, boolean isManaged) {
2904 synchronized (mUsersLock) {
2905 mIsUserManaged.put(userId, isManaged);
2906 }
2907 }
Oleksandr Peletskyi7f1f1df2016-01-18 15:40:21 +01002908
2909 @Override
2910 public void setUserIcon(int userId, Bitmap bitmap) {
2911 long ident = Binder.clearCallingIdentity();
2912 try {
2913 synchronized (mPackagesLock) {
2914 UserData userData = getUserDataNoChecks(userId);
2915 if (userData == null || userData.info.partial) {
2916 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
2917 return;
2918 }
2919 writeBitmapLP(userData.info, bitmap);
2920 writeUserLP(userData);
2921 }
2922 sendUserInfoChangedBroadcast(userId);
2923 } finally {
2924 Binder.restoreCallingIdentity(ident);
2925 }
2926 }
Lenka Trochtovaf348e8e2016-01-07 17:20:34 +01002927
2928 @Override
2929 public void setForceEphemeralUsers(boolean forceEphemeralUsers) {
2930 synchronized (mUsersLock) {
2931 mForceEphemeralUsers = forceEphemeralUsers;
2932 }
2933 }
2934
2935 @Override
2936 public void removeAllUsers() {
2937 if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
2938 // Remove the non-system users straight away.
2939 removeNonSystemUsers();
2940 } else {
2941 // Switch to the system user first and then remove the other users.
2942 BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
2943 @Override
2944 public void onReceive(Context context, Intent intent) {
2945 int userId =
2946 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2947 if (userId != UserHandle.USER_SYSTEM) {
2948 return;
2949 }
2950 mContext.unregisterReceiver(this);
2951 removeNonSystemUsers();
2952 }
2953 };
2954 IntentFilter userSwitchedFilter = new IntentFilter();
2955 userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
2956 mContext.registerReceiver(
2957 userSwitchedReceiver, userSwitchedFilter, null, mHandler);
2958
2959 // Switch to the system user.
2960 ActivityManager am =
2961 (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
2962 am.switchUser(UserHandle.USER_SYSTEM);
2963 }
2964 }
2965 }
2966
2967 /* Remove all the users except of the system one. */
2968 private void removeNonSystemUsers() {
2969 ArrayList<UserInfo> usersToRemove = new ArrayList<>();
2970 synchronized (mUsersLock) {
2971 final int userSize = mUsers.size();
2972 for (int i = 0; i < userSize; i++) {
2973 UserInfo ui = mUsers.valueAt(i).info;
2974 if (ui.id != UserHandle.USER_SYSTEM) {
2975 usersToRemove.add(ui);
2976 }
2977 }
2978 }
2979 for (UserInfo ui: usersToRemove) {
2980 removeUser(ui.id);
2981 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002982 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002983
2984 private class Shell extends ShellCommand {
2985 @Override
2986 public int onCommand(String cmd) {
2987 return onShellCommand(this, cmd);
2988 }
2989
2990 @Override
2991 public void onHelp() {
2992 final PrintWriter pw = getOutPrintWriter();
2993 pw.println("User manager (user) commands:");
2994 pw.println(" help");
2995 pw.println(" Print this help text.");
2996 pw.println("");
2997 pw.println(" list");
2998 pw.println(" Prints all users on the system.");
2999 }
3000 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08003001
3002 private static void debug(String message) {
3003 Log.d(LOG_TAG, message +
3004 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
3005 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07003006}