blob: b8599155036d975a5346efb949c4475603c509da [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 Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070020import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070025import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080037import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080042import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010043import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070044import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070045import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070046import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070047import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040048import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070049import android.os.ShellCommand;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070050import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070051import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070052import android.os.UserManagerInternal;
Makoto Onukid45a4a22015-11-02 17:17:38 -080053import android.os.UserManagerInternal.UserRestrictionsListener;
Paul Crowley85e4e812015-05-19 12:42:00 +010054import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070055import android.os.storage.VolumeInfo;
56import android.system.ErrnoException;
57import android.system.Os;
58import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070059import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070060import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import android.util.Slog;
62import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080063import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070064import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import android.util.Xml;
66
Makoto Onuki068c54a2015-10-13 14:34:03 -070067import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070068import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040069import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080070import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070071import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070072import com.android.internal.util.XmlUtils;
Clara Bayarri10ad84a2015-12-01 17:38:05 +000073import com.android.internal.widget.LockPatternUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070074import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080075
76import org.xmlpull.v1.XmlPullParser;
77import org.xmlpull.v1.XmlPullParserException;
78import org.xmlpull.v1.XmlSerializer;
79
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.io.BufferedOutputStream;
81import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070082import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.io.FileOutputStream;
86import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010088import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import java.util.ArrayList;
90import java.util.List;
91
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import libcore.io.IoUtils;
93
Makoto Onuki068c54a2015-10-13 14:34:03 -070094/**
95 * Service for {@link UserManager}.
96 *
97 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070098 * <ul>
Fyodor Kupolove80085d2015-11-06 18:21:39 -080099 * <li> Methods suffixed with "LP" should be called within the {@link #mPackagesLock} lock.
Fyodor Kupolov82402752015-10-28 14:54:51 -0700100 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
101 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
102 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700103 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700104public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700105 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800106 static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
107 private static final boolean DBG_WITH_STACKTRACE = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700108
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700113 private static final String ATTR_CREATION_TIME = "created";
114 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700115 private static final String ATTR_SERIAL_NO = "serialNumber";
116 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700117 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700118 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700119 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100120 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700121 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530122 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700123 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700124 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800125 private static final String TAG_RESTRICTIONS = "restrictions";
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800126 private static final String TAG_DEVICE_POLICY_RESTRICTIONS = "device_policy_restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String TAG_ENTRY = "entry";
128 private static final String TAG_VALUE = "value";
129 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700130 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800131 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700133 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
134 private static final String ATTR_TYPE_STRING = "s";
135 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700136 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700137 private static final String ATTR_TYPE_BUNDLE = "B";
138 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700139
Amith Yamasani0b285492011-04-14 17:35:23 -0700140 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700142 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100143 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800145 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700146 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800147
Amith Yamasani634cf312012-10-04 17:34:21 -0700148 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700149 // We need to keep process uid within Integer.MAX_VALUE.
150 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700151
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700152 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700153
Amith Yamasani920ace02012-09-20 22:15:37 -0700154 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
155
Nicolas Prevotb8186812015-08-06 15:00:03 +0100156 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700157 // without first making sure that the rest of the framework is prepared for it.
158 private static final int MAX_MANAGED_PROFILES = 1;
159
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800160 static final int WRITE_USER_MSG = 1;
161 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530162
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700163 private static final String XATTR_SERIAL = "user.serial";
164
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165 private final Context mContext;
166 private final PackageManagerService mPm;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700167 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700168 // Short-term lock for internal state, when interaction/sync with PM is not required
169 private final Object mUsersLock = new Object();
170 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800172 private final Handler mHandler;
173
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700174 private final File mUsersDir;
175 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176
Fyodor Kupolov82402752015-10-28 14:54:51 -0700177 @GuardedBy("mUsersLock")
178 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700179
180 /**
181 * User restrictions set via UserManager. This doesn't include restrictions set by
182 * device owner / profile owners.
183 *
184 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
185 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
186 * maybe shared between {@link #mBaseUserRestrictions} and
187 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
188 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700189 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700190 */
191 @GuardedBy("mRestrictionsLock")
192 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
193
194 /**
195 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
196 * with device / profile owner restrictions. We'll initialize it lazily; use
197 * {@link #getEffectiveUserRestrictions} to access it.
198 *
199 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
200 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
201 * maybe shared between {@link #mBaseUserRestrictions} and
202 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
203 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700204 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700205 */
206 @GuardedBy("mRestrictionsLock")
207 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
208
Makoto Onuki4f160732015-10-27 17:15:38 -0700209 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800210 * User restrictions that have already been applied in
211 * {@link #updateUserRestrictionsInternalLR(Bundle, int)}. We use it to detect restrictions
212 * that have changed since the last
213 * {@link #updateUserRestrictionsInternalLR(Bundle, int)} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700214 */
215 @GuardedBy("mRestrictionsLock")
216 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
217
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800218 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800219 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
220 * that should be applied to all users, including guests.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800221 */
222 @GuardedBy("mRestrictionsLock")
223 private Bundle mDevicePolicyGlobalUserRestrictions;
224
225 /**
Makoto Onukie7927da2015-11-25 10:05:17 -0800226 * User restrictions set by {@link com.android.server.devicepolicy.DevicePolicyManagerService}
227 * for each user.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800228 */
229 @GuardedBy("mRestrictionsLock")
230 private final SparseArray<Bundle> mDevicePolicyLocalUserRestrictions = new SparseArray<>();
231
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800232 @GuardedBy("mGuestRestrictions")
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530233 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800234
235 /**
236 * Set of user IDs being actively removed. Removed IDs linger in this set
237 * for several seconds to work around a VFS caching issue.
238 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700239 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800240 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700241
Fyodor Kupolov82402752015-10-28 14:54:51 -0700242 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700243 private int[] mUserIds;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800244 @GuardedBy("mPackagesLock")
Amith Yamasani2a003292012-08-14 18:25:45 -0700245 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700246 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700247
Jason Monk62062992014-05-06 09:55:28 -0400248 private IAppOpsService mAppOpsService;
249
Makoto Onuki068c54a2015-10-13 14:34:03 -0700250 private final LocalService mLocalService;
251
Makoto Onukie7927da2015-11-25 10:05:17 -0800252 @GuardedBy("mUsersLock")
253 private boolean mIsDeviceManaged;
254
255 @GuardedBy("mUsersLock")
256 private final SparseBooleanArray mIsUserManaged = new SparseBooleanArray();
257
Makoto Onukid45a4a22015-11-02 17:17:38 -0800258 @GuardedBy("mUserRestrictionsListeners")
259 private final ArrayList<UserRestrictionsListener> mUserRestrictionsListeners =
260 new ArrayList<>();
261
Amith Yamasani258848d2012-08-10 17:06:33 -0700262 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700263
Dianne Hackborn4428e172012-08-24 17:43:05 -0700264 public static UserManagerService getInstance() {
265 synchronized (UserManagerService.class) {
266 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700268 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700269
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800270 @VisibleForTesting
271 UserManagerService(File dataDir) {
272 this(null, null, new Object(), dataDir);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700273 }
274
Dianne Hackborn4428e172012-08-24 17:43:05 -0700275 /**
276 * Called by package manager to create the service. This is closely
277 * associated with the package manager, and the given lock is the
278 * package manager's own lock.
279 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800280 UserManagerService(Context context, PackageManagerService pm, Object packagesLock) {
281 this(context, pm, packagesLock, Environment.getDataDirectory());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700282 }
283
Dianne Hackborn4428e172012-08-24 17:43:05 -0700284 private UserManagerService(Context context, PackageManagerService pm,
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800285 Object packagesLock, File dataDir) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700286 mContext = context;
287 mPm = pm;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700288 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800289 mHandler = new MainHandler();
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800290 synchronized (mPackagesLock) {
291 mUsersDir = new File(dataDir, USER_INFO_DIR);
292 mUsersDir.mkdirs();
293 // Make zeroth user directory, for services to migrate their files to that location
294 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
295 userZeroDir.mkdirs();
296 FileUtils.setPermissions(mUsersDir.toString(),
297 FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IROTH | FileUtils.S_IXOTH,
298 -1, -1);
299 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
300 initDefaultGuestRestrictions();
301 readUserListLP();
302 sInstance = this;
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700303 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700304 mLocalService = new LocalService();
305 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700306 }
307
308 void systemReady() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800309 // Prune out any partially created/partially removed users.
310 ArrayList<UserInfo> partials = new ArrayList<>();
311 synchronized (mUsersLock) {
312 final int userSize = mUsers.size();
313 for (int i = 0; i < userSize; i++) {
314 UserInfo ui = mUsers.valueAt(i);
315 if ((ui.partial || ui.guestToRemove) && i != 0) {
316 partials.add(ui);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700317 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700318 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700319 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800320 final int partialsSize = partials.size();
321 for (int i = 0; i < partialsSize; i++) {
322 UserInfo ui = partials.get(i);
323 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
324 + " (name=" + ui.name + ")");
325 removeUserState(ui.id);
326 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800327
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700328 onUserForeground(UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800329
Jason Monk62062992014-05-06 09:55:28 -0400330 mAppOpsService = IAppOpsService.Stub.asInterface(
331 ServiceManager.getService(Context.APP_OPS_SERVICE));
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800332
333 synchronized (mRestrictionsLock) {
334 applyUserRestrictionsLR(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400335 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700336 }
337
338 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700339 public UserInfo getPrimaryUser() {
340 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700341 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700342 final int userSize = mUsers.size();
343 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700344 UserInfo ui = mUsers.valueAt(i);
Xiaohui Chend3e9e182015-11-18 13:37:32 -0800345 if (ui.isPrimary() && !mRemovingUserIds.get(ui.id)) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700346 return ui;
347 }
348 }
349 }
350 return null;
351 }
352
353 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700354 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700355 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700356 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700357 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700358 final int userSize = mUsers.size();
359 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700360 UserInfo ui = mUsers.valueAt(i);
361 if (ui.partial) {
362 continue;
363 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800364 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700365 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700366 }
Amith Yamasani13593602012-03-22 16:16:17 -0700367 }
368 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700369 }
Amith Yamasani13593602012-03-22 16:16:17 -0700370 }
371
Amith Yamasani258848d2012-08-10 17:06:33 -0700372 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100373 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800374 if (userId != UserHandle.getCallingUserId()) {
375 checkManageUsersPermission("getting profiles related to user " + userId);
376 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700377 final long ident = Binder.clearCallingIdentity();
378 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700379 synchronized (mUsersLock) {
380 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100381 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700382 } finally {
383 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000384 }
385 }
386
Amith Yamasanibe465322014-04-24 13:45:17 -0700387 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700388 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
389 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700390 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700391 if (user == null) {
392 // Probably a dying user
393 return users;
394 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700395 final int userSize = mUsers.size();
396 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700397 UserInfo profile = mUsers.valueAt(i);
398 if (!isProfileOf(user, profile)) {
399 continue;
400 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100401 if (enabledOnly && !profile.isEnabled()) {
402 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700403 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700404 if (mRemovingUserIds.get(profile.id)) {
405 continue;
406 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700407 users.add(profile);
408 }
409 return users;
410 }
411
Jessica Hummelbe81c802014-04-22 15:49:22 +0100412 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700413 public int getCredentialOwnerProfile(int userHandle) {
414 checkManageUsersPermission("get the credential owner");
Clara Bayarri10ad84a2015-12-01 17:38:05 +0000415 if (!LockPatternUtils.isSeparateWorkChallengeEnabled()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700416 synchronized (mUsersLock) {
417 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700418 if (profileParent != null) {
419 return profileParent.id;
420 }
421 }
422 }
423
424 return userHandle;
425 }
426
427 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700428 public boolean isSameProfileGroup(int userId, int otherUserId) {
429 if (userId == otherUserId) return true;
430 checkManageUsersPermission("check if in the same profile group");
431 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700432 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700433 }
434 }
435
Fyodor Kupolov82402752015-10-28 14:54:51 -0700436 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
437 synchronized (mUsersLock) {
438 UserInfo userInfo = getUserInfoLU(userId);
439 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
440 return false;
441 }
442 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
443 if (otherUserInfo == null
444 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
445 return false;
446 }
447 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700448 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700449 }
450
451 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100452 public UserInfo getProfileParent(int userHandle) {
453 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700454 synchronized (mUsersLock) {
455 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700456 }
457 }
458
Fyodor Kupolov82402752015-10-28 14:54:51 -0700459 private UserInfo getProfileParentLU(int userHandle) {
460 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700461 if (profile == null) {
462 return null;
463 }
464 int parentUserId = profile.profileGroupId;
465 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
466 return null;
467 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700468 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100469 }
470 }
471
Fyodor Kupolov82402752015-10-28 14:54:51 -0700472 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100473 return user.id == profile.id ||
474 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
475 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000476 }
477
478 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100479 public void setUserEnabled(int userId) {
480 checkManageUsersPermission("enable user");
481 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700482 UserInfo info;
483 synchronized (mUsersLock) {
484 info = getUserInfoLU(userId);
485 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100486 if (info != null && !info.isEnabled()) {
487 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700488 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100489 }
490 }
491 }
492
493 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700494 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700495 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700496 synchronized (mUsersLock) {
497 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700498 }
499 }
500
Amith Yamasani71e6c692013-03-24 17:39:28 -0700501 @Override
502 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700503 synchronized (mUsersLock) {
504 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700505 }
506 }
507
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700508 @Override
509 public boolean canHaveRestrictedProfile(int userId) {
510 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700511 synchronized (mUsersLock) {
512 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700513 if (userInfo == null || !userInfo.canHaveProfile()) {
514 return false;
515 }
516 if (!userInfo.isAdmin()) {
517 return false;
518 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800519 // restricted profile can be created if there is no DO set and the admin user has no PO;
520 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700521 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700522 }
523
Amith Yamasani195263742012-08-21 15:40:12 -0700524 /*
525 * Should be locked on mUsers before calling this.
526 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700527 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700528 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700529 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800530 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700531 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
532 return null;
533 }
534 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700535 }
536
Fyodor Kupolov82402752015-10-28 14:54:51 -0700537 /**
538 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
539 * <p>No permissions checking or any addition checks are made</p>
540 */
541 private UserInfo getUserInfoNoChecks(int userId) {
542 synchronized (mUsersLock) {
543 return mUsers.get(userId);
544 }
545 }
546
Amith Yamasani236b2b52015-08-18 14:32:14 -0700547 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700548 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700549 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700550 }
551
Amith Yamasani258848d2012-08-10 17:06:33 -0700552 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700553 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700554 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700555 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700556 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700557 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700558 if (info == null || info.partial) {
559 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
560 return;
561 }
Amith Yamasani13593602012-03-22 16:16:17 -0700562 if (name != null && !name.equals(info.name)) {
563 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700564 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700565 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700566 }
567 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700568 if (changed) {
569 sendUserInfoChangedBroadcast(userId);
570 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700571 }
572
Amith Yamasani258848d2012-08-10 17:06:33 -0700573 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700574 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700575 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400576 long ident = Binder.clearCallingIdentity();
577 try {
578 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700579 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400580 if (info == null || info.partial) {
581 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
582 return;
583 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700584 writeBitmapLP(info, bitmap);
585 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700586 }
Jason Monk9a944532014-07-08 09:31:21 -0400587 sendUserInfoChangedBroadcast(userId);
588 } finally {
589 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700590 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700591 }
592
593 private void sendUserInfoChangedBroadcast(int userId) {
594 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
595 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
596 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700597 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700598 }
599
Amith Yamasani258848d2012-08-10 17:06:33 -0700600 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100601 public ParcelFileDescriptor getUserIcon(int userId) {
602 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700603 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700604 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700605 if (info == null || info.partial) {
606 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
607 return null;
608 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700609 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100610 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
611 || callingGroupId != info.profileGroupId) {
612 checkManageUsersPermission("get the icon of a user who is not related");
613 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700614 if (info.iconPath == null) {
615 return null;
616 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100617 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700618 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100619
620 try {
621 return ParcelFileDescriptor.open(
622 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
623 } catch (FileNotFoundException e) {
624 Log.e(LOG_TAG, "Couldn't find icon file", e);
625 }
626 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700627 }
628
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700629 public void makeInitialized(int userId) {
630 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800631 boolean scheduleWriteUser = false;
632 UserInfo info;
633 synchronized (mUsersLock) {
634 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700635 if (info == null || info.partial) {
636 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800637 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700638 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800639 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700640 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800641 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700642 }
643 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800644 if (scheduleWriteUser) {
645 scheduleWriteUser(info);
646 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700647 }
648
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700649 /**
650 * If default guest restrictions haven't been initialized yet, add the basic
651 * restrictions.
652 */
653 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800654 synchronized (mGuestRestrictions) {
655 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800656 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800657 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
658 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
659 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700660 }
661 }
662
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800663 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530664 public Bundle getDefaultGuestRestrictions() {
665 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800666 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530667 return new Bundle(mGuestRestrictions);
668 }
669 }
670
671 @Override
672 public void setDefaultGuestRestrictions(Bundle restrictions) {
673 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800674 synchronized (mGuestRestrictions) {
675 mGuestRestrictions.clear();
676 mGuestRestrictions.putAll(restrictions);
677 }
678 synchronized (mPackagesLock) {
679 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530680 }
681 }
682
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800683 /**
684 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
685 */
686 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
687 @Nullable Bundle global) {
688 Preconditions.checkNotNull(local);
689 boolean globalChanged = false;
690 boolean localChanged;
691 synchronized (mRestrictionsLock) {
692 if (global != null) {
693 // Update global.
694 globalChanged = !UserRestrictionsUtils.areEqual(
695 mDevicePolicyGlobalUserRestrictions, global);
696 if (globalChanged) {
697 mDevicePolicyGlobalUserRestrictions = global;
698 }
699 }
700 {
701 // Update local.
702 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
703 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
704 if (localChanged) {
705 mDevicePolicyLocalUserRestrictions.put(userId, local);
706 }
707 }
708 }
709 if (DBG) {
710 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
711 + " global=" + global + (globalChanged ? " (changed)" : "")
712 + " local=" + local + (localChanged ? " (changed)" : "")
713 );
714 }
715 // Don't call them within the mRestrictionsLock.
716 synchronized (mPackagesLock) {
717 if (globalChanged) {
718 writeUserListLP();
719 }
720 if (localChanged) {
721 writeUserLP(getUserInfoNoChecks(userId));
722 }
723 }
724
725 synchronized (mRestrictionsLock) {
726 if (globalChanged) {
727 applyUserRestrictionsForAllUsersLR();
728 } else if (localChanged) {
729 applyUserRestrictionsLR(userId);
730 }
731 }
732 }
733
Makoto Onuki068c54a2015-10-13 14:34:03 -0700734 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700735 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800736 final Bundle baseRestrictions =
737 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
738 final Bundle global = mDevicePolicyGlobalUserRestrictions;
739 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700740
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800741 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
742 // Common case first.
743 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700744 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800745 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
746 UserRestrictionsUtils.merge(effective, global);
747 UserRestrictionsUtils.merge(effective, local);
748
Makoto Onuki068c54a2015-10-13 14:34:03 -0700749 return effective;
750 }
751
752 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700753 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700754 if (DBG) {
755 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
756 }
757 mCachedEffectiveUserRestrictions.remove(userId);
758 }
759
760 private Bundle getEffectiveUserRestrictions(int userId) {
761 synchronized (mRestrictionsLock) {
762 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
763 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700764 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700765 mCachedEffectiveUserRestrictions.put(userId, restrictions);
766 }
767 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700768 }
769 }
770
Makoto Onuki068c54a2015-10-13 14:34:03 -0700771 /** @return a specific user restriction that's in effect currently. */
772 @Override
773 public boolean hasUserRestriction(String restrictionKey, int userId) {
774 Bundle restrictions = getEffectiveUserRestrictions(userId);
775 return restrictions != null && restrictions.getBoolean(restrictionKey);
776 }
777
778 /**
779 * @return UserRestrictions that are in effect currently. This always returns a new
780 * {@link Bundle}.
781 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700782 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800783 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800784 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800785 }
786
787 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700788 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700789 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700790 synchronized (mRestrictionsLock) {
791 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
792 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800793 final Bundle newRestrictions = UserRestrictionsUtils.clone(
794 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700795 newRestrictions.putBoolean(key, value);
796
Fyodor Kupolov82402752015-10-28 14:54:51 -0700797 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700798 }
799 }
800
Makoto Onuki068c54a2015-10-13 14:34:03 -0700801 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800802 * Optionally updating user restrictions, calculate the effective user restrictions and also
803 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700804 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800805 * @param newRestrictions User restrictions to set.
806 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700807 * @param userId target user ID.
808 */
809 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700810 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700811 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800812
813 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
814 mAppliedUserRestrictions.get(userId));
815
816 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700817 if (newRestrictions != null) {
818 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800819 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
820
821 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700822 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
823 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800824
825 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
826 mBaseUserRestrictions.put(userId, newRestrictions);
827 scheduleWriteUser(getUserInfoNoChecks(userId));
828 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700829 }
830
Fyodor Kupolov82402752015-10-28 14:54:51 -0700831 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700832
Makoto Onuki759a7632015-10-28 16:43:10 -0700833 mCachedEffectiveUserRestrictions.put(userId, effective);
834
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800835 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700836 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800837 debug("Applying user restrictions: userId=" + userId
838 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700839 }
840
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800841 if (mAppOpsService != null) { // We skip it until system-ready.
842 final long token = Binder.clearCallingIdentity();
843 try {
844 mAppOpsService.setUserRestrictions(effective, userId);
845 } catch (RemoteException e) {
846 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
847 } finally {
848 Binder.restoreCallingIdentity(token);
849 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700850 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700851
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800852 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700853
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800854 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700855 }
856
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800857 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800858 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800859 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
860 // actually, but we still need some kind of synchronization otherwise we might end up
861 // calling listeners out-of-order, thus "LR".
862
863 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
864 return;
865 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800866
867 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
868 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
869
870 mHandler.post(new Runnable() {
871 @Override
872 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700873 UserRestrictionsUtils.applyUserRestrictions(
874 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800875
Makoto Onukid45a4a22015-11-02 17:17:38 -0800876 final UserRestrictionsListener[] listeners;
877 synchronized (mUserRestrictionsListeners) {
878 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
879 mUserRestrictionsListeners.toArray(listeners);
880 }
881 for (int i = 0; i < listeners.length; i++) {
882 listeners[i].onUserRestrictionsChanged(userId,
883 newRestrictionsFinal, prevRestrictionsFinal);
884 }
885 }
886 });
887 }
888
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800889 // Package private for the inner class.
890 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700891 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700892 }
893
894 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800895 // Package private for the inner class.
896 void applyUserRestrictionsForAllUsersLR() {
897 if (DBG) {
898 debug("applyUserRestrictionsForAllUsersLR");
899 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700900 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700901 mCachedEffectiveUserRestrictions.clear();
902
Makoto Onuki068c54a2015-10-13 14:34:03 -0700903 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
904 // it on a handler.
905 final Runnable r = new Runnable() {
906 @Override
907 public void run() {
908 // Then get the list of running users.
909 final int[] runningUsers;
910 try {
911 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
912 } catch (RemoteException e) {
913 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
914 return;
915 }
916 // Then re-calculate the effective restrictions and apply, only for running users.
917 // It's okay if a new user has started after the getRunningUserIds() call,
918 // because we'll do the same thing (re-calculate the restrictions and apply)
919 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700920 synchronized (mRestrictionsLock) {
921 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800922 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700923 }
924 }
925 }
926 };
927 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700928 }
929
Amith Yamasani258848d2012-08-10 17:06:33 -0700930 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700931 * Check if we've hit the limit of how many users can be created.
932 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700933 private boolean isUserLimitReached() {
934 int count;
935 synchronized (mUsersLock) {
936 count = getAliveUsersExcludingGuestsCountLU();
937 }
938 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700939 }
940
941 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000942 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700943 checkManageUsersPermission("check if more managed profiles can be added.");
944 if (ActivityManager.isLowRamDeviceStatic()) {
945 return false;
946 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700947 if (!mContext.getPackageManager().hasSystemFeature(
948 PackageManager.FEATURE_MANAGED_USERS)) {
949 return false;
950 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100951 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000952 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
953 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
954 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100955 return false;
956 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700957 synchronized(mUsersLock) {
958 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100959 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700960 return false;
961 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000962 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
963 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -0700964 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +0000965 return usersCountAfterRemoving == 1
966 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700967 }
968 }
969
Fyodor Kupolov82402752015-10-28 14:54:51 -0700970 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700971 int aliveUserCount = 0;
972 final int totalUserCount = mUsers.size();
973 // Skip over users being removed
974 for (int i = 0; i < totalUserCount; i++) {
975 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700976 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700977 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700978 aliveUserCount++;
979 }
980 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700981 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700982 }
983
984 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700985 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700986 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700987 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700988 *
989 * @param message used as message if SecurityException is thrown
990 * @throws SecurityException if the caller is not system or root
991 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700992 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700993 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700994 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400995 && ActivityManager.checkComponentPermission(
996 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700997 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
998 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
999 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001000 }
1001
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001002 private static void checkSystemOrRoot(String message) {
1003 final int uid = Binder.getCallingUid();
1004 if (uid != Process.SYSTEM_UID && uid != 0) {
1005 throw new SecurityException("Only system may call: " + message);
1006 }
1007 }
1008
Fyodor Kupolov82402752015-10-28 14:54:51 -07001009 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001010 try {
1011 File dir = new File(mUsersDir, Integer.toString(info.id));
1012 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001013 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001014 if (!dir.exists()) {
1015 dir.mkdir();
1016 FileUtils.setPermissions(
1017 dir.getPath(),
1018 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1019 -1, -1);
1020 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001021 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001022 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1023 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001024 info.iconPath = file.getAbsolutePath();
1025 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001026 try {
1027 os.close();
1028 } catch (IOException ioe) {
1029 // What the ... !
1030 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001031 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001032 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001033 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001034 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001035 }
1036
Amith Yamasani0b285492011-04-14 17:35:23 -07001037 /**
1038 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1039 * cache it elsewhere.
1040 * @return the array of user ids.
1041 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001042 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001043 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001044 return mUserIds;
1045 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001046 }
1047
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001048 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001049 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001050 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001051 return;
1052 }
1053 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001054 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001055 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001056 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001057 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001058 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001059 int type;
1060 while ((type = parser.next()) != XmlPullParser.START_TAG
1061 && type != XmlPullParser.END_DOCUMENT) {
1062 ;
1063 }
1064
1065 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001066 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001067 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001068 return;
1069 }
1070
Amith Yamasani2a003292012-08-14 18:25:45 -07001071 mNextSerialNumber = -1;
1072 if (parser.getName().equals(TAG_USERS)) {
1073 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1074 if (lastSerialNumber != null) {
1075 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1076 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001077 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1078 if (versionNumber != null) {
1079 mUserVersion = Integer.parseInt(versionNumber);
1080 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001081 }
1082
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001083 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1084
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001085 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301086 if (type == XmlPullParser.START_TAG) {
1087 final String name = parser.getName();
1088 if (name.equals(TAG_USER)) {
1089 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001090 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001091
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301092 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001093 synchronized (mUsersLock) {
1094 mUsers.put(user.id, user);
1095 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1096 mNextSerialNumber = user.id + 1;
1097 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301098 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001099 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301100 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001101 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1102 && type != XmlPullParser.END_TAG) {
1103 if (type == XmlPullParser.START_TAG) {
1104 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001105 synchronized (mGuestRestrictions) {
1106 UserRestrictionsUtils
1107 .readRestrictions(parser, mGuestRestrictions);
1108 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001109 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1110 ) {
1111 UserRestrictionsUtils.readRestrictions(parser,
1112 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001113 }
1114 break;
1115 }
1116 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001117 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001118 }
1119 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001120 synchronized (mRestrictionsLock) {
1121 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1122 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001123 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001124 upgradeIfNecessaryLP();
1125 } catch (IOException | XmlPullParserException e) {
1126 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001127 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001128 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001129 }
1130 }
1131
Amith Yamasani6f34b412012-10-22 18:19:27 -07001132 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001133 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001134 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001135 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001136 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001137 int userVersion = mUserVersion;
1138 if (userVersion < 1) {
1139 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001140 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001141 if ("Primary".equals(user.name)) {
1142 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001143 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001144 }
1145 userVersion = 1;
1146 }
1147
Amith Yamasanibc9625052012-11-15 14:39:18 -08001148 if (userVersion < 2) {
1149 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001150 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001151 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1152 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001153 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001154 }
1155 userVersion = 2;
1156 }
1157
Amith Yamasani350962c2013-08-06 11:18:53 -07001158
Amith Yamasani5e486f52013-08-07 11:06:44 -07001159 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001160 userVersion = 4;
1161 }
1162
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001163 if (userVersion < 5) {
1164 initDefaultGuestRestrictions();
1165 userVersion = 5;
1166 }
1167
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001168 if (userVersion < 6) {
1169 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001170 synchronized (mUsersLock) {
1171 for (int i = 0; i < mUsers.size(); i++) {
1172 UserInfo user = mUsers.valueAt(i);
1173 // In non-split mode, only user 0 can have restricted profiles
1174 if (!splitSystemUser && user.isRestricted()
1175 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1176 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001177 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001178 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001179 }
1180 }
1181 userVersion = 6;
1182 }
1183
Amith Yamasani6f34b412012-10-22 18:19:27 -07001184 if (userVersion < USER_VERSION) {
1185 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1186 + USER_VERSION);
1187 } else {
1188 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001189
1190 if (originalVersion < mUserVersion) {
1191 writeUserListLP();
1192 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001193 }
1194 }
1195
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001196 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001197 int flags = UserInfo.FLAG_INITIALIZED;
1198 // In split system user mode, the admin and primary flags are assigned to the first human
1199 // user.
1200 if (!UserManager.isSplitSystemUser()) {
1201 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1202 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001203 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001204 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001205 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001206 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001207 synchronized (mUsersLock) {
1208 mUsers.put(system.id, system);
1209 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001210 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001211 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001212
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001213 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001214 synchronized (mRestrictionsLock) {
1215 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1216 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001217
Fyodor Kupolov82402752015-10-28 14:54:51 -07001218 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001219 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001220
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001221 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001222 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001223 }
1224
Makoto Onuki9e935a32015-11-06 14:24:24 -08001225 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001226 if (DBG) {
1227 debug("scheduleWriteUser");
1228 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001229 // No need to wrap it within a lock -- worst case, we'll just post the same message
1230 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001231 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1232 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1233 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1234 }
1235 }
1236
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001237 /*
1238 * Writes the user file in this format:
1239 *
1240 * <user flags="20039023" id="0">
1241 * <name>Primary</name>
1242 * </user>
1243 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001244 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001245 if (DBG) {
1246 debug("writeUserLP " + userInfo);
1247 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001248 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001249 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001250 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001251 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001252 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1253
1254 // XmlSerializer serializer = XmlUtils.serializerInstance();
1255 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001256 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001257 serializer.startDocument(null, true);
1258 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1259
1260 serializer.startTag(null, TAG_USER);
1261 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001262 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001263 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001264 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1265 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1266 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001267 if (userInfo.iconPath != null) {
1268 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1269 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001270 if (userInfo.partial) {
1271 serializer.attribute(null, ATTR_PARTIAL, "true");
1272 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001273 if (userInfo.guestToRemove) {
1274 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1275 }
Kenny Guy2a764942014-04-02 13:29:20 +01001276 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1277 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1278 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001279 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001280 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1281 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1282 Integer.toString(userInfo.restrictedProfileParentId));
1283 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001284 serializer.startTag(null, TAG_NAME);
1285 serializer.text(userInfo.name);
1286 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001287 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001288 UserRestrictionsUtils.writeRestrictions(serializer,
1289 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1290 UserRestrictionsUtils.writeRestrictions(serializer,
1291 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1292 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001293 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001294 serializer.endTag(null, TAG_USER);
1295
1296 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001297 userFile.finishWrite(fos);
1298 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001299 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001300 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001301 }
1302 }
1303
1304 /*
1305 * Writes the user list file in this format:
1306 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001307 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001308 * <user id="0"></user>
1309 * <user id="2"></user>
1310 * </users>
1311 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001312 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001313 if (DBG) {
1314 debug("writeUserList");
1315 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001316 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001317 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001318 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001319 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001320 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1321
1322 // XmlSerializer serializer = XmlUtils.serializerInstance();
1323 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001324 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001325 serializer.startDocument(null, true);
1326 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1327
1328 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001329 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001330 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001331
Adam Lesinskieddeb492014-09-08 17:50:03 -07001332 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001333 synchronized (mGuestRestrictions) {
1334 UserRestrictionsUtils
1335 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1336 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301337 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001338 synchronized (mRestrictionsLock) {
1339 UserRestrictionsUtils.writeRestrictions(serializer,
1340 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1341 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001342 int[] userIdsToWrite;
1343 synchronized (mUsersLock) {
1344 userIdsToWrite = new int[mUsers.size()];
1345 for (int i = 0; i < userIdsToWrite.length; i++) {
1346 UserInfo user = mUsers.valueAt(i);
1347 userIdsToWrite[i] = user.id;
1348 }
1349 }
1350 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001351 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001352 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001353 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001354 }
1355
1356 serializer.endTag(null, TAG_USERS);
1357
1358 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001359 userListFile.finishWrite(fos);
1360 } catch (Exception e) {
1361 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001362 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001363 }
1364 }
1365
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001366 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001367 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001368 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001369 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001370 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001371 long creationTime = 0L;
1372 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001373 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001374 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001375 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001376 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001377 Bundle baseRestrictions = new Bundle();
1378 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001379
1380 FileInputStream fis = null;
1381 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001382 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001383 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001384 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001385 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001386 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001387 int type;
1388 while ((type = parser.next()) != XmlPullParser.START_TAG
1389 && type != XmlPullParser.END_DOCUMENT) {
1390 ;
1391 }
1392
1393 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001394 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001395 return null;
1396 }
1397
1398 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001399 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1400 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001401 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001402 return null;
1403 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001404 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1405 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001406 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001407 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1408 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001409 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1410 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001411 restrictedProfileParentId = readIntAttribute(parser,
1412 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001413 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1414 if ("true".equals(valueString)) {
1415 partial = true;
1416 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001417 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1418 if ("true".equals(valueString)) {
1419 guestToRemove = true;
1420 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001421
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001422 int outerDepth = parser.getDepth();
1423 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1424 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1425 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1426 continue;
1427 }
1428 String tag = parser.getName();
1429 if (TAG_NAME.equals(tag)) {
1430 type = parser.next();
1431 if (type == XmlPullParser.TEXT) {
1432 name = parser.getText();
1433 }
1434 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001435 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1436 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1437 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001438 }
1439 }
1440 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001441
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001442 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001443 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001444 userInfo.creationTime = creationTime;
1445 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001446 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001447 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001448 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001449 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001450 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001451 mBaseUserRestrictions.put(id, baseRestrictions);
1452 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001453 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001454 return userInfo;
1455
1456 } catch (IOException ioe) {
1457 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001458 } finally {
1459 if (fis != null) {
1460 try {
1461 fis.close();
1462 } catch (IOException e) {
1463 }
1464 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001465 }
1466 return null;
1467 }
1468
Amith Yamasani920ace02012-09-20 22:15:37 -07001469 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1470 String valueString = parser.getAttributeValue(null, attr);
1471 if (valueString == null) return defaultValue;
1472 try {
1473 return Integer.parseInt(valueString);
1474 } catch (NumberFormatException nfe) {
1475 return defaultValue;
1476 }
1477 }
1478
1479 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1480 String valueString = parser.getAttributeValue(null, attr);
1481 if (valueString == null) return defaultValue;
1482 try {
1483 return Long.parseLong(valueString);
1484 } catch (NumberFormatException nfe) {
1485 return defaultValue;
1486 }
1487 }
1488
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001489 private boolean isPackageInstalled(String pkg, int userId) {
1490 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1491 PackageManager.GET_UNINSTALLED_PACKAGES,
1492 userId);
1493 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1494 return false;
1495 }
1496 return true;
1497 }
1498
Amith Yamasanib82add22013-07-09 11:24:44 -07001499 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001500 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001501 * Does not do any permissions checking.
1502 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001503 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001504 synchronized (mPackagesLock) {
1505 File dir = Environment.getUserSystemDirectory(userId);
1506 String[] files = dir.list();
1507 if (files == null) return;
1508 for (String fileName : files) {
1509 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1510 File resFile = new File(dir, fileName);
1511 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001512 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001513 }
1514 }
1515 }
1516 }
1517 }
1518
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001519 /**
1520 * Removes the app restrictions file for a specific package and user id, if it exists.
1521 */
1522 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1523 synchronized (mPackagesLock) {
1524 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001525 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001526 if (resFile.exists()) {
1527 resFile.delete();
1528 }
1529 }
1530 }
1531
Kenny Guya52dc3e2014-02-11 15:33:14 +00001532 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001533 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001534 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001535 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001536 }
1537
Amith Yamasani258848d2012-08-10 17:06:33 -07001538 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001539 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001540 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001541 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001542 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001543
Jessica Hummelbe81c802014-04-22 15:49:22 +01001544 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001545 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001546 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1547 return null;
1548 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001549 if (ActivityManager.isLowRamDeviceStatic()) {
1550 return null;
1551 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001552 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001553 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001554 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001555 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001556 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001557 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001558 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001559 synchronized (mPackagesLock) {
1560 UserInfo parent = null;
1561 if (parentId != UserHandle.USER_NULL) {
1562 synchronized (mUsersLock) {
1563 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001564 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001565 if (parent == null) return null;
1566 }
1567 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1568 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1569 return null;
1570 }
1571 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1572 // If we're not adding a guest user or a managed profile and the limit has
1573 // been reached, cannot add a user.
1574 return null;
1575 }
1576 // If we're adding a guest and there already exists one, bail.
1577 if (isGuest && findCurrentGuestUser() != null) {
1578 return null;
1579 }
1580 // In legacy mode, restricted profile's parent can only be the owner user
1581 if (isRestricted && !UserManager.isSplitSystemUser()
1582 && (parentId != UserHandle.USER_SYSTEM)) {
1583 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1584 return null;
1585 }
1586 if (isRestricted && UserManager.isSplitSystemUser()) {
1587 if (parent == null) {
1588 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1589 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001590 return null;
1591 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001592 if (!parent.canHaveProfile()) {
1593 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1594 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001595 return null;
1596 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001597 }
1598 // In split system user mode, we assign the first human user the primary flag.
1599 // And if there is no device owner, we also assign the admin flag to primary user.
1600 if (UserManager.isSplitSystemUser()
1601 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1602 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001603 synchronized (mUsersLock) {
1604 if (!mIsDeviceManaged) {
1605 flags |= UserInfo.FLAG_ADMIN;
1606 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001607 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001608 }
1609 userId = getNextAvailableId();
1610 userInfo = new UserInfo(userId, name, null, flags);
1611 userInfo.serialNumber = mNextSerialNumber++;
1612 long now = System.currentTimeMillis();
1613 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1614 userInfo.partial = true;
1615 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1616 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001617 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001618 }
1619 writeUserListLP();
1620 if (parent != null) {
1621 if (isManagedProfile) {
1622 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1623 parent.profileGroupId = parent.id;
1624 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001625 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001626 userInfo.profileGroupId = parent.profileGroupId;
1627 } else if (isRestricted) {
1628 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1629 parent.restrictedProfileParentId = parent.id;
1630 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001631 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001632 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001633 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001634 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001635 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001636 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1637 storage.createUserKey(userId, userInfo.serialNumber);
1638 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1639 final String volumeUuid = vol.getFsUuid();
1640 try {
1641 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1642 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1643 enforceSerialNumber(userDir, userInfo.serialNumber);
1644 } catch (IOException e) {
1645 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1646 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001647 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001648 mPm.createNewUser(userId);
1649 userInfo.partial = false;
1650 synchronized (mPackagesLock) {
1651 writeUserLP(userInfo);
1652 }
1653 updateUserIds();
1654 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001655 if (isGuest) {
1656 synchronized (mGuestRestrictions) {
1657 restrictions.putAll(mGuestRestrictions);
1658 }
1659 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001660 synchronized (mRestrictionsLock) {
1661 mBaseUserRestrictions.append(userId, restrictions);
1662 }
1663 mPm.newUserCreated(userId);
1664 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1665 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1666 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1667 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001668 } finally {
1669 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001670 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001671 return userInfo;
1672 }
1673
Amith Yamasani0b285492011-04-14 17:35:23 -07001674 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001675 * @hide
1676 */
1677 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1678 checkManageUsersPermission("setupRestrictedProfile");
1679 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1680 if (user == null) {
1681 return null;
1682 }
1683 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1684 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1685 // the putIntForUser() will fail.
1686 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1687 android.provider.Settings.Secure.LOCATION_MODE,
1688 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1689 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1690 return user;
1691 }
1692
1693 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001694 * Find the current guest user. If the Guest user is partial,
1695 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001696 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001697 private UserInfo findCurrentGuestUser() {
1698 synchronized (mUsersLock) {
1699 final int size = mUsers.size();
1700 for (int i = 0; i < size; i++) {
1701 final UserInfo user = mUsers.valueAt(i);
1702 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1703 return user;
1704 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001705 }
1706 }
1707 return null;
1708 }
1709
1710 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001711 * Mark this guest user for deletion to allow us to create another guest
1712 * and switch to that user before actually removing this guest.
1713 * @param userHandle the userid of the current guest
1714 * @return whether the user could be marked for deletion
1715 */
1716 public boolean markGuestForDeletion(int userHandle) {
1717 checkManageUsersPermission("Only the system can remove users");
1718 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1719 UserManager.DISALLOW_REMOVE_USER, false)) {
1720 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1721 return false;
1722 }
1723
1724 long ident = Binder.clearCallingIdentity();
1725 try {
1726 final UserInfo user;
1727 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001728 synchronized (mUsersLock) {
1729 user = mUsers.get(userHandle);
1730 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1731 return false;
1732 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001733 }
1734 if (!user.isGuest()) {
1735 return false;
1736 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001737 // We set this to a guest user that is to be removed. This is a temporary state
1738 // where we are allowed to add new Guest users, even if this one is still not
1739 // removed. This user will still show up in getUserInfo() calls.
1740 // If we don't get around to removing this Guest user, it will be purged on next
1741 // startup.
1742 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001743 // Mark it as disabled, so that it isn't returned any more when
1744 // profiles are queried.
1745 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001746 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001747 }
1748 } finally {
1749 Binder.restoreCallingIdentity(ident);
1750 }
1751 return true;
1752 }
1753
1754 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001755 * Removes a user and all data directories created for that user. This method should be called
1756 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001757 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001758 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001759 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001760 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001761 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1762 UserManager.DISALLOW_REMOVE_USER, false)) {
1763 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1764 return false;
1765 }
1766
Kenny Guyee58b4f2014-05-23 15:19:53 +01001767 long ident = Binder.clearCallingIdentity();
1768 try {
1769 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001770 int currentUser = ActivityManager.getCurrentUser();
1771 if (currentUser == userHandle) {
1772 Log.w(LOG_TAG, "Current user cannot be removed");
1773 return false;
1774 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001775 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001776 synchronized (mUsersLock) {
1777 user = mUsers.get(userHandle);
1778 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1779 return false;
1780 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001781
Fyodor Kupolov82402752015-10-28 14:54:51 -07001782 // We remember deleted user IDs to prevent them from being
1783 // reused during the current boot; they can still be reused
1784 // after a reboot.
1785 mRemovingUserIds.put(userHandle, true);
1786 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001787
Kenny Guyee58b4f2014-05-23 15:19:53 +01001788 try {
1789 mAppOpsService.removeUser(userHandle);
1790 } catch (RemoteException e) {
1791 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1792 }
1793 // Set this to a partially created user, so that the user will be purged
1794 // on next startup, in case the runtime stops now before stopping and
1795 // removing the user completely.
1796 user.partial = true;
1797 // Mark it as disabled, so that it isn't returned any more when
1798 // profiles are queried.
1799 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001800 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001801 }
1802
1803 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1804 && user.isManagedProfile()) {
1805 // Send broadcast to notify system that the user removed was a
1806 // managed user.
1807 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1808 }
1809
1810 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1811 int res;
1812 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001813 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
1814 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001815 @Override
1816 public void userStopped(int userId) {
1817 finishRemoveUser(userId);
1818 }
1819 @Override
1820 public void userStopAborted(int userId) {
1821 }
1822 });
1823 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001824 return false;
1825 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001826 return res == ActivityManager.USER_OP_SUCCESS;
1827 } finally {
1828 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001829 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001830 }
1831
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001832 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001833 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001834 // Let other services shutdown any activity and clean up their state before completely
1835 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001836 long ident = Binder.clearCallingIdentity();
1837 try {
1838 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1839 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001840 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1841 android.Manifest.permission.MANAGE_USERS,
1842
1843 new BroadcastReceiver() {
1844 @Override
1845 public void onReceive(Context context, Intent intent) {
1846 if (DBG) {
1847 Slog.i(LOG_TAG,
1848 "USER_REMOVED broadcast sent, cleaning up user data "
1849 + userHandle);
1850 }
1851 new Thread() {
1852 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001853 // Clean up any ActivityManager state
1854 LocalServices.getService(ActivityManagerInternal.class)
1855 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001856 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001857 }
1858 }.start();
1859 }
1860 },
1861
1862 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001863 } finally {
1864 Binder.restoreCallingIdentity(ident);
1865 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001866 }
1867
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001868 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001869 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001870 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001871 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001872
1873 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001874 synchronized (mUsersLock) {
1875 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08001876 mIsUserManaged.delete(userHandle);
1877 }
1878 synchronized (mRestrictionsLock) {
1879 mBaseUserRestrictions.remove(userHandle);
1880 mAppliedUserRestrictions.remove(userHandle);
1881 mCachedEffectiveUserRestrictions.remove(userHandle);
1882 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001883 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001884 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001885 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001886 userFile.delete();
1887 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001888 synchronized (mPackagesLock) {
1889 writeUserListLP();
1890 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001891 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001892 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1893 }
1894
Amith Yamasani61f57372012-08-31 12:12:28 -07001895 private void removeDirectoryRecursive(File parent) {
1896 if (parent.isDirectory()) {
1897 String[] files = parent.list();
1898 for (String filename : files) {
1899 File child = new File(parent, filename);
1900 removeDirectoryRecursive(child);
1901 }
1902 }
1903 parent.delete();
1904 }
1905
Kenny Guyf8d3a232014-05-15 16:09:52 +01001906 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001907 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001908 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1909 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001910 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1911 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001912 }
1913
Amith Yamasani2a003292012-08-14 18:25:45 -07001914 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001915 public Bundle getApplicationRestrictions(String packageName) {
1916 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1917 }
1918
1919 @Override
1920 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001921 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001922 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001923 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001924 }
1925 synchronized (mPackagesLock) {
1926 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001927 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001928 }
1929 }
1930
1931 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001932 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001933 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001934 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001935 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001936 if (restrictions == null || restrictions.isEmpty()) {
1937 cleanAppRestrictionsForPackage(packageName, userId);
1938 } else {
1939 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001940 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001941 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001942 }
Robin Lee66e5d962014-04-09 16:44:21 +01001943
Kenny Guyd21b2182014-07-17 16:38:55 +01001944 if (isPackageInstalled(packageName, userId)) {
1945 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1946 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1947 changeIntent.setPackage(packageName);
1948 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1949 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1950 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001951 }
1952
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001953 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001954 mHandler.post(new Runnable() {
1955 @Override
1956 public void run() {
1957 List<ApplicationInfo> apps =
1958 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1959 userHandle).getList();
1960 final long ident = Binder.clearCallingIdentity();
1961 try {
1962 for (ApplicationInfo appInfo : apps) {
1963 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001964 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1965 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001966 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001967 userHandle);
1968 }
1969 }
1970 } finally {
1971 Binder.restoreCallingIdentity(ident);
1972 }
1973 }
1974 });
1975 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001976 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001977 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001978 try {
1979 return mContext.getPackageManager().getApplicationInfo(packageName,
1980 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1981 } catch (NameNotFoundException nnfe) {
1982 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001983 } finally {
1984 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001985 }
1986 }
1987
Fyodor Kupolov82402752015-10-28 14:54:51 -07001988 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001989 AtomicFile restrictionsFile =
1990 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1991 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001992 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001993 }
1994
1995 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001996 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001997 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001998 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001999 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002000 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002001 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002002
2003 FileInputStream fis = null;
2004 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002005 fis = restrictionsFile.openRead();
2006 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002007 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002008 XmlUtils.nextElement(parser);
2009 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002010 Slog.e(LOG_TAG, "Unable to read restrictions file "
2011 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002012 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002013 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002014 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2015 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002016 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002017 } catch (IOException|XmlPullParserException e) {
2018 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002019 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002020 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002021 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002022 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002023 }
2024
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002025 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2026 XmlPullParser parser) throws XmlPullParserException, IOException {
2027 int type = parser.getEventType();
2028 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2029 String key = parser.getAttributeValue(null, ATTR_KEY);
2030 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2031 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2032 if (multiple != null) {
2033 values.clear();
2034 int count = Integer.parseInt(multiple);
2035 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2036 if (type == XmlPullParser.START_TAG
2037 && parser.getName().equals(TAG_VALUE)) {
2038 values.add(parser.nextText().trim());
2039 count--;
2040 }
2041 }
2042 String [] valueStrings = new String[values.size()];
2043 values.toArray(valueStrings);
2044 restrictions.putStringArray(key, valueStrings);
2045 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2046 restrictions.putBundle(key, readBundleEntry(parser, values));
2047 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2048 final int outerDepth = parser.getDepth();
2049 ArrayList<Bundle> bundleList = new ArrayList<>();
2050 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2051 Bundle childBundle = readBundleEntry(parser, values);
2052 bundleList.add(childBundle);
2053 }
2054 restrictions.putParcelableArray(key,
2055 bundleList.toArray(new Bundle[bundleList.size()]));
2056 } else {
2057 String value = parser.nextText().trim();
2058 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2059 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2060 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2061 restrictions.putInt(key, Integer.parseInt(value));
2062 } else {
2063 restrictions.putString(key, value);
2064 }
2065 }
2066 }
2067 }
2068
2069 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2070 throws IOException, XmlPullParserException {
2071 Bundle childBundle = new Bundle();
2072 final int outerDepth = parser.getDepth();
2073 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2074 readEntry(childBundle, values, parser);
2075 }
2076 return childBundle;
2077 }
2078
Fyodor Kupolov82402752015-10-28 14:54:51 -07002079 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002080 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002081 AtomicFile restrictionsFile = new AtomicFile(
2082 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002083 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002084 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002085 }
2086
2087 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002088 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002089 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002090 try {
2091 fos = restrictionsFile.startWrite();
2092 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2093
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002094 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002095 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002096 serializer.startDocument(null, true);
2097 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2098
2099 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002100 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002101 serializer.endTag(null, TAG_RESTRICTIONS);
2102
2103 serializer.endDocument();
2104 restrictionsFile.finishWrite(fos);
2105 } catch (Exception e) {
2106 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002107 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2108 }
2109 }
2110
2111 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2112 throws IOException {
2113 for (String key : restrictions.keySet()) {
2114 Object value = restrictions.get(key);
2115 serializer.startTag(null, TAG_ENTRY);
2116 serializer.attribute(null, ATTR_KEY, key);
2117
2118 if (value instanceof Boolean) {
2119 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2120 serializer.text(value.toString());
2121 } else if (value instanceof Integer) {
2122 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2123 serializer.text(value.toString());
2124 } else if (value == null || value instanceof String) {
2125 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2126 serializer.text(value != null ? (String) value : "");
2127 } else if (value instanceof Bundle) {
2128 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2129 writeBundle((Bundle) value, serializer);
2130 } else if (value instanceof Parcelable[]) {
2131 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2132 Parcelable[] array = (Parcelable[]) value;
2133 for (Parcelable parcelable : array) {
2134 if (!(parcelable instanceof Bundle)) {
2135 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2136 }
2137 serializer.startTag(null, TAG_ENTRY);
2138 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2139 writeBundle((Bundle) parcelable, serializer);
2140 serializer.endTag(null, TAG_ENTRY);
2141 }
2142 } else {
2143 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2144 String[] values = (String[]) value;
2145 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2146 for (String choice : values) {
2147 serializer.startTag(null, TAG_VALUE);
2148 serializer.text(choice != null ? choice : "");
2149 serializer.endTag(null, TAG_VALUE);
2150 }
2151 }
2152 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002153 }
2154 }
2155
2156 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002157 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002158 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002159 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002160 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002161 }
2162 }
2163
2164 @Override
2165 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002166 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002167 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002168 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002169 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002170 }
2171 // Not found
2172 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002173 }
2174 }
2175
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002176 @Override
2177 public long getUserCreationTime(int userHandle) {
2178 int callingUserId = UserHandle.getCallingUserId();
2179 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002180 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002181 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002182 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002183 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002184 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002185 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002186 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002187 }
2188 }
2189 }
2190 if (userInfo == null) {
2191 throw new SecurityException("userHandle can only be the calling user or a managed "
2192 + "profile associated with this user");
2193 }
2194 return userInfo.creationTime;
2195 }
2196
Amith Yamasani0b285492011-04-14 17:35:23 -07002197 /**
2198 * Caches the list of user ids in an array, adjusting the array size when necessary.
2199 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002200 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002201 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002202 synchronized (mUsersLock) {
2203 final int userSize = mUsers.size();
2204 for (int i = 0; i < userSize; i++) {
2205 if (!mUsers.valueAt(i).partial) {
2206 num++;
2207 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002208 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002209 final int[] newUsers = new int[num];
2210 int n = 0;
2211 for (int i = 0; i < userSize; i++) {
2212 if (!mUsers.valueAt(i).partial) {
2213 newUsers[n++] = mUsers.keyAt(i);
2214 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002215 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002216 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002217 }
2218 }
2219
2220 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002221 * Called right before a user starts. This will not be called for the system user.
2222 */
2223 public void onBeforeStartUser(int userId) {
2224 synchronized (mRestrictionsLock) {
2225 applyUserRestrictionsLR(userId);
2226 }
2227 }
2228
2229 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002230 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002231 * @param userId the user that was just foregrounded
2232 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002233 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002234 UserInfo user = getUserInfoNoChecks(userId);
2235 if (user == null || user.partial) {
2236 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2237 return;
2238 }
2239 long now = System.currentTimeMillis();
2240 if (now > EPOCH_PLUS_30_YEARS) {
2241 user.lastLoggedInTime = now;
2242 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002243 }
2244 }
2245
2246 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002247 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002248 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2249 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002250 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002251 private int getNextAvailableId() {
2252 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002253 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002254 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002255 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002256 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002257 }
2258 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002259 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002260 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002261 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002262 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002263
Amith Yamasanifc95e702013-09-26 13:20:17 -07002264 private String packageToRestrictionsFileName(String packageName) {
2265 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2266 }
2267
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002268 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002269 * Enforce that serial number stored in user directory inode matches the
2270 * given expected value. Gracefully sets the serial number if currently
2271 * undefined.
2272 *
2273 * @throws IOException when problem extracting serial number, or serial
2274 * number is mismatched.
2275 */
2276 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2277 final int foundSerial = getSerialNumber(file);
2278 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2279
2280 if (foundSerial == -1) {
2281 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2282 try {
2283 setSerialNumber(file, serialNumber);
2284 } catch (IOException e) {
2285 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2286 }
2287
2288 } else if (foundSerial != serialNumber) {
2289 throw new IOException("Found serial number " + foundSerial
2290 + " doesn't match expected " + serialNumber);
2291 }
2292 }
2293
2294 /**
2295 * Set serial number stored in user directory inode.
2296 *
2297 * @throws IOException if serial number was already set
2298 */
2299 private static void setSerialNumber(File file, int serialNumber)
2300 throws IOException {
2301 try {
2302 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2303 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2304 } catch (ErrnoException e) {
2305 throw e.rethrowAsIOException();
2306 }
2307 }
2308
2309 /**
2310 * Return serial number stored in user directory inode.
2311 *
2312 * @return parsed serial number, or -1 if not set
2313 */
2314 private static int getSerialNumber(File file) throws IOException {
2315 try {
2316 final byte[] buf = new byte[256];
2317 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2318 final String serial = new String(buf, 0, len);
2319 try {
2320 return Integer.parseInt(serial);
2321 } catch (NumberFormatException e) {
2322 throw new IOException("Bad serial number: " + serial);
2323 }
2324 } catch (ErrnoException e) {
2325 if (e.errno == OsConstants.ENODATA) {
2326 return -1;
2327 } else {
2328 throw e.rethrowAsIOException();
2329 }
2330 }
2331 }
2332
Amith Yamasani920ace02012-09-20 22:15:37 -07002333 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002334 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2335 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2336 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2337 }
2338
2339 int onShellCommand(Shell shell, String cmd) {
2340 if (cmd == null) {
2341 return shell.handleDefaultCommands(cmd);
2342 }
2343
2344 final PrintWriter pw = shell.getOutPrintWriter();
2345 try {
2346 switch(cmd) {
2347 case "list":
2348 return runList(pw);
2349 }
2350 } catch (RemoteException e) {
2351 pw.println("Remote exception: " + e);
2352 }
2353 return -1;
2354 }
2355
2356 private int runList(PrintWriter pw) throws RemoteException {
2357 final IActivityManager am = ActivityManagerNative.getDefault();
2358 final List<UserInfo> users = getUsers(false);
2359 if (users == null) {
2360 pw.println("Error: couldn't get users");
2361 return 1;
2362 } else {
2363 pw.println("Users:");
2364 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002365 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002366 pw.println("\t" + users.get(i).toString() + running);
2367 }
2368 return 0;
2369 }
2370 }
2371
2372 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002373 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2374 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2375 != PackageManager.PERMISSION_GRANTED) {
2376 pw.println("Permission Denial: can't dump UserManager from from pid="
2377 + Binder.getCallingPid()
2378 + ", uid=" + Binder.getCallingUid()
2379 + " without permission "
2380 + android.Manifest.permission.DUMP);
2381 return;
2382 }
2383
2384 long now = System.currentTimeMillis();
2385 StringBuilder sb = new StringBuilder();
2386 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002387 synchronized (mUsersLock) {
2388 pw.println("Users:");
2389 for (int i = 0; i < mUsers.size(); i++) {
2390 UserInfo user = mUsers.valueAt(i);
2391 if (user == null) {
2392 continue;
2393 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002394 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002395 pw.print(" "); pw.print(user);
2396 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002397 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002398 pw.print(" <removing> ");
2399 }
2400 if (user.partial) {
2401 pw.print(" <partial>");
2402 }
2403 pw.println();
2404 pw.print(" Created: ");
2405 if (user.creationTime == 0) {
2406 pw.println("<unknown>");
2407 } else {
2408 sb.setLength(0);
2409 TimeUtils.formatDuration(now - user.creationTime, sb);
2410 sb.append(" ago");
2411 pw.println(sb);
2412 }
2413 pw.print(" Last logged in: ");
2414 if (user.lastLoggedInTime == 0) {
2415 pw.println("<unknown>");
2416 } else {
2417 sb.setLength(0);
2418 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2419 sb.append(" ago");
2420 pw.println(sb);
2421 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002422 pw.print(" Has profile owner: ");
2423 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002424 pw.println(" Restrictions:");
2425 synchronized (mRestrictionsLock) {
2426 UserRestrictionsUtils.dumpRestrictions(
2427 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002428 pw.println(" Device policy local restrictions:");
2429 UserRestrictionsUtils.dumpRestrictions(
2430 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002431 pw.println(" Effective restrictions:");
2432 UserRestrictionsUtils.dumpRestrictions(
2433 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2434 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002435 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002436 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002437 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002438 pw.println(" Device policy global restrictions:");
2439 synchronized (mRestrictionsLock) {
2440 UserRestrictionsUtils
2441 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2442 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002443 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002444 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002445 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002446 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002447 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002448 synchronized (mUsersLock) {
2449 pw.println();
2450 pw.println(" Device managed: " + mIsDeviceManaged);
2451 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002452 }
2453 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002454
2455 final class MainHandler extends Handler {
2456
2457 @Override
2458 public void handleMessage(Message msg) {
2459 switch (msg.what) {
2460 case WRITE_USER_MSG:
2461 removeMessages(WRITE_USER_MSG, msg.obj);
2462 synchronized (mPackagesLock) {
2463 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002464 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002465 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002466 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002467 }
2468 }
2469 }
2470 }
2471 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002472
2473 /**
2474 * @param userId
2475 * @return whether the user has been initialized yet
2476 */
2477 boolean isInitialized(int userId) {
2478 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2479 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002480
2481 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002482 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002483 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2484 @Nullable Bundle globalRestrictions) {
2485 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2486 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002487 }
2488
2489 @Override
2490 public Bundle getBaseUserRestrictions(int userId) {
2491 synchronized (mRestrictionsLock) {
2492 return mBaseUserRestrictions.get(userId);
2493 }
2494 }
2495
2496 @Override
2497 public void setBaseUserRestrictionsByDpmsForMigration(
2498 int userId, Bundle baseRestrictions) {
2499 synchronized (mRestrictionsLock) {
2500 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002501 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002502 }
2503
Fyodor Kupolov82402752015-10-28 14:54:51 -07002504 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002505 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002506 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002507 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002508 } else {
2509 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2510 }
2511 }
2512 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002513
2514 @Override
2515 public boolean getUserRestriction(int userId, String key) {
2516 return getUserRestrictions(userId).getBoolean(key);
2517 }
2518
2519 @Override
2520 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2521 synchronized (mUserRestrictionsListeners) {
2522 mUserRestrictionsListeners.add(listener);
2523 }
2524 }
2525
2526 @Override
2527 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2528 synchronized (mUserRestrictionsListeners) {
2529 mUserRestrictionsListeners.remove(listener);
2530 }
2531 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002532
2533 @Override
2534 public void setDeviceManaged(boolean isManaged) {
2535 synchronized (mUsersLock) {
2536 mIsDeviceManaged = isManaged;
2537 }
2538 }
2539
2540 @Override
2541 public void setUserManaged(int userId, boolean isManaged) {
2542 synchronized (mUsersLock) {
2543 mIsUserManaged.put(userId, isManaged);
2544 }
2545 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002546 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002547
2548 private class Shell extends ShellCommand {
2549 @Override
2550 public int onCommand(String cmd) {
2551 return onShellCommand(this, cmd);
2552 }
2553
2554 @Override
2555 public void onHelp() {
2556 final PrintWriter pw = getOutPrintWriter();
2557 pw.println("User manager (user) commands:");
2558 pw.println(" help");
2559 pw.println(" Print this help text.");
2560 pw.println("");
2561 pw.println(" list");
2562 pw.println(" Prints all users on the system.");
2563 }
2564 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002565
2566 private static void debug(String message) {
2567 Log.d(LOG_TAG, message +
2568 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2569 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002570}