blob: 5910c1068b7d1b62f4470643e0e603897f2650c3 [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
Rubin Xu0a29ecd2015-11-04 15:11:48 +0000478 private void broadcastProfileAvailabilityChanges(UserHandle profileHandle,
479 UserHandle parentHandle, Bundle extras) {
480 // Send intent to profile
481 Intent intent = new Intent(Intent.ACTION_AVAILABILITY_CHANGED);
482 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
483 intent.putExtras(extras);
484 mContext.sendBroadcastAsUser(intent, profileHandle);
485
486 // Send intent to parent
487 if (parentHandle != null) {
488 intent = new Intent(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
489 intent.putExtra(Intent.EXTRA_USER, profileHandle);
490 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
491 intent.putExtras(extras);
492 mContext.sendBroadcastAsUser(intent, parentHandle);
493 }
494 }
495
496 @Override
497 public void setQuietModeEnabled(int userHandle, boolean enableQuietMode) {
498 checkManageUsersPermission("silence profile");
499 boolean changed = false;
500 UserInfo profile, parent;
501 synchronized (mPackagesLock) {
502 synchronized (mUsersLock) {
503 profile = getUserInfoLU(userHandle);
504 parent = getProfileParentLU(userHandle);
505
506 }
507 if (profile == null || !profile.isManagedProfile()) {
508 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
509 }
510 if (profile.isQuietModeEnabled() != enableQuietMode) {
511 profile.flags ^= UserInfo.FLAG_QUIET_MODE;
512 writeUserLP(profile);
513 changed = true;
514 }
515 }
516 if (changed) {
517 Bundle extras = new Bundle();
518 extras.putBoolean(Intent.EXTRA_QUIET_MODE, enableQuietMode);
519 broadcastProfileAvailabilityChanges(profile.getUserHandle(),
520 parent != null ? parent.getUserHandle() : null, extras);
521 }
522 }
523
524 @Override
525 public boolean isQuietModeEnabled(int userHandle) {
526 synchronized (mPackagesLock) {
527 UserInfo info;
528 synchronized (mUsersLock) {
529 info = getUserInfoLU(userHandle);
530 }
531 if (info == null || !info.isManagedProfile()) {
532 throw new IllegalArgumentException("User " + userHandle + " is not a profile");
533 }
534 return info.isQuietModeEnabled();
535 }
536 }
537
Kenny Guya52dc3e2014-02-11 15:33:14 +0000538 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100539 public void setUserEnabled(int userId) {
540 checkManageUsersPermission("enable user");
541 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700542 UserInfo info;
543 synchronized (mUsersLock) {
544 info = getUserInfoLU(userId);
545 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100546 if (info != null && !info.isEnabled()) {
547 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100549 }
550 }
551 }
552
553 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700554 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700555 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700556 synchronized (mUsersLock) {
557 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700558 }
559 }
560
Amith Yamasani71e6c692013-03-24 17:39:28 -0700561 @Override
562 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700563 synchronized (mUsersLock) {
564 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700565 }
566 }
567
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700568 @Override
569 public boolean canHaveRestrictedProfile(int userId) {
570 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700571 synchronized (mUsersLock) {
572 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700573 if (userInfo == null || !userInfo.canHaveProfile()) {
574 return false;
575 }
576 if (!userInfo.isAdmin()) {
577 return false;
578 }
Makoto Onukie7927da2015-11-25 10:05:17 -0800579 // restricted profile can be created if there is no DO set and the admin user has no PO;
580 return !mIsDeviceManaged && !mIsUserManaged.get(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700581 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700582 }
583
Amith Yamasani195263742012-08-21 15:40:12 -0700584 /*
585 * Should be locked on mUsers before calling this.
586 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700587 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700588 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700589 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800590 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700591 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
592 return null;
593 }
594 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700595 }
596
Fyodor Kupolov82402752015-10-28 14:54:51 -0700597 /**
598 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
599 * <p>No permissions checking or any addition checks are made</p>
600 */
601 private UserInfo getUserInfoNoChecks(int userId) {
602 synchronized (mUsersLock) {
603 return mUsers.get(userId);
604 }
605 }
606
Amith Yamasani236b2b52015-08-18 14:32:14 -0700607 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700608 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700609 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700610 }
611
Amith Yamasani258848d2012-08-10 17:06:33 -0700612 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700613 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700614 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700615 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700616 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700617 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700618 if (info == null || info.partial) {
619 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
620 return;
621 }
Amith Yamasani13593602012-03-22 16:16:17 -0700622 if (name != null && !name.equals(info.name)) {
623 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700624 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700625 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700626 }
627 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700628 if (changed) {
629 sendUserInfoChangedBroadcast(userId);
630 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700631 }
632
Amith Yamasani258848d2012-08-10 17:06:33 -0700633 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700634 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700635 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400636 long ident = Binder.clearCallingIdentity();
637 try {
638 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700639 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400640 if (info == null || info.partial) {
641 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
642 return;
643 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700644 writeBitmapLP(info, bitmap);
645 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700646 }
Jason Monk9a944532014-07-08 09:31:21 -0400647 sendUserInfoChangedBroadcast(userId);
648 } finally {
649 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700650 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700651 }
652
653 private void sendUserInfoChangedBroadcast(int userId) {
654 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
655 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
656 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700657 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700658 }
659
Amith Yamasani258848d2012-08-10 17:06:33 -0700660 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100661 public ParcelFileDescriptor getUserIcon(int userId) {
662 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700663 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700664 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700665 if (info == null || info.partial) {
666 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
667 return null;
668 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700669 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100670 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
671 || callingGroupId != info.profileGroupId) {
672 checkManageUsersPermission("get the icon of a user who is not related");
673 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700674 if (info.iconPath == null) {
675 return null;
676 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100677 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700678 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100679
680 try {
681 return ParcelFileDescriptor.open(
682 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
683 } catch (FileNotFoundException e) {
684 Log.e(LOG_TAG, "Couldn't find icon file", e);
685 }
686 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700687 }
688
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700689 public void makeInitialized(int userId) {
690 checkManageUsersPermission("makeInitialized");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800691 boolean scheduleWriteUser = false;
692 UserInfo info;
693 synchronized (mUsersLock) {
694 info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700695 if (info == null || info.partial) {
696 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800697 return;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700698 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800699 if ((info.flags & UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700700 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800701 scheduleWriteUser = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700702 }
703 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800704 if (scheduleWriteUser) {
705 scheduleWriteUser(info);
706 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700707 }
708
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700709 /**
710 * If default guest restrictions haven't been initialized yet, add the basic
711 * restrictions.
712 */
713 private void initDefaultGuestRestrictions() {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800714 synchronized (mGuestRestrictions) {
715 if (mGuestRestrictions.isEmpty()) {
Fyodor Kupolove04462c2015-11-30 15:02:53 -0800716 mGuestRestrictions.putBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800717 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
718 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
719 }
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700720 }
721 }
722
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800723 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530724 public Bundle getDefaultGuestRestrictions() {
725 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800726 synchronized (mGuestRestrictions) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530727 return new Bundle(mGuestRestrictions);
728 }
729 }
730
731 @Override
732 public void setDefaultGuestRestrictions(Bundle restrictions) {
733 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800734 synchronized (mGuestRestrictions) {
735 mGuestRestrictions.clear();
736 mGuestRestrictions.putAll(restrictions);
737 }
738 synchronized (mPackagesLock) {
739 writeUserListLP();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530740 }
741 }
742
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800743 /**
744 * See {@link UserManagerInternal#setDevicePolicyUserRestrictions(int, Bundle, Bundle)}
745 */
746 void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle local,
747 @Nullable Bundle global) {
748 Preconditions.checkNotNull(local);
749 boolean globalChanged = false;
750 boolean localChanged;
751 synchronized (mRestrictionsLock) {
752 if (global != null) {
753 // Update global.
754 globalChanged = !UserRestrictionsUtils.areEqual(
755 mDevicePolicyGlobalUserRestrictions, global);
756 if (globalChanged) {
757 mDevicePolicyGlobalUserRestrictions = global;
758 }
759 }
760 {
761 // Update local.
762 final Bundle prev = mDevicePolicyLocalUserRestrictions.get(userId);
763 localChanged = !UserRestrictionsUtils.areEqual(prev, local);
764 if (localChanged) {
765 mDevicePolicyLocalUserRestrictions.put(userId, local);
766 }
767 }
768 }
769 if (DBG) {
770 Log.d(LOG_TAG, "setDevicePolicyUserRestrictions: userId=" + userId
771 + " global=" + global + (globalChanged ? " (changed)" : "")
772 + " local=" + local + (localChanged ? " (changed)" : "")
773 );
774 }
775 // Don't call them within the mRestrictionsLock.
776 synchronized (mPackagesLock) {
777 if (globalChanged) {
778 writeUserListLP();
779 }
780 if (localChanged) {
781 writeUserLP(getUserInfoNoChecks(userId));
782 }
783 }
784
785 synchronized (mRestrictionsLock) {
786 if (globalChanged) {
787 applyUserRestrictionsForAllUsersLR();
788 } else if (localChanged) {
789 applyUserRestrictionsLR(userId);
790 }
791 }
792 }
793
Makoto Onuki068c54a2015-10-13 14:34:03 -0700794 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700795 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800796 final Bundle baseRestrictions =
797 UserRestrictionsUtils.nonNull(mBaseUserRestrictions.get(userId));
798 final Bundle global = mDevicePolicyGlobalUserRestrictions;
799 final Bundle local = mDevicePolicyLocalUserRestrictions.get(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700800
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800801 if (UserRestrictionsUtils.isEmpty(global) && UserRestrictionsUtils.isEmpty(local)) {
802 // Common case first.
803 return baseRestrictions;
Makoto Onuki068c54a2015-10-13 14:34:03 -0700804 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800805 final Bundle effective = UserRestrictionsUtils.clone(baseRestrictions);
806 UserRestrictionsUtils.merge(effective, global);
807 UserRestrictionsUtils.merge(effective, local);
808
Makoto Onuki068c54a2015-10-13 14:34:03 -0700809 return effective;
810 }
811
812 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700813 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700814 if (DBG) {
815 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
816 }
817 mCachedEffectiveUserRestrictions.remove(userId);
818 }
819
820 private Bundle getEffectiveUserRestrictions(int userId) {
821 synchronized (mRestrictionsLock) {
822 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
823 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700824 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700825 mCachedEffectiveUserRestrictions.put(userId, restrictions);
826 }
827 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700828 }
829 }
830
Makoto Onuki068c54a2015-10-13 14:34:03 -0700831 /** @return a specific user restriction that's in effect currently. */
832 @Override
833 public boolean hasUserRestriction(String restrictionKey, int userId) {
834 Bundle restrictions = getEffectiveUserRestrictions(userId);
835 return restrictions != null && restrictions.getBoolean(restrictionKey);
836 }
837
838 /**
839 * @return UserRestrictions that are in effect currently. This always returns a new
840 * {@link Bundle}.
841 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700842 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800843 public Bundle getUserRestrictions(int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800844 return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800845 }
846
847 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700848 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700849 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700850 synchronized (mRestrictionsLock) {
851 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
852 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800853 final Bundle newRestrictions = UserRestrictionsUtils.clone(
854 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700855 newRestrictions.putBoolean(key, value);
856
Fyodor Kupolov82402752015-10-28 14:54:51 -0700857 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700858 }
859 }
860
Makoto Onuki068c54a2015-10-13 14:34:03 -0700861 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800862 * Optionally updating user restrictions, calculate the effective user restrictions and also
863 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700864 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800865 * @param newRestrictions User restrictions to set.
866 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700867 * @param userId target user ID.
868 */
869 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700870 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700871 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800872
873 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
874 mAppliedUserRestrictions.get(userId));
875
876 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700877 if (newRestrictions != null) {
878 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800879 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
880
881 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700882 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
883 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800884
885 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
886 mBaseUserRestrictions.put(userId, newRestrictions);
887 scheduleWriteUser(getUserInfoNoChecks(userId));
888 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700889 }
890
Fyodor Kupolov82402752015-10-28 14:54:51 -0700891 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700892
Makoto Onuki759a7632015-10-28 16:43:10 -0700893 mCachedEffectiveUserRestrictions.put(userId, effective);
894
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800895 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700896 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800897 debug("Applying user restrictions: userId=" + userId
898 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700899 }
900
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800901 if (mAppOpsService != null) { // We skip it until system-ready.
902 final long token = Binder.clearCallingIdentity();
903 try {
904 mAppOpsService.setUserRestrictions(effective, userId);
905 } catch (RemoteException e) {
906 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
907 } finally {
908 Binder.restoreCallingIdentity(token);
909 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700910 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700911
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800912 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700913
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800914 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700915 }
916
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800917 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800918 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800919 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
920 // actually, but we still need some kind of synchronization otherwise we might end up
921 // calling listeners out-of-order, thus "LR".
922
923 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
924 return;
925 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800926
927 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
928 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
929
930 mHandler.post(new Runnable() {
931 @Override
932 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700933 UserRestrictionsUtils.applyUserRestrictions(
934 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800935
Makoto Onukid45a4a22015-11-02 17:17:38 -0800936 final UserRestrictionsListener[] listeners;
937 synchronized (mUserRestrictionsListeners) {
938 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
939 mUserRestrictionsListeners.toArray(listeners);
940 }
941 for (int i = 0; i < listeners.length; i++) {
942 listeners[i].onUserRestrictionsChanged(userId,
943 newRestrictionsFinal, prevRestrictionsFinal);
944 }
945 }
946 });
947 }
948
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800949 // Package private for the inner class.
950 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700951 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700952 }
953
954 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800955 // Package private for the inner class.
956 void applyUserRestrictionsForAllUsersLR() {
957 if (DBG) {
958 debug("applyUserRestrictionsForAllUsersLR");
959 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700960 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700961 mCachedEffectiveUserRestrictions.clear();
962
Makoto Onuki068c54a2015-10-13 14:34:03 -0700963 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
964 // it on a handler.
965 final Runnable r = new Runnable() {
966 @Override
967 public void run() {
968 // Then get the list of running users.
969 final int[] runningUsers;
970 try {
971 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
972 } catch (RemoteException e) {
973 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
974 return;
975 }
976 // Then re-calculate the effective restrictions and apply, only for running users.
977 // It's okay if a new user has started after the getRunningUserIds() call,
978 // because we'll do the same thing (re-calculate the restrictions and apply)
979 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700980 synchronized (mRestrictionsLock) {
981 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800982 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700983 }
984 }
985 }
986 };
987 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700988 }
989
Amith Yamasani258848d2012-08-10 17:06:33 -0700990 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700991 * Check if we've hit the limit of how many users can be created.
992 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700993 private boolean isUserLimitReached() {
994 int count;
995 synchronized (mUsersLock) {
996 count = getAliveUsersExcludingGuestsCountLU();
997 }
998 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700999 }
1000
1001 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001002 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001003 checkManageUsersPermission("check if more managed profiles can be added.");
1004 if (ActivityManager.isLowRamDeviceStatic()) {
1005 return false;
1006 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001007 if (!mContext.getPackageManager().hasSystemFeature(
1008 PackageManager.FEATURE_MANAGED_USERS)) {
1009 return false;
1010 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001011 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001012 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1013 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1014 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001015 return false;
1016 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001017 synchronized(mUsersLock) {
1018 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001019 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001020 return false;
1021 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001022 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1023 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001024 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001025 return usersCountAfterRemoving == 1
1026 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001027 }
1028 }
1029
Fyodor Kupolov82402752015-10-28 14:54:51 -07001030 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001031 int aliveUserCount = 0;
1032 final int totalUserCount = mUsers.size();
1033 // Skip over users being removed
1034 for (int i = 0; i < totalUserCount; i++) {
1035 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001036 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001037 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001038 aliveUserCount++;
1039 }
1040 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001041 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001042 }
1043
1044 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001045 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001046 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001047 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001048 *
1049 * @param message used as message if SecurityException is thrown
1050 * @throws SecurityException if the caller is not system or root
1051 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001052 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001053 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -07001054 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001055 && ActivityManager.checkComponentPermission(
1056 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001057 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1058 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1059 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001060 }
1061
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001062 private static void checkSystemOrRoot(String message) {
1063 final int uid = Binder.getCallingUid();
1064 if (uid != Process.SYSTEM_UID && uid != 0) {
1065 throw new SecurityException("Only system may call: " + message);
1066 }
1067 }
1068
Fyodor Kupolov82402752015-10-28 14:54:51 -07001069 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001070 try {
1071 File dir = new File(mUsersDir, Integer.toString(info.id));
1072 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001073 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001074 if (!dir.exists()) {
1075 dir.mkdir();
1076 FileUtils.setPermissions(
1077 dir.getPath(),
1078 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1079 -1, -1);
1080 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001081 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001082 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1083 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001084 info.iconPath = file.getAbsolutePath();
1085 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001086 try {
1087 os.close();
1088 } catch (IOException ioe) {
1089 // What the ... !
1090 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001091 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001092 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001093 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001094 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001095 }
1096
Amith Yamasani0b285492011-04-14 17:35:23 -07001097 /**
1098 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1099 * cache it elsewhere.
1100 * @return the array of user ids.
1101 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001102 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001103 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001104 return mUserIds;
1105 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001106 }
1107
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001108 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001109 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001110 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001111 return;
1112 }
1113 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001114 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001115 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001116 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001117 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001118 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001119 int type;
1120 while ((type = parser.next()) != XmlPullParser.START_TAG
1121 && type != XmlPullParser.END_DOCUMENT) {
1122 ;
1123 }
1124
1125 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001126 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001127 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001128 return;
1129 }
1130
Amith Yamasani2a003292012-08-14 18:25:45 -07001131 mNextSerialNumber = -1;
1132 if (parser.getName().equals(TAG_USERS)) {
1133 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1134 if (lastSerialNumber != null) {
1135 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1136 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001137 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1138 if (versionNumber != null) {
1139 mUserVersion = Integer.parseInt(versionNumber);
1140 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001141 }
1142
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001143 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1144
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001145 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301146 if (type == XmlPullParser.START_TAG) {
1147 final String name = parser.getName();
1148 if (name.equals(TAG_USER)) {
1149 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001150 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001151
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301152 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001153 synchronized (mUsersLock) {
1154 mUsers.put(user.id, user);
1155 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1156 mNextSerialNumber = user.id + 1;
1157 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301158 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001159 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301160 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001161 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1162 && type != XmlPullParser.END_TAG) {
1163 if (type == XmlPullParser.START_TAG) {
1164 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001165 synchronized (mGuestRestrictions) {
1166 UserRestrictionsUtils
1167 .readRestrictions(parser, mGuestRestrictions);
1168 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001169 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1170 ) {
1171 UserRestrictionsUtils.readRestrictions(parser,
1172 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001173 }
1174 break;
1175 }
1176 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001177 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001178 }
1179 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001180 synchronized (mRestrictionsLock) {
1181 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1182 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001183 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001184 upgradeIfNecessaryLP();
1185 } catch (IOException | XmlPullParserException e) {
1186 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001187 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001188 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001189 }
1190 }
1191
Amith Yamasani6f34b412012-10-22 18:19:27 -07001192 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001193 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001194 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001195 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001196 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001197 int userVersion = mUserVersion;
1198 if (userVersion < 1) {
1199 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001200 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001201 if ("Primary".equals(user.name)) {
1202 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001203 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001204 }
1205 userVersion = 1;
1206 }
1207
Amith Yamasanibc9625052012-11-15 14:39:18 -08001208 if (userVersion < 2) {
1209 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001210 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001211 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1212 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001213 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001214 }
1215 userVersion = 2;
1216 }
1217
Amith Yamasani350962c2013-08-06 11:18:53 -07001218
Amith Yamasani5e486f52013-08-07 11:06:44 -07001219 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001220 userVersion = 4;
1221 }
1222
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001223 if (userVersion < 5) {
1224 initDefaultGuestRestrictions();
1225 userVersion = 5;
1226 }
1227
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001228 if (userVersion < 6) {
1229 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001230 synchronized (mUsersLock) {
1231 for (int i = 0; i < mUsers.size(); i++) {
1232 UserInfo user = mUsers.valueAt(i);
1233 // In non-split mode, only user 0 can have restricted profiles
1234 if (!splitSystemUser && user.isRestricted()
1235 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1236 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001237 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001238 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001239 }
1240 }
1241 userVersion = 6;
1242 }
1243
Amith Yamasani6f34b412012-10-22 18:19:27 -07001244 if (userVersion < USER_VERSION) {
1245 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1246 + USER_VERSION);
1247 } else {
1248 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001249
1250 if (originalVersion < mUserVersion) {
1251 writeUserListLP();
1252 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001253 }
1254 }
1255
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001256 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001257 int flags = UserInfo.FLAG_INITIALIZED;
1258 // In split system user mode, the admin and primary flags are assigned to the first human
1259 // user.
1260 if (!UserManager.isSplitSystemUser()) {
1261 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1262 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001263 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001264 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001265 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001266 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001267 synchronized (mUsersLock) {
1268 mUsers.put(system.id, system);
1269 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001270 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001271 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001272
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001273 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001274 synchronized (mRestrictionsLock) {
1275 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1276 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001277
Fyodor Kupolov82402752015-10-28 14:54:51 -07001278 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001279 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001280
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001281 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001282 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001283 }
1284
Makoto Onuki9e935a32015-11-06 14:24:24 -08001285 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001286 if (DBG) {
1287 debug("scheduleWriteUser");
1288 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001289 // No need to wrap it within a lock -- worst case, we'll just post the same message
1290 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001291 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1292 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1293 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1294 }
1295 }
1296
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001297 /*
1298 * Writes the user file in this format:
1299 *
1300 * <user flags="20039023" id="0">
1301 * <name>Primary</name>
1302 * </user>
1303 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001304 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001305 if (DBG) {
1306 debug("writeUserLP " + userInfo);
1307 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001308 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001309 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001310 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001311 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001312 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1313
1314 // XmlSerializer serializer = XmlUtils.serializerInstance();
1315 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001316 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001317 serializer.startDocument(null, true);
1318 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1319
1320 serializer.startTag(null, TAG_USER);
1321 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001322 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001323 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001324 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1325 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1326 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001327 if (userInfo.iconPath != null) {
1328 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1329 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001330 if (userInfo.partial) {
1331 serializer.attribute(null, ATTR_PARTIAL, "true");
1332 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001333 if (userInfo.guestToRemove) {
1334 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1335 }
Kenny Guy2a764942014-04-02 13:29:20 +01001336 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1337 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1338 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001339 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001340 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1341 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1342 Integer.toString(userInfo.restrictedProfileParentId));
1343 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001344 serializer.startTag(null, TAG_NAME);
1345 serializer.text(userInfo.name);
1346 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001347 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001348 UserRestrictionsUtils.writeRestrictions(serializer,
1349 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1350 UserRestrictionsUtils.writeRestrictions(serializer,
1351 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1352 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001353 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001354 serializer.endTag(null, TAG_USER);
1355
1356 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001357 userFile.finishWrite(fos);
1358 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001359 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001360 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001361 }
1362 }
1363
1364 /*
1365 * Writes the user list file in this format:
1366 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001367 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001368 * <user id="0"></user>
1369 * <user id="2"></user>
1370 * </users>
1371 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001372 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001373 if (DBG) {
1374 debug("writeUserList");
1375 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001376 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001377 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001378 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001379 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001380 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1381
1382 // XmlSerializer serializer = XmlUtils.serializerInstance();
1383 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001384 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001385 serializer.startDocument(null, true);
1386 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1387
1388 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001389 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001390 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001391
Adam Lesinskieddeb492014-09-08 17:50:03 -07001392 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001393 synchronized (mGuestRestrictions) {
1394 UserRestrictionsUtils
1395 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1396 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301397 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001398 synchronized (mRestrictionsLock) {
1399 UserRestrictionsUtils.writeRestrictions(serializer,
1400 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1401 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001402 int[] userIdsToWrite;
1403 synchronized (mUsersLock) {
1404 userIdsToWrite = new int[mUsers.size()];
1405 for (int i = 0; i < userIdsToWrite.length; i++) {
1406 UserInfo user = mUsers.valueAt(i);
1407 userIdsToWrite[i] = user.id;
1408 }
1409 }
1410 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001411 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001412 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001413 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001414 }
1415
1416 serializer.endTag(null, TAG_USERS);
1417
1418 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001419 userListFile.finishWrite(fos);
1420 } catch (Exception e) {
1421 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001422 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001423 }
1424 }
1425
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001426 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001427 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001428 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001429 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001430 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001431 long creationTime = 0L;
1432 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001433 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001434 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001435 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001436 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001437 Bundle baseRestrictions = new Bundle();
1438 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001439
1440 FileInputStream fis = null;
1441 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001442 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001443 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001444 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001445 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001446 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001447 int type;
1448 while ((type = parser.next()) != XmlPullParser.START_TAG
1449 && type != XmlPullParser.END_DOCUMENT) {
1450 ;
1451 }
1452
1453 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001454 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001455 return null;
1456 }
1457
1458 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001459 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1460 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001461 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001462 return null;
1463 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001464 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1465 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001466 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001467 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1468 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001469 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1470 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001471 restrictedProfileParentId = readIntAttribute(parser,
1472 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001473 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1474 if ("true".equals(valueString)) {
1475 partial = true;
1476 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001477 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1478 if ("true".equals(valueString)) {
1479 guestToRemove = true;
1480 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001481
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001482 int outerDepth = parser.getDepth();
1483 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1484 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1485 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1486 continue;
1487 }
1488 String tag = parser.getName();
1489 if (TAG_NAME.equals(tag)) {
1490 type = parser.next();
1491 if (type == XmlPullParser.TEXT) {
1492 name = parser.getText();
1493 }
1494 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001495 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1496 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1497 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001498 }
1499 }
1500 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001501
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001502 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001503 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001504 userInfo.creationTime = creationTime;
1505 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001506 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001507 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001508 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001509 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001510 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001511 mBaseUserRestrictions.put(id, baseRestrictions);
1512 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001513 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001514 return userInfo;
1515
1516 } catch (IOException ioe) {
1517 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001518 } finally {
1519 if (fis != null) {
1520 try {
1521 fis.close();
1522 } catch (IOException e) {
1523 }
1524 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001525 }
1526 return null;
1527 }
1528
Amith Yamasani920ace02012-09-20 22:15:37 -07001529 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1530 String valueString = parser.getAttributeValue(null, attr);
1531 if (valueString == null) return defaultValue;
1532 try {
1533 return Integer.parseInt(valueString);
1534 } catch (NumberFormatException nfe) {
1535 return defaultValue;
1536 }
1537 }
1538
1539 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1540 String valueString = parser.getAttributeValue(null, attr);
1541 if (valueString == null) return defaultValue;
1542 try {
1543 return Long.parseLong(valueString);
1544 } catch (NumberFormatException nfe) {
1545 return defaultValue;
1546 }
1547 }
1548
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001549 private boolean isPackageInstalled(String pkg, int userId) {
1550 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1551 PackageManager.GET_UNINSTALLED_PACKAGES,
1552 userId);
1553 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1554 return false;
1555 }
1556 return true;
1557 }
1558
Amith Yamasanib82add22013-07-09 11:24:44 -07001559 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001560 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001561 * Does not do any permissions checking.
1562 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001563 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001564 synchronized (mPackagesLock) {
1565 File dir = Environment.getUserSystemDirectory(userId);
1566 String[] files = dir.list();
1567 if (files == null) return;
1568 for (String fileName : files) {
1569 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1570 File resFile = new File(dir, fileName);
1571 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001572 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001573 }
1574 }
1575 }
1576 }
1577 }
1578
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001579 /**
1580 * Removes the app restrictions file for a specific package and user id, if it exists.
1581 */
1582 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1583 synchronized (mPackagesLock) {
1584 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001585 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001586 if (resFile.exists()) {
1587 resFile.delete();
1588 }
1589 }
1590 }
1591
Kenny Guya52dc3e2014-02-11 15:33:14 +00001592 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001593 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001594 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001595 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001596 }
1597
Amith Yamasani258848d2012-08-10 17:06:33 -07001598 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001599 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001600 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001601 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001602 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001603
Jessica Hummelbe81c802014-04-22 15:49:22 +01001604 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001605 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001606 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1607 return null;
1608 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001609 if (ActivityManager.isLowRamDeviceStatic()) {
1610 return null;
1611 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001612 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001613 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001614 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001615 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001616 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001617 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001618 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001619 synchronized (mPackagesLock) {
1620 UserInfo parent = null;
1621 if (parentId != UserHandle.USER_NULL) {
1622 synchronized (mUsersLock) {
1623 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001624 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001625 if (parent == null) return null;
1626 }
1627 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1628 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1629 return null;
1630 }
1631 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1632 // If we're not adding a guest user or a managed profile and the limit has
1633 // been reached, cannot add a user.
1634 return null;
1635 }
1636 // If we're adding a guest and there already exists one, bail.
1637 if (isGuest && findCurrentGuestUser() != null) {
1638 return null;
1639 }
1640 // In legacy mode, restricted profile's parent can only be the owner user
1641 if (isRestricted && !UserManager.isSplitSystemUser()
1642 && (parentId != UserHandle.USER_SYSTEM)) {
1643 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1644 return null;
1645 }
1646 if (isRestricted && UserManager.isSplitSystemUser()) {
1647 if (parent == null) {
1648 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1649 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001650 return null;
1651 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001652 if (!parent.canHaveProfile()) {
1653 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1654 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001655 return null;
1656 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001657 }
1658 // In split system user mode, we assign the first human user the primary flag.
1659 // And if there is no device owner, we also assign the admin flag to primary user.
1660 if (UserManager.isSplitSystemUser()
1661 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1662 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001663 synchronized (mUsersLock) {
1664 if (!mIsDeviceManaged) {
1665 flags |= UserInfo.FLAG_ADMIN;
1666 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001667 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001668 }
1669 userId = getNextAvailableId();
1670 userInfo = new UserInfo(userId, name, null, flags);
1671 userInfo.serialNumber = mNextSerialNumber++;
1672 long now = System.currentTimeMillis();
1673 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1674 userInfo.partial = true;
1675 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1676 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001677 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001678 }
1679 writeUserListLP();
1680 if (parent != null) {
1681 if (isManagedProfile) {
1682 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1683 parent.profileGroupId = parent.id;
1684 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001685 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001686 userInfo.profileGroupId = parent.profileGroupId;
1687 } else if (isRestricted) {
1688 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1689 parent.restrictedProfileParentId = parent.id;
1690 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001691 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001692 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001693 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001694 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001695 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001696 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1697 storage.createUserKey(userId, userInfo.serialNumber);
1698 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1699 final String volumeUuid = vol.getFsUuid();
1700 try {
1701 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
1702 storage.prepareUserStorage(volumeUuid, userId, userInfo.serialNumber);
1703 enforceSerialNumber(userDir, userInfo.serialNumber);
1704 } catch (IOException e) {
1705 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1706 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001707 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001708 mPm.createNewUser(userId);
1709 userInfo.partial = false;
1710 synchronized (mPackagesLock) {
1711 writeUserLP(userInfo);
1712 }
1713 updateUserIds();
1714 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001715 if (isGuest) {
1716 synchronized (mGuestRestrictions) {
1717 restrictions.putAll(mGuestRestrictions);
1718 }
1719 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001720 synchronized (mRestrictionsLock) {
1721 mBaseUserRestrictions.append(userId, restrictions);
1722 }
1723 mPm.newUserCreated(userId);
1724 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1725 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1726 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1727 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001728 } finally {
1729 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001730 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001731 return userInfo;
1732 }
1733
Amith Yamasani0b285492011-04-14 17:35:23 -07001734 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001735 * @hide
1736 */
1737 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1738 checkManageUsersPermission("setupRestrictedProfile");
1739 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1740 if (user == null) {
1741 return null;
1742 }
1743 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1744 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1745 // the putIntForUser() will fail.
1746 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1747 android.provider.Settings.Secure.LOCATION_MODE,
1748 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1749 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1750 return user;
1751 }
1752
1753 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001754 * Find the current guest user. If the Guest user is partial,
1755 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001756 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001757 private UserInfo findCurrentGuestUser() {
1758 synchronized (mUsersLock) {
1759 final int size = mUsers.size();
1760 for (int i = 0; i < size; i++) {
1761 final UserInfo user = mUsers.valueAt(i);
1762 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1763 return user;
1764 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001765 }
1766 }
1767 return null;
1768 }
1769
1770 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001771 * Mark this guest user for deletion to allow us to create another guest
1772 * and switch to that user before actually removing this guest.
1773 * @param userHandle the userid of the current guest
1774 * @return whether the user could be marked for deletion
1775 */
1776 public boolean markGuestForDeletion(int userHandle) {
1777 checkManageUsersPermission("Only the system can remove users");
1778 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1779 UserManager.DISALLOW_REMOVE_USER, false)) {
1780 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1781 return false;
1782 }
1783
1784 long ident = Binder.clearCallingIdentity();
1785 try {
1786 final UserInfo user;
1787 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001788 synchronized (mUsersLock) {
1789 user = mUsers.get(userHandle);
1790 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1791 return false;
1792 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001793 }
1794 if (!user.isGuest()) {
1795 return false;
1796 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001797 // We set this to a guest user that is to be removed. This is a temporary state
1798 // where we are allowed to add new Guest users, even if this one is still not
1799 // removed. This user will still show up in getUserInfo() calls.
1800 // If we don't get around to removing this Guest user, it will be purged on next
1801 // startup.
1802 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001803 // Mark it as disabled, so that it isn't returned any more when
1804 // profiles are queried.
1805 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001806 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001807 }
1808 } finally {
1809 Binder.restoreCallingIdentity(ident);
1810 }
1811 return true;
1812 }
1813
1814 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001815 * Removes a user and all data directories created for that user. This method should be called
1816 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001817 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001818 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001819 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001820 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001821 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1822 UserManager.DISALLOW_REMOVE_USER, false)) {
1823 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1824 return false;
1825 }
1826
Kenny Guyee58b4f2014-05-23 15:19:53 +01001827 long ident = Binder.clearCallingIdentity();
1828 try {
1829 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001830 int currentUser = ActivityManager.getCurrentUser();
1831 if (currentUser == userHandle) {
1832 Log.w(LOG_TAG, "Current user cannot be removed");
1833 return false;
1834 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001835 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001836 synchronized (mUsersLock) {
1837 user = mUsers.get(userHandle);
1838 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1839 return false;
1840 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001841
Fyodor Kupolov82402752015-10-28 14:54:51 -07001842 // We remember deleted user IDs to prevent them from being
1843 // reused during the current boot; they can still be reused
1844 // after a reboot.
1845 mRemovingUserIds.put(userHandle, true);
1846 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001847
Kenny Guyee58b4f2014-05-23 15:19:53 +01001848 try {
1849 mAppOpsService.removeUser(userHandle);
1850 } catch (RemoteException e) {
1851 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1852 }
1853 // Set this to a partially created user, so that the user will be purged
1854 // on next startup, in case the runtime stops now before stopping and
1855 // removing the user completely.
1856 user.partial = true;
1857 // Mark it as disabled, so that it isn't returned any more when
1858 // profiles are queried.
1859 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001860 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001861 }
1862
1863 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1864 && user.isManagedProfile()) {
1865 // Send broadcast to notify system that the user removed was a
1866 // managed user.
1867 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1868 }
1869
1870 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1871 int res;
1872 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001873 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
1874 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001875 @Override
1876 public void userStopped(int userId) {
1877 finishRemoveUser(userId);
1878 }
1879 @Override
1880 public void userStopAborted(int userId) {
1881 }
1882 });
1883 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001884 return false;
1885 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001886 return res == ActivityManager.USER_OP_SUCCESS;
1887 } finally {
1888 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001889 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001890 }
1891
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001892 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001893 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001894 // Let other services shutdown any activity and clean up their state before completely
1895 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001896 long ident = Binder.clearCallingIdentity();
1897 try {
1898 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1899 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001900 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1901 android.Manifest.permission.MANAGE_USERS,
1902
1903 new BroadcastReceiver() {
1904 @Override
1905 public void onReceive(Context context, Intent intent) {
1906 if (DBG) {
1907 Slog.i(LOG_TAG,
1908 "USER_REMOVED broadcast sent, cleaning up user data "
1909 + userHandle);
1910 }
1911 new Thread() {
1912 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001913 // Clean up any ActivityManager state
1914 LocalServices.getService(ActivityManagerInternal.class)
1915 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001916 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001917 }
1918 }.start();
1919 }
1920 },
1921
1922 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001923 } finally {
1924 Binder.restoreCallingIdentity(ident);
1925 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001926 }
1927
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001928 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001929 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001930 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001931 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001932
1933 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001934 synchronized (mUsersLock) {
1935 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08001936 mIsUserManaged.delete(userHandle);
1937 }
1938 synchronized (mRestrictionsLock) {
1939 mBaseUserRestrictions.remove(userHandle);
1940 mAppliedUserRestrictions.remove(userHandle);
1941 mCachedEffectiveUserRestrictions.remove(userHandle);
1942 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001943 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001944 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001945 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001946 userFile.delete();
1947 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001948 synchronized (mPackagesLock) {
1949 writeUserListLP();
1950 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001951 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001952 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1953 }
1954
Amith Yamasani61f57372012-08-31 12:12:28 -07001955 private void removeDirectoryRecursive(File parent) {
1956 if (parent.isDirectory()) {
1957 String[] files = parent.list();
1958 for (String filename : files) {
1959 File child = new File(parent, filename);
1960 removeDirectoryRecursive(child);
1961 }
1962 }
1963 parent.delete();
1964 }
1965
Kenny Guyf8d3a232014-05-15 16:09:52 +01001966 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001967 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001968 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1969 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001970 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1971 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001972 }
1973
Amith Yamasani2a003292012-08-14 18:25:45 -07001974 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001975 public Bundle getApplicationRestrictions(String packageName) {
1976 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1977 }
1978
1979 @Override
1980 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001981 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001982 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001983 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001984 }
1985 synchronized (mPackagesLock) {
1986 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001987 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001988 }
1989 }
1990
1991 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001992 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001993 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001994 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001995 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001996 if (restrictions == null || restrictions.isEmpty()) {
1997 cleanAppRestrictionsForPackage(packageName, userId);
1998 } else {
1999 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002000 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002001 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002002 }
Robin Lee66e5d962014-04-09 16:44:21 +01002003
Kenny Guyd21b2182014-07-17 16:38:55 +01002004 if (isPackageInstalled(packageName, userId)) {
2005 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2006 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2007 changeIntent.setPackage(packageName);
2008 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2009 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2010 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002011 }
2012
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002013 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002014 mHandler.post(new Runnable() {
2015 @Override
2016 public void run() {
2017 List<ApplicationInfo> apps =
2018 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
2019 userHandle).getList();
2020 final long ident = Binder.clearCallingIdentity();
2021 try {
2022 for (ApplicationInfo appInfo : apps) {
2023 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002024 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
2025 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002026 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002027 userHandle);
2028 }
2029 }
2030 } finally {
2031 Binder.restoreCallingIdentity(ident);
2032 }
2033 }
2034 });
2035 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002036 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002037 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002038 try {
2039 return mContext.getPackageManager().getApplicationInfo(packageName,
2040 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2041 } catch (NameNotFoundException nnfe) {
2042 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002043 } finally {
2044 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002045 }
2046 }
2047
Fyodor Kupolov82402752015-10-28 14:54:51 -07002048 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002049 AtomicFile restrictionsFile =
2050 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2051 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002052 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002053 }
2054
2055 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002056 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002057 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002058 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002059 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002060 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002061 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002062
2063 FileInputStream fis = null;
2064 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002065 fis = restrictionsFile.openRead();
2066 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002067 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002068 XmlUtils.nextElement(parser);
2069 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002070 Slog.e(LOG_TAG, "Unable to read restrictions file "
2071 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002072 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002073 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002074 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2075 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002076 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002077 } catch (IOException|XmlPullParserException e) {
2078 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002079 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002080 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002081 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002082 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002083 }
2084
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002085 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2086 XmlPullParser parser) throws XmlPullParserException, IOException {
2087 int type = parser.getEventType();
2088 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2089 String key = parser.getAttributeValue(null, ATTR_KEY);
2090 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2091 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2092 if (multiple != null) {
2093 values.clear();
2094 int count = Integer.parseInt(multiple);
2095 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2096 if (type == XmlPullParser.START_TAG
2097 && parser.getName().equals(TAG_VALUE)) {
2098 values.add(parser.nextText().trim());
2099 count--;
2100 }
2101 }
2102 String [] valueStrings = new String[values.size()];
2103 values.toArray(valueStrings);
2104 restrictions.putStringArray(key, valueStrings);
2105 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2106 restrictions.putBundle(key, readBundleEntry(parser, values));
2107 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2108 final int outerDepth = parser.getDepth();
2109 ArrayList<Bundle> bundleList = new ArrayList<>();
2110 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2111 Bundle childBundle = readBundleEntry(parser, values);
2112 bundleList.add(childBundle);
2113 }
2114 restrictions.putParcelableArray(key,
2115 bundleList.toArray(new Bundle[bundleList.size()]));
2116 } else {
2117 String value = parser.nextText().trim();
2118 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2119 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2120 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2121 restrictions.putInt(key, Integer.parseInt(value));
2122 } else {
2123 restrictions.putString(key, value);
2124 }
2125 }
2126 }
2127 }
2128
2129 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2130 throws IOException, XmlPullParserException {
2131 Bundle childBundle = new Bundle();
2132 final int outerDepth = parser.getDepth();
2133 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2134 readEntry(childBundle, values, parser);
2135 }
2136 return childBundle;
2137 }
2138
Fyodor Kupolov82402752015-10-28 14:54:51 -07002139 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002140 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002141 AtomicFile restrictionsFile = new AtomicFile(
2142 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002143 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002144 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002145 }
2146
2147 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002148 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002149 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002150 try {
2151 fos = restrictionsFile.startWrite();
2152 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2153
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002154 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002155 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002156 serializer.startDocument(null, true);
2157 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2158
2159 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002160 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002161 serializer.endTag(null, TAG_RESTRICTIONS);
2162
2163 serializer.endDocument();
2164 restrictionsFile.finishWrite(fos);
2165 } catch (Exception e) {
2166 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002167 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2168 }
2169 }
2170
2171 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2172 throws IOException {
2173 for (String key : restrictions.keySet()) {
2174 Object value = restrictions.get(key);
2175 serializer.startTag(null, TAG_ENTRY);
2176 serializer.attribute(null, ATTR_KEY, key);
2177
2178 if (value instanceof Boolean) {
2179 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2180 serializer.text(value.toString());
2181 } else if (value instanceof Integer) {
2182 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2183 serializer.text(value.toString());
2184 } else if (value == null || value instanceof String) {
2185 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2186 serializer.text(value != null ? (String) value : "");
2187 } else if (value instanceof Bundle) {
2188 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2189 writeBundle((Bundle) value, serializer);
2190 } else if (value instanceof Parcelable[]) {
2191 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2192 Parcelable[] array = (Parcelable[]) value;
2193 for (Parcelable parcelable : array) {
2194 if (!(parcelable instanceof Bundle)) {
2195 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2196 }
2197 serializer.startTag(null, TAG_ENTRY);
2198 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2199 writeBundle((Bundle) parcelable, serializer);
2200 serializer.endTag(null, TAG_ENTRY);
2201 }
2202 } else {
2203 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2204 String[] values = (String[]) value;
2205 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2206 for (String choice : values) {
2207 serializer.startTag(null, TAG_VALUE);
2208 serializer.text(choice != null ? choice : "");
2209 serializer.endTag(null, TAG_VALUE);
2210 }
2211 }
2212 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002213 }
2214 }
2215
2216 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002217 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002218 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002219 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002220 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002221 }
2222 }
2223
2224 @Override
2225 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002226 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002227 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002228 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002229 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002230 }
2231 // Not found
2232 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002233 }
2234 }
2235
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002236 @Override
2237 public long getUserCreationTime(int userHandle) {
2238 int callingUserId = UserHandle.getCallingUserId();
2239 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002240 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002241 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002242 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002243 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002244 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002245 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002246 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002247 }
2248 }
2249 }
2250 if (userInfo == null) {
2251 throw new SecurityException("userHandle can only be the calling user or a managed "
2252 + "profile associated with this user");
2253 }
2254 return userInfo.creationTime;
2255 }
2256
Amith Yamasani0b285492011-04-14 17:35:23 -07002257 /**
2258 * Caches the list of user ids in an array, adjusting the array size when necessary.
2259 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002260 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002261 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002262 synchronized (mUsersLock) {
2263 final int userSize = mUsers.size();
2264 for (int i = 0; i < userSize; i++) {
2265 if (!mUsers.valueAt(i).partial) {
2266 num++;
2267 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002268 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002269 final int[] newUsers = new int[num];
2270 int n = 0;
2271 for (int i = 0; i < userSize; i++) {
2272 if (!mUsers.valueAt(i).partial) {
2273 newUsers[n++] = mUsers.keyAt(i);
2274 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002275 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002276 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002277 }
2278 }
2279
2280 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002281 * Called right before a user starts. This will not be called for the system user.
2282 */
2283 public void onBeforeStartUser(int userId) {
2284 synchronized (mRestrictionsLock) {
2285 applyUserRestrictionsLR(userId);
2286 }
2287 }
2288
2289 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002290 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002291 * @param userId the user that was just foregrounded
2292 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002293 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002294 UserInfo user = getUserInfoNoChecks(userId);
2295 if (user == null || user.partial) {
2296 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2297 return;
2298 }
2299 long now = System.currentTimeMillis();
2300 if (now > EPOCH_PLUS_30_YEARS) {
2301 user.lastLoggedInTime = now;
2302 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002303 }
2304 }
2305
2306 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002307 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002308 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2309 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002310 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002311 private int getNextAvailableId() {
2312 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002313 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002314 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002315 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002316 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002317 }
2318 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002319 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002320 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002321 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002322 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002323
Amith Yamasanifc95e702013-09-26 13:20:17 -07002324 private String packageToRestrictionsFileName(String packageName) {
2325 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2326 }
2327
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002328 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002329 * Enforce that serial number stored in user directory inode matches the
2330 * given expected value. Gracefully sets the serial number if currently
2331 * undefined.
2332 *
2333 * @throws IOException when problem extracting serial number, or serial
2334 * number is mismatched.
2335 */
2336 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2337 final int foundSerial = getSerialNumber(file);
2338 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2339
2340 if (foundSerial == -1) {
2341 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2342 try {
2343 setSerialNumber(file, serialNumber);
2344 } catch (IOException e) {
2345 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2346 }
2347
2348 } else if (foundSerial != serialNumber) {
2349 throw new IOException("Found serial number " + foundSerial
2350 + " doesn't match expected " + serialNumber);
2351 }
2352 }
2353
2354 /**
2355 * Set serial number stored in user directory inode.
2356 *
2357 * @throws IOException if serial number was already set
2358 */
2359 private static void setSerialNumber(File file, int serialNumber)
2360 throws IOException {
2361 try {
2362 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2363 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2364 } catch (ErrnoException e) {
2365 throw e.rethrowAsIOException();
2366 }
2367 }
2368
2369 /**
2370 * Return serial number stored in user directory inode.
2371 *
2372 * @return parsed serial number, or -1 if not set
2373 */
2374 private static int getSerialNumber(File file) throws IOException {
2375 try {
2376 final byte[] buf = new byte[256];
2377 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2378 final String serial = new String(buf, 0, len);
2379 try {
2380 return Integer.parseInt(serial);
2381 } catch (NumberFormatException e) {
2382 throw new IOException("Bad serial number: " + serial);
2383 }
2384 } catch (ErrnoException e) {
2385 if (e.errno == OsConstants.ENODATA) {
2386 return -1;
2387 } else {
2388 throw e.rethrowAsIOException();
2389 }
2390 }
2391 }
2392
Amith Yamasani920ace02012-09-20 22:15:37 -07002393 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002394 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2395 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2396 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2397 }
2398
2399 int onShellCommand(Shell shell, String cmd) {
2400 if (cmd == null) {
2401 return shell.handleDefaultCommands(cmd);
2402 }
2403
2404 final PrintWriter pw = shell.getOutPrintWriter();
2405 try {
2406 switch(cmd) {
2407 case "list":
2408 return runList(pw);
2409 }
2410 } catch (RemoteException e) {
2411 pw.println("Remote exception: " + e);
2412 }
2413 return -1;
2414 }
2415
2416 private int runList(PrintWriter pw) throws RemoteException {
2417 final IActivityManager am = ActivityManagerNative.getDefault();
2418 final List<UserInfo> users = getUsers(false);
2419 if (users == null) {
2420 pw.println("Error: couldn't get users");
2421 return 1;
2422 } else {
2423 pw.println("Users:");
2424 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002425 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002426 pw.println("\t" + users.get(i).toString() + running);
2427 }
2428 return 0;
2429 }
2430 }
2431
2432 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002433 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2434 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2435 != PackageManager.PERMISSION_GRANTED) {
2436 pw.println("Permission Denial: can't dump UserManager from from pid="
2437 + Binder.getCallingPid()
2438 + ", uid=" + Binder.getCallingUid()
2439 + " without permission "
2440 + android.Manifest.permission.DUMP);
2441 return;
2442 }
2443
2444 long now = System.currentTimeMillis();
2445 StringBuilder sb = new StringBuilder();
2446 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002447 synchronized (mUsersLock) {
2448 pw.println("Users:");
2449 for (int i = 0; i < mUsers.size(); i++) {
2450 UserInfo user = mUsers.valueAt(i);
2451 if (user == null) {
2452 continue;
2453 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002454 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002455 pw.print(" "); pw.print(user);
2456 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002457 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002458 pw.print(" <removing> ");
2459 }
2460 if (user.partial) {
2461 pw.print(" <partial>");
2462 }
2463 pw.println();
2464 pw.print(" Created: ");
2465 if (user.creationTime == 0) {
2466 pw.println("<unknown>");
2467 } else {
2468 sb.setLength(0);
2469 TimeUtils.formatDuration(now - user.creationTime, sb);
2470 sb.append(" ago");
2471 pw.println(sb);
2472 }
2473 pw.print(" Last logged in: ");
2474 if (user.lastLoggedInTime == 0) {
2475 pw.println("<unknown>");
2476 } else {
2477 sb.setLength(0);
2478 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2479 sb.append(" ago");
2480 pw.println(sb);
2481 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002482 pw.print(" Has profile owner: ");
2483 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002484 pw.println(" Restrictions:");
2485 synchronized (mRestrictionsLock) {
2486 UserRestrictionsUtils.dumpRestrictions(
2487 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002488 pw.println(" Device policy local restrictions:");
2489 UserRestrictionsUtils.dumpRestrictions(
2490 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002491 pw.println(" Effective restrictions:");
2492 UserRestrictionsUtils.dumpRestrictions(
2493 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2494 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002495 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002496 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002497 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002498 pw.println(" Device policy global restrictions:");
2499 synchronized (mRestrictionsLock) {
2500 UserRestrictionsUtils
2501 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2502 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002503 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002504 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002505 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002506 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002507 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002508 synchronized (mUsersLock) {
2509 pw.println();
2510 pw.println(" Device managed: " + mIsDeviceManaged);
2511 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002512 }
2513 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002514
2515 final class MainHandler extends Handler {
2516
2517 @Override
2518 public void handleMessage(Message msg) {
2519 switch (msg.what) {
2520 case WRITE_USER_MSG:
2521 removeMessages(WRITE_USER_MSG, msg.obj);
2522 synchronized (mPackagesLock) {
2523 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002524 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002525 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002526 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002527 }
2528 }
2529 }
2530 }
2531 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002532
2533 /**
2534 * @param userId
2535 * @return whether the user has been initialized yet
2536 */
2537 boolean isInitialized(int userId) {
2538 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2539 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002540
2541 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002542 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002543 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2544 @Nullable Bundle globalRestrictions) {
2545 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2546 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002547 }
2548
2549 @Override
2550 public Bundle getBaseUserRestrictions(int userId) {
2551 synchronized (mRestrictionsLock) {
2552 return mBaseUserRestrictions.get(userId);
2553 }
2554 }
2555
2556 @Override
2557 public void setBaseUserRestrictionsByDpmsForMigration(
2558 int userId, Bundle baseRestrictions) {
2559 synchronized (mRestrictionsLock) {
2560 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002561 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002562 }
2563
Fyodor Kupolov82402752015-10-28 14:54:51 -07002564 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002565 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002566 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002567 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002568 } else {
2569 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2570 }
2571 }
2572 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002573
2574 @Override
2575 public boolean getUserRestriction(int userId, String key) {
2576 return getUserRestrictions(userId).getBoolean(key);
2577 }
2578
2579 @Override
2580 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2581 synchronized (mUserRestrictionsListeners) {
2582 mUserRestrictionsListeners.add(listener);
2583 }
2584 }
2585
2586 @Override
2587 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2588 synchronized (mUserRestrictionsListeners) {
2589 mUserRestrictionsListeners.remove(listener);
2590 }
2591 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002592
2593 @Override
2594 public void setDeviceManaged(boolean isManaged) {
2595 synchronized (mUsersLock) {
2596 mIsDeviceManaged = isManaged;
2597 }
2598 }
2599
2600 @Override
2601 public void setUserManaged(int userId, boolean isManaged) {
2602 synchronized (mUsersLock) {
2603 mIsUserManaged.put(userId, isManaged);
2604 }
2605 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002606 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002607
2608 private class Shell extends ShellCommand {
2609 @Override
2610 public int onCommand(String cmd) {
2611 return onShellCommand(this, cmd);
2612 }
2613
2614 @Override
2615 public void onHelp() {
2616 final PrintWriter pw = getOutPrintWriter();
2617 pw.println("User manager (user) commands:");
2618 pw.println(" help");
2619 pw.println(" Print this help text.");
2620 pw.println("");
2621 pw.println(" list");
2622 pw.println(" Prints all users on the system.");
2623 }
2624 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002625
2626 private static void debug(String message) {
2627 Log.d(LOG_TAG, message +
2628 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2629 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002630}