blob: 4497e4dd73b67611a1c12e8e782e15ccfcb3232f [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() {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100309 // Prune out any partially created, partially removed and ephemeral users.
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800310 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);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +0100315 if ((ui.partial || ui.guestToRemove || ui.isEphemeral()) && i != 0) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -0800316 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
Zoltan Szatmary-Ban3bbcedd2015-11-26 13:45:51 +0000848 public boolean hasBaseUserRestriction(String restrictionKey, int userId) {
849 checkManageUsersPermission("hasBaseUserRestriction");
850 synchronized (mRestrictionsLock) {
851 Bundle bundle = mBaseUserRestrictions.get(userId);
852 return (bundle != null && bundle.getBoolean(restrictionKey, false));
853 }
854 }
855
856 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700857 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700858 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700859 synchronized (mRestrictionsLock) {
860 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
861 // a copy.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800862 final Bundle newRestrictions = UserRestrictionsUtils.clone(
863 mBaseUserRestrictions.get(userId));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700864 newRestrictions.putBoolean(key, value);
865
Fyodor Kupolov82402752015-10-28 14:54:51 -0700866 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700867 }
868 }
869
Makoto Onuki068c54a2015-10-13 14:34:03 -0700870 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800871 * Optionally updating user restrictions, calculate the effective user restrictions and also
872 * propagate to other services and system settings.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700873 *
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800874 * @param newRestrictions User restrictions to set.
875 * If null, will not update user restrictions and only does the propagation.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700876 * @param userId target user ID.
877 */
878 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700879 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700880 @Nullable Bundle newRestrictions, int userId) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800881
882 final Bundle prevAppliedRestrictions = UserRestrictionsUtils.nonNull(
883 mAppliedUserRestrictions.get(userId));
884
885 // Update base restrictions.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700886 if (newRestrictions != null) {
887 // If newRestrictions == the current one, it's probably a bug.
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800888 final Bundle prevBaseRestrictions = mBaseUserRestrictions.get(userId);
889
890 Preconditions.checkState(prevBaseRestrictions != newRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700891 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
892 != newRestrictions);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800893
894 if (!UserRestrictionsUtils.areEqual(prevBaseRestrictions, newRestrictions)) {
895 mBaseUserRestrictions.put(userId, newRestrictions);
896 scheduleWriteUser(getUserInfoNoChecks(userId));
897 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700898 }
899
Fyodor Kupolov82402752015-10-28 14:54:51 -0700900 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700901
Makoto Onuki759a7632015-10-28 16:43:10 -0700902 mCachedEffectiveUserRestrictions.put(userId, effective);
903
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800904 // Apply the new restrictions.
Makoto Onuki4f160732015-10-27 17:15:38 -0700905 if (DBG) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800906 debug("Applying user restrictions: userId=" + userId
907 + " new=" + effective + " prev=" + prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700908 }
909
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800910 if (mAppOpsService != null) { // We skip it until system-ready.
911 final long token = Binder.clearCallingIdentity();
912 try {
913 mAppOpsService.setUserRestrictions(effective, userId);
914 } catch (RemoteException e) {
915 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
916 } finally {
917 Binder.restoreCallingIdentity(token);
918 }
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700919 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700920
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800921 propagateUserRestrictionsLR(userId, effective, prevAppliedRestrictions);
Makoto Onuki4f160732015-10-27 17:15:38 -0700922
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800923 mAppliedUserRestrictions.put(userId, new Bundle(effective));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700924 }
925
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800926 private void propagateUserRestrictionsLR(final int userId,
Makoto Onukid45a4a22015-11-02 17:17:38 -0800927 Bundle newRestrictions, Bundle prevRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800928 // Note this method doesn't touch any state, meaning it doesn't require mRestrictionsLock
929 // actually, but we still need some kind of synchronization otherwise we might end up
930 // calling listeners out-of-order, thus "LR".
931
932 if (UserRestrictionsUtils.areEqual(newRestrictions, prevRestrictions)) {
933 return;
934 }
Makoto Onukid45a4a22015-11-02 17:17:38 -0800935
936 final Bundle newRestrictionsFinal = new Bundle(newRestrictions);
937 final Bundle prevRestrictionsFinal = new Bundle(prevRestrictions);
938
939 mHandler.post(new Runnable() {
940 @Override
941 public void run() {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -0700942 UserRestrictionsUtils.applyUserRestrictions(
943 mContext, userId, newRestrictionsFinal, prevRestrictionsFinal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800944
Makoto Onukid45a4a22015-11-02 17:17:38 -0800945 final UserRestrictionsListener[] listeners;
946 synchronized (mUserRestrictionsListeners) {
947 listeners = new UserRestrictionsListener[mUserRestrictionsListeners.size()];
948 mUserRestrictionsListeners.toArray(listeners);
949 }
950 for (int i = 0; i < listeners.length; i++) {
951 listeners[i].onUserRestrictionsChanged(userId,
952 newRestrictionsFinal, prevRestrictionsFinal);
953 }
954 }
955 });
956 }
957
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800958 // Package private for the inner class.
959 void applyUserRestrictionsLR(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700960 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700961 }
962
963 @GuardedBy("mRestrictionsLock")
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800964 // Package private for the inner class.
965 void applyUserRestrictionsForAllUsersLR() {
966 if (DBG) {
967 debug("applyUserRestrictionsForAllUsersLR");
968 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700969 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700970 mCachedEffectiveUserRestrictions.clear();
971
Makoto Onuki068c54a2015-10-13 14:34:03 -0700972 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
973 // it on a handler.
974 final Runnable r = new Runnable() {
975 @Override
976 public void run() {
977 // Then get the list of running users.
978 final int[] runningUsers;
979 try {
980 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
981 } catch (RemoteException e) {
982 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
983 return;
984 }
985 // Then re-calculate the effective restrictions and apply, only for running users.
986 // It's okay if a new user has started after the getRunningUserIds() call,
987 // because we'll do the same thing (re-calculate the restrictions and apply)
988 // when we start a user.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700989 synchronized (mRestrictionsLock) {
990 for (int i = 0; i < runningUsers.length; i++) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -0800991 applyUserRestrictionsLR(runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700992 }
993 }
994 }
995 };
996 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700997 }
998
Amith Yamasani258848d2012-08-10 17:06:33 -0700999 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001000 * Check if we've hit the limit of how many users can be created.
1001 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001002 private boolean isUserLimitReached() {
1003 int count;
1004 synchronized (mUsersLock) {
1005 count = getAliveUsersExcludingGuestsCountLU();
1006 }
1007 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001008 }
1009
1010 @Override
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001011 public boolean canAddMoreManagedProfiles(int userId, boolean allowedToRemoveOne) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001012 checkManageUsersPermission("check if more managed profiles can be added.");
1013 if (ActivityManager.isLowRamDeviceStatic()) {
1014 return false;
1015 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -07001016 if (!mContext.getPackageManager().hasSystemFeature(
1017 PackageManager.FEATURE_MANAGED_USERS)) {
1018 return false;
1019 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001020 // Limit number of managed profiles that can be created
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001021 final int managedProfilesCount = getProfiles(userId, true).size() - 1;
1022 final int profilesRemovedCount = managedProfilesCount > 0 && allowedToRemoveOne ? 1 : 0;
1023 if (managedProfilesCount - profilesRemovedCount >= MAX_MANAGED_PROFILES) {
Nicolas Prevotb8186812015-08-06 15:00:03 +01001024 return false;
1025 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001026 synchronized(mUsersLock) {
1027 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +01001028 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001029 return false;
1030 }
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001031 int usersCountAfterRemoving = getAliveUsersExcludingGuestsCountLU()
1032 - profilesRemovedCount;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001033 // We allow creating a managed profile in the special case where there is only one user.
Nicolas Prevot07387fe2015-10-30 17:53:30 +00001034 return usersCountAfterRemoving == 1
1035 || usersCountAfterRemoving < UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -07001036 }
1037 }
1038
Fyodor Kupolov82402752015-10-28 14:54:51 -07001039 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -07001040 int aliveUserCount = 0;
1041 final int totalUserCount = mUsers.size();
1042 // Skip over users being removed
1043 for (int i = 0; i < totalUserCount; i++) {
1044 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001045 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -07001046 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -07001047 aliveUserCount++;
1048 }
1049 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001050 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001051 }
1052
1053 /**
Amith Yamasani195263742012-08-21 15:40:12 -07001054 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001055 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -07001056 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -07001057 *
1058 * @param message used as message if SecurityException is thrown
1059 * @throws SecurityException if the caller is not system or root
1060 */
Amith Yamasanibe465322014-04-24 13:45:17 -07001061 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001062 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -07001063 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001064 && ActivityManager.checkComponentPermission(
1065 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -07001066 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1067 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
1068 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001069 }
1070
Fyodor Kupolovb5013302015-04-17 17:59:14 -07001071 private static void checkSystemOrRoot(String message) {
1072 final int uid = Binder.getCallingUid();
1073 if (uid != Process.SYSTEM_UID && uid != 0) {
1074 throw new SecurityException("Only system may call: " + message);
1075 }
1076 }
1077
Fyodor Kupolov82402752015-10-28 14:54:51 -07001078 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001079 try {
1080 File dir = new File(mUsersDir, Integer.toString(info.id));
1081 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +01001082 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001083 if (!dir.exists()) {
1084 dir.mkdir();
1085 FileUtils.setPermissions(
1086 dir.getPath(),
1087 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1088 -1, -1);
1089 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001090 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +01001091 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
1092 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -07001093 info.iconPath = file.getAbsolutePath();
1094 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -07001095 try {
1096 os.close();
1097 } catch (IOException ioe) {
1098 // What the ... !
1099 }
Adrian Roos1bdff912015-02-17 15:51:35 +01001100 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001101 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001102 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001103 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001104 }
1105
Amith Yamasani0b285492011-04-14 17:35:23 -07001106 /**
1107 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
1108 * cache it elsewhere.
1109 * @return the array of user ids.
1110 */
Dianne Hackborn1676c852012-09-10 14:52:30 -07001111 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001112 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001113 return mUserIds;
1114 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001115 }
1116
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001117 private void readUserListLP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001118 if (!mUserListFile.exists()) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001119 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001120 return;
1121 }
1122 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001123 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001124 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001125 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001126 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001127 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001128 int type;
1129 while ((type = parser.next()) != XmlPullParser.START_TAG
1130 && type != XmlPullParser.END_DOCUMENT) {
1131 ;
1132 }
1133
1134 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001135 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001136 fallbackToSingleUserLP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001137 return;
1138 }
1139
Amith Yamasani2a003292012-08-14 18:25:45 -07001140 mNextSerialNumber = -1;
1141 if (parser.getName().equals(TAG_USERS)) {
1142 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
1143 if (lastSerialNumber != null) {
1144 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
1145 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001146 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
1147 if (versionNumber != null) {
1148 mUserVersion = Integer.parseInt(versionNumber);
1149 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001150 }
1151
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001152 final Bundle newDevicePolicyGlobalUserRestrictions = new Bundle();
1153
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001154 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301155 if (type == XmlPullParser.START_TAG) {
1156 final String name = parser.getName();
1157 if (name.equals(TAG_USER)) {
1158 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001159 UserInfo user = readUserLP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001160
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301161 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001162 synchronized (mUsersLock) {
1163 mUsers.put(user.id, user);
1164 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1165 mNextSerialNumber = user.id + 1;
1166 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301167 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001168 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301169 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001170 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1171 && type != XmlPullParser.END_TAG) {
1172 if (type == XmlPullParser.START_TAG) {
1173 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001174 synchronized (mGuestRestrictions) {
1175 UserRestrictionsUtils
1176 .readRestrictions(parser, mGuestRestrictions);
1177 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001178 } else if (parser.getName().equals(TAG_DEVICE_POLICY_RESTRICTIONS)
1179 ) {
1180 UserRestrictionsUtils.readRestrictions(parser,
1181 newDevicePolicyGlobalUserRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001182 }
1183 break;
1184 }
1185 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001186 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001187 }
1188 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001189 synchronized (mRestrictionsLock) {
1190 mDevicePolicyGlobalUserRestrictions = newDevicePolicyGlobalUserRestrictions;
1191 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001192 updateUserIds();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001193 upgradeIfNecessaryLP();
1194 } catch (IOException | XmlPullParserException e) {
1195 fallbackToSingleUserLP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001196 } finally {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001197 IoUtils.closeQuietly(fis);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001198 }
1199 }
1200
Amith Yamasani6f34b412012-10-22 18:19:27 -07001201 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001202 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001203 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001204 private void upgradeIfNecessaryLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001205 final int originalVersion = mUserVersion;
Amith Yamasani6f34b412012-10-22 18:19:27 -07001206 int userVersion = mUserVersion;
1207 if (userVersion < 1) {
1208 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001209 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001210 if ("Primary".equals(user.name)) {
1211 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Makoto Onuki9e935a32015-11-06 14:24:24 -08001212 scheduleWriteUser(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001213 }
1214 userVersion = 1;
1215 }
1216
Amith Yamasanibc9625052012-11-15 14:39:18 -08001217 if (userVersion < 2) {
1218 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001219 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001220 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1221 user.flags |= UserInfo.FLAG_INITIALIZED;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001222 scheduleWriteUser(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001223 }
1224 userVersion = 2;
1225 }
1226
Amith Yamasani350962c2013-08-06 11:18:53 -07001227
Amith Yamasani5e486f52013-08-07 11:06:44 -07001228 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001229 userVersion = 4;
1230 }
1231
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001232 if (userVersion < 5) {
1233 initDefaultGuestRestrictions();
1234 userVersion = 5;
1235 }
1236
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001237 if (userVersion < 6) {
1238 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001239 synchronized (mUsersLock) {
1240 for (int i = 0; i < mUsers.size(); i++) {
1241 UserInfo user = mUsers.valueAt(i);
1242 // In non-split mode, only user 0 can have restricted profiles
1243 if (!splitSystemUser && user.isRestricted()
1244 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1245 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
Makoto Onuki9e935a32015-11-06 14:24:24 -08001246 scheduleWriteUser(user);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001247 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001248 }
1249 }
1250 userVersion = 6;
1251 }
1252
Amith Yamasani6f34b412012-10-22 18:19:27 -07001253 if (userVersion < USER_VERSION) {
1254 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1255 + USER_VERSION);
1256 } else {
1257 mUserVersion = userVersion;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001258
1259 if (originalVersion < mUserVersion) {
1260 writeUserListLP();
1261 }
Amith Yamasani6f34b412012-10-22 18:19:27 -07001262 }
1263 }
1264
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001265 private void fallbackToSingleUserLP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001266 int flags = UserInfo.FLAG_INITIALIZED;
1267 // In split system user mode, the admin and primary flags are assigned to the first human
1268 // user.
1269 if (!UserManager.isSplitSystemUser()) {
1270 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1271 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001272 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001273 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001274 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001275 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001276 synchronized (mUsersLock) {
1277 mUsers.put(system.id, system);
1278 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001279 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001280 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001281
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001282 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001283 synchronized (mRestrictionsLock) {
1284 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1285 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001286
Fyodor Kupolov82402752015-10-28 14:54:51 -07001287 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001288 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001289
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001290 writeUserListLP();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001291 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001292 }
1293
Makoto Onuki9e935a32015-11-06 14:24:24 -08001294 private void scheduleWriteUser(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001295 if (DBG) {
1296 debug("scheduleWriteUser");
1297 }
Makoto Onuki9e935a32015-11-06 14:24:24 -08001298 // No need to wrap it within a lock -- worst case, we'll just post the same message
1299 // twice.
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001300 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1301 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1302 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1303 }
1304 }
1305
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001306 /*
1307 * Writes the user file in this format:
1308 *
1309 * <user flags="20039023" id="0">
1310 * <name>Primary</name>
1311 * </user>
1312 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001313 private void writeUserLP(UserInfo userInfo) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001314 if (DBG) {
1315 debug("writeUserLP " + userInfo);
1316 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001317 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001318 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001319 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001320 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001321 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1322
1323 // XmlSerializer serializer = XmlUtils.serializerInstance();
1324 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001325 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001326 serializer.startDocument(null, true);
1327 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1328
1329 serializer.startTag(null, TAG_USER);
1330 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001331 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001332 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001333 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1334 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1335 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001336 if (userInfo.iconPath != null) {
1337 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1338 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001339 if (userInfo.partial) {
1340 serializer.attribute(null, ATTR_PARTIAL, "true");
1341 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001342 if (userInfo.guestToRemove) {
1343 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1344 }
Kenny Guy2a764942014-04-02 13:29:20 +01001345 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1346 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1347 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001348 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001349 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1350 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1351 Integer.toString(userInfo.restrictedProfileParentId));
1352 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001353 serializer.startTag(null, TAG_NAME);
1354 serializer.text(userInfo.name);
1355 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001356 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001357 UserRestrictionsUtils.writeRestrictions(serializer,
1358 mBaseUserRestrictions.get(userInfo.id), TAG_RESTRICTIONS);
1359 UserRestrictionsUtils.writeRestrictions(serializer,
1360 mDevicePolicyLocalUserRestrictions.get(userInfo.id),
1361 TAG_DEVICE_POLICY_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001362 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001363 serializer.endTag(null, TAG_USER);
1364
1365 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001366 userFile.finishWrite(fos);
1367 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001368 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001369 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001370 }
1371 }
1372
1373 /*
1374 * Writes the user list file in this format:
1375 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001376 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001377 * <user id="0"></user>
1378 * <user id="2"></user>
1379 * </users>
1380 */
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001381 private void writeUserListLP() {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001382 if (DBG) {
1383 debug("writeUserList");
1384 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001385 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001386 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001387 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001388 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001389 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1390
1391 // XmlSerializer serializer = XmlUtils.serializerInstance();
1392 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001393 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001394 serializer.startDocument(null, true);
1395 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1396
1397 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001398 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001399 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001400
Adam Lesinskieddeb492014-09-08 17:50:03 -07001401 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001402 synchronized (mGuestRestrictions) {
1403 UserRestrictionsUtils
1404 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
1405 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301406 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001407 synchronized (mRestrictionsLock) {
1408 UserRestrictionsUtils.writeRestrictions(serializer,
1409 mDevicePolicyGlobalUserRestrictions, TAG_DEVICE_POLICY_RESTRICTIONS);
1410 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001411 int[] userIdsToWrite;
1412 synchronized (mUsersLock) {
1413 userIdsToWrite = new int[mUsers.size()];
1414 for (int i = 0; i < userIdsToWrite.length; i++) {
1415 UserInfo user = mUsers.valueAt(i);
1416 userIdsToWrite[i] = user.id;
1417 }
1418 }
1419 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001420 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001421 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001422 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001423 }
1424
1425 serializer.endTag(null, TAG_USERS);
1426
1427 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001428 userListFile.finishWrite(fos);
1429 } catch (Exception e) {
1430 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001431 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001432 }
1433 }
1434
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001435 private UserInfo readUserLP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001436 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001437 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001438 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001439 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001440 long creationTime = 0L;
1441 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001442 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001443 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001444 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001445 boolean guestToRemove = false;
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001446 Bundle baseRestrictions = new Bundle();
1447 Bundle localRestrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001448
1449 FileInputStream fis = null;
1450 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001451 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001452 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001453 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001454 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001455 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001456 int type;
1457 while ((type = parser.next()) != XmlPullParser.START_TAG
1458 && type != XmlPullParser.END_DOCUMENT) {
1459 ;
1460 }
1461
1462 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001463 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001464 return null;
1465 }
1466
1467 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001468 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1469 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001470 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001471 return null;
1472 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001473 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1474 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001475 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001476 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1477 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001478 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1479 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001480 restrictedProfileParentId = readIntAttribute(parser,
1481 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001482 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1483 if ("true".equals(valueString)) {
1484 partial = true;
1485 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001486 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1487 if ("true".equals(valueString)) {
1488 guestToRemove = true;
1489 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001490
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001491 int outerDepth = parser.getDepth();
1492 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1493 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1494 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1495 continue;
1496 }
1497 String tag = parser.getName();
1498 if (TAG_NAME.equals(tag)) {
1499 type = parser.next();
1500 if (type == XmlPullParser.TEXT) {
1501 name = parser.getText();
1502 }
1503 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001504 UserRestrictionsUtils.readRestrictions(parser, baseRestrictions);
1505 } else if (TAG_DEVICE_POLICY_RESTRICTIONS.equals(tag)) {
1506 UserRestrictionsUtils.readRestrictions(parser, localRestrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001507 }
1508 }
1509 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001510
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001511 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001512 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001513 userInfo.creationTime = creationTime;
1514 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001515 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001516 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001517 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001518 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001519 synchronized (mRestrictionsLock) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001520 mBaseUserRestrictions.put(id, baseRestrictions);
1521 mDevicePolicyLocalUserRestrictions.put(id, localRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001522 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001523 return userInfo;
1524
1525 } catch (IOException ioe) {
1526 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001527 } finally {
1528 if (fis != null) {
1529 try {
1530 fis.close();
1531 } catch (IOException e) {
1532 }
1533 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001534 }
1535 return null;
1536 }
1537
Amith Yamasani920ace02012-09-20 22:15:37 -07001538 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1539 String valueString = parser.getAttributeValue(null, attr);
1540 if (valueString == null) return defaultValue;
1541 try {
1542 return Integer.parseInt(valueString);
1543 } catch (NumberFormatException nfe) {
1544 return defaultValue;
1545 }
1546 }
1547
1548 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1549 String valueString = parser.getAttributeValue(null, attr);
1550 if (valueString == null) return defaultValue;
1551 try {
1552 return Long.parseLong(valueString);
1553 } catch (NumberFormatException nfe) {
1554 return defaultValue;
1555 }
1556 }
1557
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001558 private boolean isPackageInstalled(String pkg, int userId) {
1559 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1560 PackageManager.GET_UNINSTALLED_PACKAGES,
1561 userId);
1562 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1563 return false;
1564 }
1565 return true;
1566 }
1567
Amith Yamasanib82add22013-07-09 11:24:44 -07001568 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001569 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001570 * Does not do any permissions checking.
1571 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001572 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001573 synchronized (mPackagesLock) {
1574 File dir = Environment.getUserSystemDirectory(userId);
1575 String[] files = dir.list();
1576 if (files == null) return;
1577 for (String fileName : files) {
1578 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1579 File resFile = new File(dir, fileName);
1580 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001581 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001582 }
1583 }
1584 }
1585 }
1586 }
1587
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001588 /**
1589 * Removes the app restrictions file for a specific package and user id, if it exists.
1590 */
1591 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1592 synchronized (mPackagesLock) {
1593 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001594 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001595 if (resFile.exists()) {
1596 resFile.delete();
1597 }
1598 }
1599 }
1600
Kenny Guya52dc3e2014-02-11 15:33:14 +00001601 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001602 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001603 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001604 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001605 }
1606
Amith Yamasani258848d2012-08-10 17:06:33 -07001607 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001608 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001609 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001610 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001611 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001612
Jessica Hummelbe81c802014-04-22 15:49:22 +01001613 private UserInfo createUserInternal(String name, int flags, int parentId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001614 if (hasUserRestriction(UserManager.DISALLOW_ADD_USER, UserHandle.getCallingUserId())) {
Julia Reynolds75175022014-06-26 16:35:00 -04001615 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1616 return null;
1617 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001618 if (ActivityManager.isLowRamDeviceStatic()) {
1619 return null;
1620 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001621 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001622 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001623 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001624 final long ident = Binder.clearCallingIdentity();
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001625 UserInfo userInfo;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001626 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001627 try {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001628 synchronized (mPackagesLock) {
1629 UserInfo parent = null;
1630 if (parentId != UserHandle.USER_NULL) {
1631 synchronized (mUsersLock) {
1632 parent = getUserInfoLU(parentId);
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001633 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001634 if (parent == null) return null;
1635 }
1636 if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
1637 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
1638 return null;
1639 }
1640 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
1641 // If we're not adding a guest user or a managed profile and the limit has
1642 // been reached, cannot add a user.
1643 return null;
1644 }
1645 // If we're adding a guest and there already exists one, bail.
1646 if (isGuest && findCurrentGuestUser() != null) {
1647 return null;
1648 }
1649 // In legacy mode, restricted profile's parent can only be the owner user
1650 if (isRestricted && !UserManager.isSplitSystemUser()
1651 && (parentId != UserHandle.USER_SYSTEM)) {
1652 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1653 return null;
1654 }
1655 if (isRestricted && UserManager.isSplitSystemUser()) {
1656 if (parent == null) {
1657 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1658 + "specified");
Nicolas Prevot12678a92015-05-13 12:15:03 -07001659 return null;
1660 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001661 if (!parent.canHaveProfile()) {
1662 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1663 + "created for the specified parent user id " + parentId);
Amith Yamasani95ab7842014-08-11 17:09:26 -07001664 return null;
1665 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001666 }
1667 // In split system user mode, we assign the first human user the primary flag.
1668 // And if there is no device owner, we also assign the admin flag to primary user.
1669 if (UserManager.isSplitSystemUser()
1670 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
1671 flags |= UserInfo.FLAG_PRIMARY;
Makoto Onukie7927da2015-11-25 10:05:17 -08001672 synchronized (mUsersLock) {
1673 if (!mIsDeviceManaged) {
1674 flags |= UserInfo.FLAG_ADMIN;
1675 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001676 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001677 }
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001678
1679 if (parent != null && parent.isEphemeral()) {
1680 flags |= UserInfo.FLAG_EPHEMERAL;
1681 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001682 userId = getNextAvailableId();
1683 userInfo = new UserInfo(userId, name, null, flags);
1684 userInfo.serialNumber = mNextSerialNumber++;
1685 long now = System.currentTimeMillis();
1686 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
1687 userInfo.partial = true;
1688 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
1689 synchronized (mUsersLock) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001690 mUsers.put(userId, userInfo);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001691 }
1692 writeUserListLP();
1693 if (parent != null) {
1694 if (isManagedProfile) {
1695 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1696 parent.profileGroupId = parent.id;
1697 writeUserLP(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001698 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001699 userInfo.profileGroupId = parent.profileGroupId;
1700 } else if (isRestricted) {
1701 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1702 parent.restrictedProfileParentId = parent.id;
1703 writeUserLP(parent);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001704 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001705 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001706 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001707 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001708 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001709 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001710 storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001711 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1712 final String volumeUuid = vol.getFsUuid();
1713 try {
1714 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01001715 storage.prepareUserStorage(
1716 volumeUuid, userId, userInfo.serialNumber, userInfo.isEphemeral());
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001717 enforceSerialNumber(userDir, userInfo.serialNumber);
1718 } catch (IOException e) {
1719 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1720 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001721 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001722 mPm.createNewUser(userId);
1723 userInfo.partial = false;
1724 synchronized (mPackagesLock) {
1725 writeUserLP(userInfo);
1726 }
1727 updateUserIds();
1728 Bundle restrictions = new Bundle();
Fyodor Kupolove04462c2015-11-30 15:02:53 -08001729 if (isGuest) {
1730 synchronized (mGuestRestrictions) {
1731 restrictions.putAll(mGuestRestrictions);
1732 }
1733 }
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001734 synchronized (mRestrictionsLock) {
1735 mBaseUserRestrictions.append(userId, restrictions);
1736 }
1737 mPm.newUserCreated(userId);
1738 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1739 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1740 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1741 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001742 } finally {
1743 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001744 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001745 return userInfo;
1746 }
1747
Amith Yamasani0b285492011-04-14 17:35:23 -07001748 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001749 * @hide
1750 */
1751 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1752 checkManageUsersPermission("setupRestrictedProfile");
1753 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1754 if (user == null) {
1755 return null;
1756 }
1757 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1758 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1759 // the putIntForUser() will fail.
1760 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1761 android.provider.Settings.Secure.LOCATION_MODE,
1762 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1763 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1764 return user;
1765 }
1766
1767 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001768 * Find the current guest user. If the Guest user is partial,
1769 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001770 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001771 private UserInfo findCurrentGuestUser() {
1772 synchronized (mUsersLock) {
1773 final int size = mUsers.size();
1774 for (int i = 0; i < size; i++) {
1775 final UserInfo user = mUsers.valueAt(i);
1776 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1777 return user;
1778 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001779 }
1780 }
1781 return null;
1782 }
1783
1784 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001785 * Mark this guest user for deletion to allow us to create another guest
1786 * and switch to that user before actually removing this guest.
1787 * @param userHandle the userid of the current guest
1788 * @return whether the user could be marked for deletion
1789 */
1790 public boolean markGuestForDeletion(int userHandle) {
1791 checkManageUsersPermission("Only the system can remove users");
1792 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1793 UserManager.DISALLOW_REMOVE_USER, false)) {
1794 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1795 return false;
1796 }
1797
1798 long ident = Binder.clearCallingIdentity();
1799 try {
1800 final UserInfo user;
1801 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001802 synchronized (mUsersLock) {
1803 user = mUsers.get(userHandle);
1804 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1805 return false;
1806 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001807 }
1808 if (!user.isGuest()) {
1809 return false;
1810 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001811 // We set this to a guest user that is to be removed. This is a temporary state
1812 // where we are allowed to add new Guest users, even if this one is still not
1813 // removed. This user will still show up in getUserInfo() calls.
1814 // If we don't get around to removing this Guest user, it will be purged on next
1815 // startup.
1816 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001817 // Mark it as disabled, so that it isn't returned any more when
1818 // profiles are queried.
1819 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001820 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001821 }
1822 } finally {
1823 Binder.restoreCallingIdentity(ident);
1824 }
1825 return true;
1826 }
1827
1828 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001829 * Removes a user and all data directories created for that user. This method should be called
1830 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001831 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001832 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001833 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001834 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001835 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1836 UserManager.DISALLOW_REMOVE_USER, false)) {
1837 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1838 return false;
1839 }
1840
Kenny Guyee58b4f2014-05-23 15:19:53 +01001841 long ident = Binder.clearCallingIdentity();
1842 try {
1843 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001844 int currentUser = ActivityManager.getCurrentUser();
1845 if (currentUser == userHandle) {
1846 Log.w(LOG_TAG, "Current user cannot be removed");
1847 return false;
1848 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001849 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001850 synchronized (mUsersLock) {
1851 user = mUsers.get(userHandle);
1852 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1853 return false;
1854 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001855
Fyodor Kupolov82402752015-10-28 14:54:51 -07001856 // We remember deleted user IDs to prevent them from being
1857 // reused during the current boot; they can still be reused
1858 // after a reboot.
1859 mRemovingUserIds.put(userHandle, true);
1860 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001861
Kenny Guyee58b4f2014-05-23 15:19:53 +01001862 try {
1863 mAppOpsService.removeUser(userHandle);
1864 } catch (RemoteException e) {
1865 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1866 }
1867 // Set this to a partially created user, so that the user will be purged
1868 // on next startup, in case the runtime stops now before stopping and
1869 // removing the user completely.
1870 user.partial = true;
1871 // Mark it as disabled, so that it isn't returned any more when
1872 // profiles are queried.
1873 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001874 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001875 }
1876
1877 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1878 && user.isManagedProfile()) {
1879 // Send broadcast to notify system that the user removed was a
1880 // managed user.
1881 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1882 }
1883
1884 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1885 int res;
1886 try {
Fyodor Kupolov9cbfc9e2015-10-07 15:52:33 -07001887 res = ActivityManagerNative.getDefault().stopUser(userHandle, /* force= */ true,
1888 new IStopUserCallback.Stub() {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001889 @Override
1890 public void userStopped(int userId) {
1891 finishRemoveUser(userId);
1892 }
1893 @Override
1894 public void userStopAborted(int userId) {
1895 }
1896 });
1897 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001898 return false;
1899 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001900 return res == ActivityManager.USER_OP_SUCCESS;
1901 } finally {
1902 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001903 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001904 }
1905
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001906 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001907 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001908 // Let other services shutdown any activity and clean up their state before completely
1909 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001910 long ident = Binder.clearCallingIdentity();
1911 try {
1912 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1913 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001914 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1915 android.Manifest.permission.MANAGE_USERS,
1916
1917 new BroadcastReceiver() {
1918 @Override
1919 public void onReceive(Context context, Intent intent) {
1920 if (DBG) {
1921 Slog.i(LOG_TAG,
1922 "USER_REMOVED broadcast sent, cleaning up user data "
1923 + userHandle);
1924 }
1925 new Thread() {
1926 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001927 // Clean up any ActivityManager state
1928 LocalServices.getService(ActivityManagerInternal.class)
1929 .onUserRemoved(userHandle);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001930 removeUserState(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001931 }
1932 }.start();
1933 }
1934 },
1935
1936 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001937 } finally {
1938 Binder.restoreCallingIdentity(ident);
1939 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001940 }
1941
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001942 private void removeUserState(final int userHandle) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001943 mContext.getSystemService(StorageManager.class).destroyUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001944 // Cleanup package manager settings
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001945 mPm.cleanUpUser(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001946
1947 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001948 synchronized (mUsersLock) {
1949 mUsers.remove(userHandle);
Makoto Onukie7927da2015-11-25 10:05:17 -08001950 mIsUserManaged.delete(userHandle);
1951 }
1952 synchronized (mRestrictionsLock) {
1953 mBaseUserRestrictions.remove(userHandle);
1954 mAppliedUserRestrictions.remove(userHandle);
1955 mCachedEffectiveUserRestrictions.remove(userHandle);
1956 mDevicePolicyLocalUserRestrictions.remove(userHandle);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001957 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001958 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001959 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001960 userFile.delete();
1961 // Update the user list
Fyodor Kupolove80085d2015-11-06 18:21:39 -08001962 synchronized (mPackagesLock) {
1963 writeUserListLP();
1964 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001965 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001966 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1967 }
1968
Amith Yamasani61f57372012-08-31 12:12:28 -07001969 private void removeDirectoryRecursive(File parent) {
1970 if (parent.isDirectory()) {
1971 String[] files = parent.list();
1972 for (String filename : files) {
1973 File child = new File(parent, filename);
1974 removeDirectoryRecursive(child);
1975 }
1976 }
1977 parent.delete();
1978 }
1979
Kenny Guyf8d3a232014-05-15 16:09:52 +01001980 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001981 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001982 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1983 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001984 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1985 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001986 }
1987
Amith Yamasani2a003292012-08-14 18:25:45 -07001988 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001989 public Bundle getApplicationRestrictions(String packageName) {
1990 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1991 }
1992
1993 @Override
1994 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001995 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001996 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001997 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001998 }
1999 synchronized (mPackagesLock) {
2000 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002001 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002002 }
2003 }
2004
2005 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002006 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002007 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01002008 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002009 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01002010 if (restrictions == null || restrictions.isEmpty()) {
2011 cleanAppRestrictionsForPackage(packageName, userId);
2012 } else {
2013 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07002014 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01002015 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002016 }
Robin Lee66e5d962014-04-09 16:44:21 +01002017
Kenny Guyd21b2182014-07-17 16:38:55 +01002018 if (isPackageInstalled(packageName, userId)) {
2019 // Notify package of changes via an intent - only sent to explicitly registered receivers.
2020 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
2021 changeIntent.setPackage(packageName);
2022 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2023 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
2024 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002025 }
2026
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002027 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002028 mHandler.post(new Runnable() {
2029 @Override
2030 public void run() {
2031 List<ApplicationInfo> apps =
2032 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
2033 userHandle).getList();
2034 final long ident = Binder.clearCallingIdentity();
2035 try {
2036 for (ApplicationInfo appInfo : apps) {
2037 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002038 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
2039 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07002040 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002041 userHandle);
2042 }
2043 }
2044 } finally {
2045 Binder.restoreCallingIdentity(ident);
2046 }
2047 }
2048 });
2049 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002050 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07002051 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002052 try {
2053 return mContext.getPackageManager().getApplicationInfo(packageName,
2054 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
2055 } catch (NameNotFoundException nnfe) {
2056 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07002057 } finally {
2058 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002059 }
2060 }
2061
Fyodor Kupolov82402752015-10-28 14:54:51 -07002062 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002063 AtomicFile restrictionsFile =
2064 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
2065 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002066 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002067 }
2068
2069 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002070 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002071 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002072 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002073 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07002074 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07002075 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002076
2077 FileInputStream fis = null;
2078 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002079 fis = restrictionsFile.openRead();
2080 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002081 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002082 XmlUtils.nextElement(parser);
2083 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002084 Slog.e(LOG_TAG, "Unable to read restrictions file "
2085 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002086 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002087 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002088 while (parser.next() != XmlPullParser.END_DOCUMENT) {
2089 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002090 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002091 } catch (IOException|XmlPullParserException e) {
2092 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002093 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002094 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002095 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002096 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002097 }
2098
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002099 private static void readEntry(Bundle restrictions, ArrayList<String> values,
2100 XmlPullParser parser) throws XmlPullParserException, IOException {
2101 int type = parser.getEventType();
2102 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
2103 String key = parser.getAttributeValue(null, ATTR_KEY);
2104 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
2105 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
2106 if (multiple != null) {
2107 values.clear();
2108 int count = Integer.parseInt(multiple);
2109 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
2110 if (type == XmlPullParser.START_TAG
2111 && parser.getName().equals(TAG_VALUE)) {
2112 values.add(parser.nextText().trim());
2113 count--;
2114 }
2115 }
2116 String [] valueStrings = new String[values.size()];
2117 values.toArray(valueStrings);
2118 restrictions.putStringArray(key, valueStrings);
2119 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
2120 restrictions.putBundle(key, readBundleEntry(parser, values));
2121 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
2122 final int outerDepth = parser.getDepth();
2123 ArrayList<Bundle> bundleList = new ArrayList<>();
2124 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2125 Bundle childBundle = readBundleEntry(parser, values);
2126 bundleList.add(childBundle);
2127 }
2128 restrictions.putParcelableArray(key,
2129 bundleList.toArray(new Bundle[bundleList.size()]));
2130 } else {
2131 String value = parser.nextText().trim();
2132 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
2133 restrictions.putBoolean(key, Boolean.parseBoolean(value));
2134 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
2135 restrictions.putInt(key, Integer.parseInt(value));
2136 } else {
2137 restrictions.putString(key, value);
2138 }
2139 }
2140 }
2141 }
2142
2143 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
2144 throws IOException, XmlPullParserException {
2145 Bundle childBundle = new Bundle();
2146 final int outerDepth = parser.getDepth();
2147 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
2148 readEntry(childBundle, values, parser);
2149 }
2150 return childBundle;
2151 }
2152
Fyodor Kupolov82402752015-10-28 14:54:51 -07002153 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07002154 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002155 AtomicFile restrictionsFile = new AtomicFile(
2156 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07002157 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002158 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002159 }
2160
2161 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07002162 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002163 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002164 try {
2165 fos = restrictionsFile.startWrite();
2166 final BufferedOutputStream bos = new BufferedOutputStream(fos);
2167
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002168 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002169 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002170 serializer.startDocument(null, true);
2171 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2172
2173 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002174 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002175 serializer.endTag(null, TAG_RESTRICTIONS);
2176
2177 serializer.endDocument();
2178 restrictionsFile.finishWrite(fos);
2179 } catch (Exception e) {
2180 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07002181 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
2182 }
2183 }
2184
2185 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
2186 throws IOException {
2187 for (String key : restrictions.keySet()) {
2188 Object value = restrictions.get(key);
2189 serializer.startTag(null, TAG_ENTRY);
2190 serializer.attribute(null, ATTR_KEY, key);
2191
2192 if (value instanceof Boolean) {
2193 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
2194 serializer.text(value.toString());
2195 } else if (value instanceof Integer) {
2196 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2197 serializer.text(value.toString());
2198 } else if (value == null || value instanceof String) {
2199 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2200 serializer.text(value != null ? (String) value : "");
2201 } else if (value instanceof Bundle) {
2202 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2203 writeBundle((Bundle) value, serializer);
2204 } else if (value instanceof Parcelable[]) {
2205 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2206 Parcelable[] array = (Parcelable[]) value;
2207 for (Parcelable parcelable : array) {
2208 if (!(parcelable instanceof Bundle)) {
2209 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2210 }
2211 serializer.startTag(null, TAG_ENTRY);
2212 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2213 writeBundle((Bundle) parcelable, serializer);
2214 serializer.endTag(null, TAG_ENTRY);
2215 }
2216 } else {
2217 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2218 String[] values = (String[]) value;
2219 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2220 for (String choice : values) {
2221 serializer.startTag(null, TAG_VALUE);
2222 serializer.text(choice != null ? choice : "");
2223 serializer.endTag(null, TAG_VALUE);
2224 }
2225 }
2226 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002227 }
2228 }
2229
2230 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002231 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002232 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002233 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002234 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002235 }
2236 }
2237
2238 @Override
2239 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002240 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002241 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002242 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002243 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002244 }
2245 // Not found
2246 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002247 }
2248 }
2249
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002250 @Override
2251 public long getUserCreationTime(int userHandle) {
2252 int callingUserId = UserHandle.getCallingUserId();
2253 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002254 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002255 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002256 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002257 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002258 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002259 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002260 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002261 }
2262 }
2263 }
2264 if (userInfo == null) {
2265 throw new SecurityException("userHandle can only be the calling user or a managed "
2266 + "profile associated with this user");
2267 }
2268 return userInfo.creationTime;
2269 }
2270
Amith Yamasani0b285492011-04-14 17:35:23 -07002271 /**
2272 * Caches the list of user ids in an array, adjusting the array size when necessary.
2273 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002274 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002275 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002276 synchronized (mUsersLock) {
2277 final int userSize = mUsers.size();
2278 for (int i = 0; i < userSize; i++) {
2279 if (!mUsers.valueAt(i).partial) {
2280 num++;
2281 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002282 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002283 final int[] newUsers = new int[num];
2284 int n = 0;
2285 for (int i = 0; i < userSize; i++) {
2286 if (!mUsers.valueAt(i).partial) {
2287 newUsers[n++] = mUsers.keyAt(i);
2288 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002289 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002290 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002291 }
2292 }
2293
2294 /**
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002295 * Called right before a user starts. This will not be called for the system user.
2296 */
2297 public void onBeforeStartUser(int userId) {
2298 synchronized (mRestrictionsLock) {
2299 applyUserRestrictionsLR(userId);
2300 }
2301 }
2302
2303 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002304 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002305 * @param userId the user that was just foregrounded
2306 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002307 public void onUserForeground(int userId) {
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002308 UserInfo user = getUserInfoNoChecks(userId);
2309 if (user == null || user.partial) {
2310 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2311 return;
2312 }
2313 long now = System.currentTimeMillis();
2314 if (now > EPOCH_PLUS_30_YEARS) {
2315 user.lastLoggedInTime = now;
2316 scheduleWriteUser(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002317 }
2318 }
2319
2320 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002321 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002322 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2323 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002324 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002325 private int getNextAvailableId() {
2326 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002327 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002328 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002329 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002330 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002331 }
2332 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002333 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002334 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002335 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002336 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002337
Amith Yamasanifc95e702013-09-26 13:20:17 -07002338 private String packageToRestrictionsFileName(String packageName) {
2339 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2340 }
2341
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002342 /**
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002343 * Enforce that serial number stored in user directory inode matches the
2344 * given expected value. Gracefully sets the serial number if currently
2345 * undefined.
2346 *
2347 * @throws IOException when problem extracting serial number, or serial
2348 * number is mismatched.
2349 */
2350 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2351 final int foundSerial = getSerialNumber(file);
2352 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2353
2354 if (foundSerial == -1) {
2355 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2356 try {
2357 setSerialNumber(file, serialNumber);
2358 } catch (IOException e) {
2359 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2360 }
2361
2362 } else if (foundSerial != serialNumber) {
2363 throw new IOException("Found serial number " + foundSerial
2364 + " doesn't match expected " + serialNumber);
2365 }
2366 }
2367
2368 /**
2369 * Set serial number stored in user directory inode.
2370 *
2371 * @throws IOException if serial number was already set
2372 */
2373 private static void setSerialNumber(File file, int serialNumber)
2374 throws IOException {
2375 try {
2376 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2377 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2378 } catch (ErrnoException e) {
2379 throw e.rethrowAsIOException();
2380 }
2381 }
2382
2383 /**
2384 * Return serial number stored in user directory inode.
2385 *
2386 * @return parsed serial number, or -1 if not set
2387 */
2388 private static int getSerialNumber(File file) throws IOException {
2389 try {
2390 final byte[] buf = new byte[256];
2391 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2392 final String serial = new String(buf, 0, len);
2393 try {
2394 return Integer.parseInt(serial);
2395 } catch (NumberFormatException e) {
2396 throw new IOException("Bad serial number: " + serial);
2397 }
2398 } catch (ErrnoException e) {
2399 if (e.errno == OsConstants.ENODATA) {
2400 return -1;
2401 } else {
2402 throw e.rethrowAsIOException();
2403 }
2404 }
2405 }
2406
Amith Yamasani920ace02012-09-20 22:15:37 -07002407 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002408 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2409 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2410 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2411 }
2412
2413 int onShellCommand(Shell shell, String cmd) {
2414 if (cmd == null) {
2415 return shell.handleDefaultCommands(cmd);
2416 }
2417
2418 final PrintWriter pw = shell.getOutPrintWriter();
2419 try {
2420 switch(cmd) {
2421 case "list":
2422 return runList(pw);
2423 }
2424 } catch (RemoteException e) {
2425 pw.println("Remote exception: " + e);
2426 }
2427 return -1;
2428 }
2429
2430 private int runList(PrintWriter pw) throws RemoteException {
2431 final IActivityManager am = ActivityManagerNative.getDefault();
2432 final List<UserInfo> users = getUsers(false);
2433 if (users == null) {
2434 pw.println("Error: couldn't get users");
2435 return 1;
2436 } else {
2437 pw.println("Users:");
2438 for (int i = 0; i < users.size(); i++) {
Jeff Sharkeye17ac152015-11-06 22:40:29 -08002439 String running = am.isUserRunning(users.get(i).id, 0) ? " running" : "";
Todd Kennedy60459ab2015-10-30 11:32:16 -07002440 pw.println("\t" + users.get(i).toString() + running);
2441 }
2442 return 0;
2443 }
2444 }
2445
2446 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002447 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2448 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2449 != PackageManager.PERMISSION_GRANTED) {
2450 pw.println("Permission Denial: can't dump UserManager from from pid="
2451 + Binder.getCallingPid()
2452 + ", uid=" + Binder.getCallingUid()
2453 + " without permission "
2454 + android.Manifest.permission.DUMP);
2455 return;
2456 }
2457
2458 long now = System.currentTimeMillis();
2459 StringBuilder sb = new StringBuilder();
2460 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002461 synchronized (mUsersLock) {
2462 pw.println("Users:");
2463 for (int i = 0; i < mUsers.size(); i++) {
2464 UserInfo user = mUsers.valueAt(i);
2465 if (user == null) {
2466 continue;
2467 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002468 final int userId = user.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002469 pw.print(" "); pw.print(user);
2470 pw.print(" serialNo="); pw.print(user.serialNumber);
Makoto Onukie7927da2015-11-25 10:05:17 -08002471 if (mRemovingUserIds.get(userId)) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002472 pw.print(" <removing> ");
2473 }
2474 if (user.partial) {
2475 pw.print(" <partial>");
2476 }
2477 pw.println();
2478 pw.print(" Created: ");
2479 if (user.creationTime == 0) {
2480 pw.println("<unknown>");
2481 } else {
2482 sb.setLength(0);
2483 TimeUtils.formatDuration(now - user.creationTime, sb);
2484 sb.append(" ago");
2485 pw.println(sb);
2486 }
2487 pw.print(" Last logged in: ");
2488 if (user.lastLoggedInTime == 0) {
2489 pw.println("<unknown>");
2490 } else {
2491 sb.setLength(0);
2492 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2493 sb.append(" ago");
2494 pw.println(sb);
2495 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002496 pw.print(" Has profile owner: ");
2497 pw.println(mIsUserManaged.get(userId));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002498 pw.println(" Restrictions:");
2499 synchronized (mRestrictionsLock) {
2500 UserRestrictionsUtils.dumpRestrictions(
2501 pw, " ", mBaseUserRestrictions.get(user.id));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002502 pw.println(" Device policy local restrictions:");
2503 UserRestrictionsUtils.dumpRestrictions(
2504 pw, " ", mDevicePolicyLocalUserRestrictions.get(user.id));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002505 pw.println(" Effective restrictions:");
2506 UserRestrictionsUtils.dumpRestrictions(
2507 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2508 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002509 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002510 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002511 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002512 pw.println(" Device policy global restrictions:");
2513 synchronized (mRestrictionsLock) {
2514 UserRestrictionsUtils
2515 .dumpRestrictions(pw, " ", mDevicePolicyGlobalUserRestrictions);
2516 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002517 pw.println();
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002518 pw.println(" Guest restrictions:");
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002519 synchronized (mGuestRestrictions) {
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002520 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Fyodor Kupolove80085d2015-11-06 18:21:39 -08002521 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002522 synchronized (mUsersLock) {
2523 pw.println();
2524 pw.println(" Device managed: " + mIsDeviceManaged);
2525 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002526 }
2527 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002528
2529 final class MainHandler extends Handler {
2530
2531 @Override
2532 public void handleMessage(Message msg) {
2533 switch (msg.what) {
2534 case WRITE_USER_MSG:
2535 removeMessages(WRITE_USER_MSG, msg.obj);
2536 synchronized (mPackagesLock) {
2537 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002538 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002539 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002540 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002541 }
2542 }
2543 }
2544 }
2545 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002546
2547 /**
2548 * @param userId
2549 * @return whether the user has been initialized yet
2550 */
2551 boolean isInitialized(int userId) {
2552 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2553 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002554
2555 private class LocalService extends UserManagerInternal {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002556 @Override
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002557 public void setDevicePolicyUserRestrictions(int userId, @NonNull Bundle localRestrictions,
2558 @Nullable Bundle globalRestrictions) {
2559 UserManagerService.this.setDevicePolicyUserRestrictions(userId, localRestrictions,
2560 globalRestrictions);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002561 }
2562
2563 @Override
2564 public Bundle getBaseUserRestrictions(int userId) {
2565 synchronized (mRestrictionsLock) {
2566 return mBaseUserRestrictions.get(userId);
2567 }
2568 }
2569
2570 @Override
2571 public void setBaseUserRestrictionsByDpmsForMigration(
2572 int userId, Bundle baseRestrictions) {
2573 synchronized (mRestrictionsLock) {
2574 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002575 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002576 }
2577
Fyodor Kupolov82402752015-10-28 14:54:51 -07002578 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002579 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002580 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002581 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002582 } else {
2583 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2584 }
2585 }
2586 }
Makoto Onukid45a4a22015-11-02 17:17:38 -08002587
2588 @Override
2589 public boolean getUserRestriction(int userId, String key) {
2590 return getUserRestrictions(userId).getBoolean(key);
2591 }
2592
2593 @Override
2594 public void addUserRestrictionsListener(UserRestrictionsListener listener) {
2595 synchronized (mUserRestrictionsListeners) {
2596 mUserRestrictionsListeners.add(listener);
2597 }
2598 }
2599
2600 @Override
2601 public void removeUserRestrictionsListener(UserRestrictionsListener listener) {
2602 synchronized (mUserRestrictionsListeners) {
2603 mUserRestrictionsListeners.remove(listener);
2604 }
2605 }
Makoto Onukie7927da2015-11-25 10:05:17 -08002606
2607 @Override
2608 public void setDeviceManaged(boolean isManaged) {
2609 synchronized (mUsersLock) {
2610 mIsDeviceManaged = isManaged;
2611 }
2612 }
2613
2614 @Override
2615 public void setUserManaged(int userId, boolean isManaged) {
2616 synchronized (mUsersLock) {
2617 mIsUserManaged.put(userId, isManaged);
2618 }
2619 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002620 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002621
2622 private class Shell extends ShellCommand {
2623 @Override
2624 public int onCommand(String cmd) {
2625 return onShellCommand(this, cmd);
2626 }
2627
2628 @Override
2629 public void onHelp() {
2630 final PrintWriter pw = getOutPrintWriter();
2631 pw.println("User manager (user) commands:");
2632 pw.println(" help");
2633 pw.println(" Print this help text.");
2634 pw.println("");
2635 pw.println(" list");
2636 pw.println(" Prints all users on the system.");
2637 }
2638 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08002639
2640 private static void debug(String message) {
2641 Log.d(LOG_TAG, message +
2642 (DBG_WITH_STACKTRACE ? " called at\n" + Debug.getCallers(10, " ") : ""));
2643 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002644}