blob: 33b4350a20a7f3b051714bf9acb607b5c0923193 [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;
25import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070026import android.app.admin.DevicePolicyManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070027import android.app.admin.DevicePolicyManagerInternal;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
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;
Jason Monk62062992014-05-06 09:55:28 -040047import android.os.ServiceManager;
Clara Bayarrif05b9d02015-10-23 13:25:19 +010048import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070050import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070051import android.os.UserManagerInternal;
Paul Crowley85e4e812015-05-19 12:42:00 +010052import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070053import android.os.storage.VolumeInfo;
54import android.system.ErrnoException;
55import android.system.Os;
56import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070057import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070058import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070059import android.util.Slog;
60import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080061import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070062import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import android.util.Xml;
64
Makoto Onuki068c54a2015-10-13 14:34:03 -070065import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070066import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040067import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080068import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070069import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070070import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070071import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080072
73import org.xmlpull.v1.XmlPullParser;
74import org.xmlpull.v1.XmlPullParserException;
75import org.xmlpull.v1.XmlSerializer;
76
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077import java.io.BufferedOutputStream;
78import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070079import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070081import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082import java.io.FileOutputStream;
83import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070084import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010085import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086import java.util.ArrayList;
87import java.util.List;
88
Fyodor Kupolov262f9952015-03-23 18:55:11 -070089import libcore.io.IoUtils;
90
Makoto Onuki068c54a2015-10-13 14:34:03 -070091/**
92 * Service for {@link UserManager}.
93 *
94 * Method naming convention:
Fyodor Kupolov82402752015-10-28 14:54:51 -070095 * <ul>
96 * <li> Methods suffixed with "LILP" should be called within {@link #mInstallLock} and
97 * {@link #mPackagesLock} locks obtained in the respective order.
98 * <li> Methods suffixed with "LR" should be called within the {@link #mRestrictionsLock} lock.
99 * <li> Methods suffixed with "LU" should be called within the {@link #mUsersLock} lock.
100 * </ul>
Makoto Onuki068c54a2015-10-13 14:34:03 -0700101 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700102public class UserManagerService extends IUserManager.Stub {
Amith Yamasani2a003292012-08-14 18:25:45 -0700103 private static final String LOG_TAG = "UserManagerService";
Makoto Onuki068c54a2015-10-13 14:34:03 -0700104 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700105
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700108 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700110 private static final String ATTR_CREATION_TIME = "created";
111 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700112 private static final String ATTR_SERIAL_NO = "serialNumber";
113 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700114 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700115 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700116 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100117 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700118 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530119 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700120 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800122 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800123 private static final String TAG_ENTRY = "entry";
124 private static final String TAG_VALUE = "value";
125 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700126 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800127 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700128
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700129 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
130 private static final String ATTR_TYPE_STRING = "s";
131 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700132 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700133 private static final String ATTR_TYPE_BUNDLE = "B";
134 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700135
Amith Yamasani0b285492011-04-14 17:35:23 -0700136 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700138 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100139 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700140
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800141 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700142 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800143
Amith Yamasani634cf312012-10-04 17:34:21 -0700144 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700145 // We need to keep process uid within Integer.MAX_VALUE.
146 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700147
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700148 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700149
Amith Yamasani920ace02012-09-20 22:15:37 -0700150 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
151
Nicolas Prevotb8186812015-08-06 15:00:03 +0100152 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700153 // without first making sure that the rest of the framework is prepared for it.
154 private static final int MAX_MANAGED_PROFILES = 1;
155
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800156 static final int WRITE_USER_MSG = 1;
157 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530158
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700159 private static final String XATTR_SERIAL = "user.serial";
160
Dianne Hackborn4428e172012-08-24 17:43:05 -0700161 private final Context mContext;
162 private final PackageManagerService mPm;
163 private final Object mInstallLock;
164 private final Object mPackagesLock;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700165 // Short-term lock for internal state, when interaction/sync with PM is not required
166 private final Object mUsersLock = new Object();
167 private final Object mRestrictionsLock = new Object();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700168
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800169 private final Handler mHandler;
170
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171 private final File mUsersDir;
172 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700173
Fyodor Kupolov82402752015-10-28 14:54:51 -0700174 @GuardedBy("mUsersLock")
175 private final SparseArray<UserInfo> mUsers = new SparseArray<>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700176
177 /**
178 * User restrictions set via UserManager. This doesn't include restrictions set by
179 * device owner / profile owners.
180 *
181 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
182 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
183 * maybe shared between {@link #mBaseUserRestrictions} and
184 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
185 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700186 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700187 */
188 @GuardedBy("mRestrictionsLock")
189 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
190
191 /**
192 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
193 * with device / profile owner restrictions. We'll initialize it lazily; use
194 * {@link #getEffectiveUserRestrictions} to access it.
195 *
196 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
197 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
198 * maybe shared between {@link #mBaseUserRestrictions} and
199 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
200 * (Otherwise we won't be able to detect what restrictions have changed in
Fyodor Kupolov82402752015-10-28 14:54:51 -0700201 * {@link #updateUserRestrictionsInternalLR}.
Makoto Onuki068c54a2015-10-13 14:34:03 -0700202 */
203 @GuardedBy("mRestrictionsLock")
204 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
205
Makoto Onuki4f160732015-10-27 17:15:38 -0700206 /**
Fyodor Kupolov82402752015-10-28 14:54:51 -0700207 * User restrictions that have already been applied in {@link #applyUserRestrictionsLR}. We
Makoto Onuki4f160732015-10-27 17:15:38 -0700208 * use it to detect restrictions that have changed since the last
Fyodor Kupolov82402752015-10-28 14:54:51 -0700209 * {@link #applyUserRestrictionsLR} call.
Makoto Onuki4f160732015-10-27 17:15:38 -0700210 */
211 @GuardedBy("mRestrictionsLock")
212 private final SparseArray<Bundle> mAppliedUserRestrictions = new SparseArray<>();
213
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530214 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800215
216 /**
217 * Set of user IDs being actively removed. Removed IDs linger in this set
218 * for several seconds to work around a VFS caching issue.
219 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700220 @GuardedBy("mUsersLock")
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800221 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700222
Fyodor Kupolov82402752015-10-28 14:54:51 -0700223 @GuardedBy("mUsersLock")
Amith Yamasani0b285492011-04-14 17:35:23 -0700224 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700225 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700226 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700227
Jason Monk62062992014-05-06 09:55:28 -0400228 private IAppOpsService mAppOpsService;
229
Makoto Onuki068c54a2015-10-13 14:34:03 -0700230 private final LocalService mLocalService;
231
Amith Yamasani258848d2012-08-10 17:06:33 -0700232 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700233
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 public static UserManagerService getInstance() {
235 synchronized (UserManagerService.class) {
236 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700237 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700238 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700239
240 /**
241 * Available for testing purposes.
242 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700243 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700244 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700245 }
246
Dianne Hackborn4428e172012-08-24 17:43:05 -0700247 /**
248 * Called by package manager to create the service. This is closely
249 * associated with the package manager, and the given lock is the
250 * package manager's own lock.
251 */
252 UserManagerService(Context context, PackageManagerService pm,
253 Object installLock, Object packagesLock) {
254 this(context, pm, installLock, packagesLock,
255 Environment.getDataDirectory(),
256 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700257 }
258
Dianne Hackborn4428e172012-08-24 17:43:05 -0700259 /**
260 * Available for testing purposes.
261 */
262 private UserManagerService(Context context, PackageManagerService pm,
263 Object installLock, Object packagesLock,
264 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700265 mContext = context;
266 mPm = pm;
267 mInstallLock = installLock;
268 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800269 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700270 synchronized (mInstallLock) {
271 synchronized (mPackagesLock) {
272 mUsersDir = new File(dataDir, USER_INFO_DIR);
273 mUsersDir.mkdirs();
274 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700275 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700276 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700277 FileUtils.setPermissions(mUsersDir.toString(),
278 FileUtils.S_IRWXU|FileUtils.S_IRWXG
279 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
280 -1, -1);
281 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800282 initDefaultGuestRestrictions();
Fyodor Kupolov82402752015-10-28 14:54:51 -0700283 readUserListLILP();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700284 sInstance = this;
285 }
286 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700287 mLocalService = new LocalService();
288 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700289 }
290
291 void systemReady() {
292 synchronized (mInstallLock) {
293 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700294 synchronized (mUsersLock) {
295 // Prune out any partially created/partially removed users.
296 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
297 final int userSize = mUsers.size();
298 for (int i = 0; i < userSize; i++) {
299 UserInfo ui = mUsers.valueAt(i);
300 if ((ui.partial || ui.guestToRemove) && i != 0) {
301 partials.add(ui);
302 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700303 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700304 final int partialsSize = partials.size();
305 for (int i = 0; i < partialsSize; i++) {
306 UserInfo ui = partials.get(i);
307 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
308 + " (name=" + ui.name + ")");
309 removeUserStateLILP(ui.id);
310 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700311 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700312 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700313 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700314 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400315 mAppOpsService = IAppOpsService.Stub.asInterface(
316 ServiceManager.getService(Context.APP_OPS_SERVICE));
317 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700318 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400319 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700320 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400321 } catch (RemoteException e) {
322 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
323 }
324 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700325 }
326
327 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700328 public UserInfo getPrimaryUser() {
329 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700330 synchronized (mUsersLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700331 final int userSize = mUsers.size();
332 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700333 UserInfo ui = mUsers.valueAt(i);
334 if (ui.isPrimary()) {
335 return ui;
336 }
337 }
338 }
339 return null;
340 }
341
342 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700343 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700344 checkManageUsersPermission("query users");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700345 synchronized (mUsersLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700346 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700347 final int userSize = mUsers.size();
348 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700349 UserInfo ui = mUsers.valueAt(i);
350 if (ui.partial) {
351 continue;
352 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800353 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700354 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700355 }
Amith Yamasani13593602012-03-22 16:16:17 -0700356 }
357 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700358 }
Amith Yamasani13593602012-03-22 16:16:17 -0700359 }
360
Amith Yamasani258848d2012-08-10 17:06:33 -0700361 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100362 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800363 if (userId != UserHandle.getCallingUserId()) {
364 checkManageUsersPermission("getting profiles related to user " + userId);
365 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700366 final long ident = Binder.clearCallingIdentity();
367 try {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700368 synchronized (mUsersLock) {
369 return getProfilesLU(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100370 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700371 } finally {
372 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000373 }
374 }
375
Amith Yamasanibe465322014-04-24 13:45:17 -0700376 /** Assume permissions already checked and caller's identity cleared */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700377 private List<UserInfo> getProfilesLU(int userId, boolean enabledOnly) {
378 UserInfo user = getUserInfoLU(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700379 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700380 if (user == null) {
381 // Probably a dying user
382 return users;
383 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700384 final int userSize = mUsers.size();
385 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700386 UserInfo profile = mUsers.valueAt(i);
387 if (!isProfileOf(user, profile)) {
388 continue;
389 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100390 if (enabledOnly && !profile.isEnabled()) {
391 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700392 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700393 if (mRemovingUserIds.get(profile.id)) {
394 continue;
395 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700396 users.add(profile);
397 }
398 return users;
399 }
400
Jessica Hummelbe81c802014-04-22 15:49:22 +0100401 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700402 public int getCredentialOwnerProfile(int userHandle) {
403 checkManageUsersPermission("get the credential owner");
Clara Bayarrif05b9d02015-10-23 13:25:19 +0100404 if (!"file".equals(SystemProperties.get("ro.crypto.type", "none"))) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700405 synchronized (mUsersLock) {
406 UserInfo profileParent = getProfileParentLU(userHandle);
Andres Moralesc5548c02015-08-05 10:23:12 -0700407 if (profileParent != null) {
408 return profileParent.id;
409 }
410 }
411 }
412
413 return userHandle;
414 }
415
416 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700417 public boolean isSameProfileGroup(int userId, int otherUserId) {
418 if (userId == otherUserId) return true;
419 checkManageUsersPermission("check if in the same profile group");
420 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700421 return isSameProfileGroupLP(userId, otherUserId);
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700422 }
423 }
424
Fyodor Kupolov82402752015-10-28 14:54:51 -0700425 private boolean isSameProfileGroupLP(int userId, int otherUserId) {
426 synchronized (mUsersLock) {
427 UserInfo userInfo = getUserInfoLU(userId);
428 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
429 return false;
430 }
431 UserInfo otherUserInfo = getUserInfoLU(otherUserId);
432 if (otherUserInfo == null
433 || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
434 return false;
435 }
436 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700437 }
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700438 }
439
440 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100441 public UserInfo getProfileParent(int userHandle) {
442 checkManageUsersPermission("get the profile parent");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700443 synchronized (mUsersLock) {
444 return getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700445 }
446 }
447
Fyodor Kupolov82402752015-10-28 14:54:51 -0700448 private UserInfo getProfileParentLU(int userHandle) {
449 UserInfo profile = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700450 if (profile == null) {
451 return null;
452 }
453 int parentUserId = profile.profileGroupId;
454 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
455 return null;
456 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700457 return getUserInfoLU(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100458 }
459 }
460
Fyodor Kupolov82402752015-10-28 14:54:51 -0700461 private static boolean isProfileOf(UserInfo user, UserInfo profile) {
Kenny Guy2a764942014-04-02 13:29:20 +0100462 return user.id == profile.id ||
463 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
464 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000465 }
466
467 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100468 public void setUserEnabled(int userId) {
469 checkManageUsersPermission("enable user");
470 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700471 UserInfo info;
472 synchronized (mUsersLock) {
473 info = getUserInfoLU(userId);
474 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100475 if (info != null && !info.isEnabled()) {
476 info.flags ^= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700477 writeUserLP(info);
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100478 }
479 }
480 }
481
482 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700483 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700484 checkManageUsersPermission("query user");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700485 synchronized (mUsersLock) {
486 return getUserInfoLU(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700487 }
488 }
489
Amith Yamasani71e6c692013-03-24 17:39:28 -0700490 @Override
491 public boolean isRestricted() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700492 synchronized (mUsersLock) {
493 return getUserInfoLU(UserHandle.getCallingUserId()).isRestricted();
Amith Yamasani71e6c692013-03-24 17:39:28 -0700494 }
495 }
496
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700497 @Override
498 public boolean canHaveRestrictedProfile(int userId) {
499 checkManageUsersPermission("canHaveRestrictedProfile");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700500 synchronized (mUsersLock) {
501 final UserInfo userInfo = getUserInfoLU(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700502 if (userInfo == null || !userInfo.canHaveProfile()) {
503 return false;
504 }
505 if (!userInfo.isAdmin()) {
506 return false;
507 }
508 }
509 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
510 Context.DEVICE_POLICY_SERVICE);
511 // restricted profile can be created if there is no DO set and the admin user has no PO
512 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
513 }
514
Amith Yamasani195263742012-08-21 15:40:12 -0700515 /*
516 * Should be locked on mUsers before calling this.
517 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700518 private UserInfo getUserInfoLU(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700519 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700520 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800521 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700522 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
523 return null;
524 }
525 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700526 }
527
Fyodor Kupolov82402752015-10-28 14:54:51 -0700528 /**
529 * Obtains {@link #mUsersLock} and return UserInfo from mUsers.
530 * <p>No permissions checking or any addition checks are made</p>
531 */
532 private UserInfo getUserInfoNoChecks(int userId) {
533 synchronized (mUsersLock) {
534 return mUsers.get(userId);
535 }
536 }
537
Amith Yamasani236b2b52015-08-18 14:32:14 -0700538 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700539 public boolean exists(int userId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700540 return getUserInfoNoChecks(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700541 }
542
Amith Yamasani258848d2012-08-10 17:06:33 -0700543 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700544 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700545 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700546 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700547 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700548 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700549 if (info == null || info.partial) {
550 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
551 return;
552 }
Amith Yamasani13593602012-03-22 16:16:17 -0700553 if (name != null && !name.equals(info.name)) {
554 info.name = name;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700555 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700556 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700557 }
558 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700559 if (changed) {
560 sendUserInfoChangedBroadcast(userId);
561 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700562 }
563
Amith Yamasani258848d2012-08-10 17:06:33 -0700564 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700565 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700566 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400567 long ident = Binder.clearCallingIdentity();
568 try {
569 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700570 UserInfo info = getUserInfoNoChecks(userId);
Jason Monk9a944532014-07-08 09:31:21 -0400571 if (info == null || info.partial) {
572 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
573 return;
574 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700575 writeBitmapLP(info, bitmap);
576 writeUserLP(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700577 }
Jason Monk9a944532014-07-08 09:31:21 -0400578 sendUserInfoChangedBroadcast(userId);
579 } finally {
580 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700581 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700582 }
583
584 private void sendUserInfoChangedBroadcast(int userId) {
585 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
586 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
587 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700588 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700589 }
590
Amith Yamasani258848d2012-08-10 17:06:33 -0700591 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100592 public ParcelFileDescriptor getUserIcon(int userId) {
593 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700594 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700595 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700596 if (info == null || info.partial) {
597 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
598 return null;
599 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700600 int callingGroupId = getUserInfoNoChecks(UserHandle.getCallingUserId()).profileGroupId;
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100601 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
602 || callingGroupId != info.profileGroupId) {
603 checkManageUsersPermission("get the icon of a user who is not related");
604 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700605 if (info.iconPath == null) {
606 return null;
607 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100608 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700609 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100610
611 try {
612 return ParcelFileDescriptor.open(
613 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
614 } catch (FileNotFoundException e) {
615 Log.e(LOG_TAG, "Couldn't find icon file", e);
616 }
617 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700618 }
619
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700620 public void makeInitialized(int userId) {
621 checkManageUsersPermission("makeInitialized");
622 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700623 UserInfo info = getUserInfoNoChecks(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700624 if (info == null || info.partial) {
625 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700626 // TODO Check if we should return here instead of a null check below
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700627 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700628 if (info != null && (info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700629 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov82402752015-10-28 14:54:51 -0700630 scheduleWriteUserLP(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700631 }
632 }
633 }
634
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700635 /**
636 * If default guest restrictions haven't been initialized yet, add the basic
637 * restrictions.
638 */
639 private void initDefaultGuestRestrictions() {
640 if (mGuestRestrictions.isEmpty()) {
641 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800642 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700643 }
644 }
645
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800646 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530647 public Bundle getDefaultGuestRestrictions() {
648 checkManageUsersPermission("getDefaultGuestRestrictions");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700649 // TODO Switch to mGuestRestrictions for locking
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530650 synchronized (mPackagesLock) {
651 return new Bundle(mGuestRestrictions);
652 }
653 }
654
655 @Override
656 public void setDefaultGuestRestrictions(Bundle restrictions) {
657 checkManageUsersPermission("setDefaultGuestRestrictions");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700658 synchronized (mInstallLock) {
659 synchronized (mPackagesLock) {
660 mGuestRestrictions.clear();
661 mGuestRestrictions.putAll(restrictions);
662 writeUserListLILP();
663 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530664 }
665 }
666
Makoto Onuki068c54a2015-10-13 14:34:03 -0700667 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700668 private Bundle computeEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700669 final DevicePolicyManagerInternal dpmi =
670 LocalServices.getService(DevicePolicyManagerInternal.class);
671 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
672
673 final Bundle effective;
674 if (dpmi == null) {
675 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
676 effective = systemRestrictions;
677 } else {
678 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
679 }
680 return effective;
681 }
682
683 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700684 private void invalidateEffectiveUserRestrictionsLR(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700685 if (DBG) {
686 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
687 }
688 mCachedEffectiveUserRestrictions.remove(userId);
689 }
690
691 private Bundle getEffectiveUserRestrictions(int userId) {
692 synchronized (mRestrictionsLock) {
693 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
694 if (restrictions == null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700695 restrictions = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700696 mCachedEffectiveUserRestrictions.put(userId, restrictions);
697 }
698 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700699 }
700 }
701
Makoto Onuki068c54a2015-10-13 14:34:03 -0700702 /** @return a specific user restriction that's in effect currently. */
703 @Override
704 public boolean hasUserRestriction(String restrictionKey, int userId) {
705 Bundle restrictions = getEffectiveUserRestrictions(userId);
706 return restrictions != null && restrictions.getBoolean(restrictionKey);
707 }
708
709 /**
710 * @return UserRestrictions that are in effect currently. This always returns a new
711 * {@link Bundle}.
712 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700713 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800714 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700715 Bundle restrictions = getEffectiveUserRestrictions(userId);
716 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800717 }
718
719 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700720 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700721 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700722 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
723 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700724 }
725 }
726
727 @Override
728 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
729 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700730 setUserRestrictionNoCheck(key, value, userId);
731 }
732
733 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
734 synchronized (mRestrictionsLock) {
735 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
736 // a copy.
737 final Bundle newRestrictions = new Bundle();
738 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
739 newRestrictions.putBoolean(key, value);
740
Fyodor Kupolov82402752015-10-28 14:54:51 -0700741 updateUserRestrictionsInternalLR(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700742 }
743 }
744
Makoto Onuki068c54a2015-10-13 14:34:03 -0700745 /**
746 * Optionally updating user restrictions, calculate the effective user restrictions by
747 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
748 * apply it to {@link com.android.server.AppOpsService}.
749 * TODO applyUserRestrictionsLocked() should also apply to system settings.
750 *
751 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
752 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
753 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
754 * @param userId target user ID.
755 */
756 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700757 private void updateUserRestrictionsInternalLR(
Makoto Onuki068c54a2015-10-13 14:34:03 -0700758 @Nullable Bundle newRestrictions, int userId) {
759 if (DBG) {
760 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
761 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800762 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700763 // Update system restrictions.
764 if (newRestrictions != null) {
765 // If newRestrictions == the current one, it's probably a bug.
766 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
767 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
768 != newRestrictions);
769 mBaseUserRestrictions.put(userId, newRestrictions);
770 }
771
Fyodor Kupolov82402752015-10-28 14:54:51 -0700772 final Bundle effective = computeEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700773
Makoto Onuki759a7632015-10-28 16:43:10 -0700774 mCachedEffectiveUserRestrictions.put(userId, effective);
775
Fyodor Kupolov82402752015-10-28 14:54:51 -0700776 applyUserRestrictionsLR(userId, effective);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800777 }
778
Makoto Onuki068c54a2015-10-13 14:34:03 -0700779 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700780 private void applyUserRestrictionsLR(int userId, Bundle newRestrictions) {
Makoto Onuki4f160732015-10-27 17:15:38 -0700781 final Bundle prevRestrictions = mAppliedUserRestrictions.get(userId);
782
783 if (DBG) {
784 Log.d(LOG_TAG, "applyUserRestrictionsRL userId=" + userId
785 + " new=" + newRestrictions + " prev=" + prevRestrictions);
786 }
787
Makoto Onuki068c54a2015-10-13 14:34:03 -0700788 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700789 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700790 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700791 } catch (RemoteException e) {
792 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
793 } finally {
794 Binder.restoreCallingIdentity(token);
795 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700796
Makoto Onuki4f160732015-10-27 17:15:38 -0700797 UserRestrictionsUtils.applyUserRestrictions(
798 mContext, userId, newRestrictions, prevRestrictions);
799
800 mAppliedUserRestrictions.put(userId, new Bundle(newRestrictions));
Makoto Onuki068c54a2015-10-13 14:34:03 -0700801 }
802
803 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700804 private void updateEffectiveUserRestrictionsLR(int userId) {
805 updateUserRestrictionsInternalLR(null, userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700806 }
807
808 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -0700809 private void updateEffectiveUserRestrictionsForAllUsersLR() {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700810 // First, invalidate all cached values.
Makoto Onuki4f160732015-10-27 17:15:38 -0700811 mCachedEffectiveUserRestrictions.clear();
812
Makoto Onuki068c54a2015-10-13 14:34:03 -0700813 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
814 // it on a handler.
815 final Runnable r = new Runnable() {
816 @Override
817 public void run() {
818 // Then get the list of running users.
819 final int[] runningUsers;
820 try {
821 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
822 } catch (RemoteException e) {
823 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
824 return;
825 }
826 // Then re-calculate the effective restrictions and apply, only for running users.
827 // It's okay if a new user has started after the getRunningUserIds() call,
828 // because we'll do the same thing (re-calculate the restrictions and apply)
829 // when we start a user.
830 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
831 synchronized (mRestrictionsLock) {
832 for (int i = 0; i < runningUsers.length; i++) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700833 updateUserRestrictionsInternalLR(null, runningUsers[i]);
Makoto Onuki068c54a2015-10-13 14:34:03 -0700834 }
835 }
836 }
837 };
838 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700839 }
840
Amith Yamasani258848d2012-08-10 17:06:33 -0700841 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700842 * Check if we've hit the limit of how many users can be created.
843 */
Fyodor Kupolov82402752015-10-28 14:54:51 -0700844 private boolean isUserLimitReached() {
845 int count;
846 synchronized (mUsersLock) {
847 count = getAliveUsersExcludingGuestsCountLU();
848 }
849 return count >= UserManager.getMaxSupportedUsers();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700850 }
851
852 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100853 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700854 checkManageUsersPermission("check if more managed profiles can be added.");
855 if (ActivityManager.isLowRamDeviceStatic()) {
856 return false;
857 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700858 if (!mContext.getPackageManager().hasSystemFeature(
859 PackageManager.FEATURE_MANAGED_USERS)) {
860 return false;
861 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100862 // Limit number of managed profiles that can be created
863 int managedProfilesCount = getProfiles(userId, true).size() - 1;
864 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
865 return false;
866 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700867 synchronized(mUsersLock) {
868 UserInfo userInfo = getUserInfoLU(userId);
Nicolas Prevotb8186812015-08-06 15:00:03 +0100869 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700870 return false;
871 }
Fyodor Kupolov82402752015-10-28 14:54:51 -0700872 int usersCount = getAliveUsersExcludingGuestsCountLU();
Nicolas Prevot12678a92015-05-13 12:15:03 -0700873 // We allow creating a managed profile in the special case where there is only one user.
874 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
875 }
876 }
877
Fyodor Kupolov82402752015-10-28 14:54:51 -0700878 private int getAliveUsersExcludingGuestsCountLU() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700879 int aliveUserCount = 0;
880 final int totalUserCount = mUsers.size();
881 // Skip over users being removed
882 for (int i = 0; i < totalUserCount; i++) {
883 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700884 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700885 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700886 aliveUserCount++;
887 }
888 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700889 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700890 }
891
892 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700893 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700894 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700895 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700896 *
897 * @param message used as message if SecurityException is thrown
898 * @throws SecurityException if the caller is not system or root
899 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700900 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700901 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700902 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400903 && ActivityManager.checkComponentPermission(
904 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700905 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
906 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
907 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400908 }
909
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700910 private static void checkSystemOrRoot(String message) {
911 final int uid = Binder.getCallingUid();
912 if (uid != Process.SYSTEM_UID && uid != 0) {
913 throw new SecurityException("Only system may call: " + message);
914 }
915 }
916
Fyodor Kupolov82402752015-10-28 14:54:51 -0700917 private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700918 try {
919 File dir = new File(mUsersDir, Integer.toString(info.id));
920 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100921 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700922 if (!dir.exists()) {
923 dir.mkdir();
924 FileUtils.setPermissions(
925 dir.getPath(),
926 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
927 -1, -1);
928 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700929 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100930 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
931 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700932 info.iconPath = file.getAbsolutePath();
933 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700934 try {
935 os.close();
936 } catch (IOException ioe) {
937 // What the ... !
938 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100939 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700940 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700941 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700942 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700943 }
944
Amith Yamasani0b285492011-04-14 17:35:23 -0700945 /**
946 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
947 * cache it elsewhere.
948 * @return the array of user ids.
949 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700950 public int[] getUserIds() {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700951 synchronized (mUsersLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700952 return mUserIds;
953 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700954 }
955
Fyodor Kupolov82402752015-10-28 14:54:51 -0700956 private void readUserListLILP() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700957 if (!mUserListFile.exists()) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700958 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700959 return;
960 }
961 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700962 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700963 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700964 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700965 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100966 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700967 int type;
968 while ((type = parser.next()) != XmlPullParser.START_TAG
969 && type != XmlPullParser.END_DOCUMENT) {
970 ;
971 }
972
973 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700974 Slog.e(LOG_TAG, "Unable to read user list");
Fyodor Kupolov82402752015-10-28 14:54:51 -0700975 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700976 return;
977 }
978
Amith Yamasani2a003292012-08-14 18:25:45 -0700979 mNextSerialNumber = -1;
980 if (parser.getName().equals(TAG_USERS)) {
981 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
982 if (lastSerialNumber != null) {
983 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
984 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700985 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
986 if (versionNumber != null) {
987 mUserVersion = Integer.parseInt(versionNumber);
988 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700989 }
990
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700991 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530992 if (type == XmlPullParser.START_TAG) {
993 final String name = parser.getName();
994 if (name.equals(TAG_USER)) {
995 String id = parser.getAttributeValue(null, ATTR_ID);
Fyodor Kupolov82402752015-10-28 14:54:51 -0700996 UserInfo user = readUserLILP(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700997
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530998 if (user != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -0700999 synchronized (mUsersLock) {
1000 mUsers.put(user.id, user);
1001 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
1002 mNextSerialNumber = user.id + 1;
1003 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301004 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001005 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301006 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -08001007 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1008 && type != XmlPullParser.END_TAG) {
1009 if (type == XmlPullParser.START_TAG) {
1010 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001011 UserRestrictionsUtils
1012 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -08001013 }
1014 break;
1015 }
1016 }
Amith Yamasani258848d2012-08-10 17:06:33 -07001017 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001018 }
1019 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001020 updateUserIds();
1021 upgradeIfNecessaryLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001022 } catch (IOException ioe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001023 fallbackToSingleUserLILP();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001024 } catch (XmlPullParserException pe) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001025 fallbackToSingleUserLILP();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001026 } finally {
1027 if (fis != null) {
1028 try {
1029 fis.close();
1030 } catch (IOException e) {
1031 }
1032 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001033 }
1034 }
1035
Amith Yamasani6f34b412012-10-22 18:19:27 -07001036 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -08001037 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -07001038 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001039 private void upgradeIfNecessaryLILP() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001040 int userVersion = mUserVersion;
1041 if (userVersion < 1) {
1042 // Assign a proper name for the owner, if not initialized correctly before
Fyodor Kupolov82402752015-10-28 14:54:51 -07001043 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001044 if ("Primary".equals(user.name)) {
1045 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001046 scheduleWriteUserLP(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001047 }
1048 userVersion = 1;
1049 }
1050
Amith Yamasanibc9625052012-11-15 14:39:18 -08001051 if (userVersion < 2) {
1052 // Owner should be marked as initialized
Fyodor Kupolov82402752015-10-28 14:54:51 -07001053 UserInfo user = getUserInfoNoChecks(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001054 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1055 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001056 scheduleWriteUserLP(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001057 }
1058 userVersion = 2;
1059 }
1060
Amith Yamasani350962c2013-08-06 11:18:53 -07001061
Amith Yamasani5e486f52013-08-07 11:06:44 -07001062 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001063 userVersion = 4;
1064 }
1065
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001066 if (userVersion < 5) {
1067 initDefaultGuestRestrictions();
1068 userVersion = 5;
1069 }
1070
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001071 if (userVersion < 6) {
1072 final boolean splitSystemUser = UserManager.isSplitSystemUser();
Fyodor Kupolov82402752015-10-28 14:54:51 -07001073 synchronized (mUsersLock) {
1074 for (int i = 0; i < mUsers.size(); i++) {
1075 UserInfo user = mUsers.valueAt(i);
1076 // In non-split mode, only user 0 can have restricted profiles
1077 if (!splitSystemUser && user.isRestricted()
1078 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1079 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1080 scheduleWriteUserLP(user);
1081 }
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001082 }
1083 }
1084 userVersion = 6;
1085 }
1086
Amith Yamasani6f34b412012-10-22 18:19:27 -07001087 if (userVersion < USER_VERSION) {
1088 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1089 + USER_VERSION);
1090 } else {
1091 mUserVersion = userVersion;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001092 writeUserListLILP();
Amith Yamasani6f34b412012-10-22 18:19:27 -07001093 }
1094 }
1095
Fyodor Kupolov82402752015-10-28 14:54:51 -07001096 private void fallbackToSingleUserLILP() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001097 int flags = UserInfo.FLAG_INITIALIZED;
1098 // In split system user mode, the admin and primary flags are assigned to the first human
1099 // user.
1100 if (!UserManager.isSplitSystemUser()) {
1101 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1102 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001103 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001104 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001105 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001106 flags);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001107 synchronized (mUsersLock) {
1108 mUsers.put(system.id, system);
1109 }
Amith Yamasani634cf312012-10-04 17:34:21 -07001110 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001111 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001112
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001113 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001114 synchronized (mRestrictionsLock) {
1115 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1116 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001117
Fyodor Kupolov82402752015-10-28 14:54:51 -07001118 updateUserIds();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001119 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001120
Fyodor Kupolov82402752015-10-28 14:54:51 -07001121 writeUserListLILP();
1122 writeUserLP(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001123 }
1124
Fyodor Kupolov82402752015-10-28 14:54:51 -07001125 private void scheduleWriteUserLP(UserInfo userInfo) {
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001126 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1127 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1128 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1129 }
1130 }
1131
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001132 /*
1133 * Writes the user file in this format:
1134 *
1135 * <user flags="20039023" id="0">
1136 * <name>Primary</name>
1137 * </user>
1138 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001139 private void writeUserLP(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001140 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001141 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001142 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001143 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001144 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1145
1146 // XmlSerializer serializer = XmlUtils.serializerInstance();
1147 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001148 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001149 serializer.startDocument(null, true);
1150 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1151
1152 serializer.startTag(null, TAG_USER);
1153 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001154 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001155 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001156 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1157 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1158 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001159 if (userInfo.iconPath != null) {
1160 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1161 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001162 if (userInfo.partial) {
1163 serializer.attribute(null, ATTR_PARTIAL, "true");
1164 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001165 if (userInfo.guestToRemove) {
1166 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1167 }
Kenny Guy2a764942014-04-02 13:29:20 +01001168 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1169 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1170 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001171 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001172 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1173 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1174 Integer.toString(userInfo.restrictedProfileParentId));
1175 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001176 serializer.startTag(null, TAG_NAME);
1177 serializer.text(userInfo.name);
1178 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001179 Bundle restrictions;
1180 synchronized (mRestrictionsLock) {
1181 restrictions = mBaseUserRestrictions.get(userInfo.id);
1182 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001183 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001184 UserRestrictionsUtils
1185 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001186 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001187 serializer.endTag(null, TAG_USER);
1188
1189 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001190 userFile.finishWrite(fos);
1191 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001192 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001193 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001194 }
1195 }
1196
1197 /*
1198 * Writes the user list file in this format:
1199 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001200 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001201 * <user id="0"></user>
1202 * <user id="2"></user>
1203 * </users>
1204 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001205 private void writeUserListLILP() {
1206 // TODO Investigate removing a dependency on mInstallLock
Amith Yamasani742a6712011-05-04 14:49:28 -07001207 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001208 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001209 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001210 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001211 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1212
1213 // XmlSerializer serializer = XmlUtils.serializerInstance();
1214 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001215 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001216 serializer.startDocument(null, true);
1217 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1218
1219 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001220 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001221 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001222
Adam Lesinskieddeb492014-09-08 17:50:03 -07001223 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001224 UserRestrictionsUtils
1225 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301226 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001227 int[] userIdsToWrite;
1228 synchronized (mUsersLock) {
1229 userIdsToWrite = new int[mUsers.size()];
1230 for (int i = 0; i < userIdsToWrite.length; i++) {
1231 UserInfo user = mUsers.valueAt(i);
1232 userIdsToWrite[i] = user.id;
1233 }
1234 }
1235 for (int id : userIdsToWrite) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001236 serializer.startTag(null, TAG_USER);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001237 serializer.attribute(null, ATTR_ID, Integer.toString(id));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001238 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001239 }
1240
1241 serializer.endTag(null, TAG_USERS);
1242
1243 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001244 userListFile.finishWrite(fos);
1245 } catch (Exception e) {
1246 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001247 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001248 }
1249 }
1250
Fyodor Kupolov82402752015-10-28 14:54:51 -07001251 private UserInfo readUserLILP(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001252 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001253 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001254 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001255 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001256 long creationTime = 0L;
1257 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001258 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001259 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001260 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001261 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001262 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001263
1264 FileInputStream fis = null;
1265 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001266 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001267 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001268 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001269 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001270 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001271 int type;
1272 while ((type = parser.next()) != XmlPullParser.START_TAG
1273 && type != XmlPullParser.END_DOCUMENT) {
1274 ;
1275 }
1276
1277 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001278 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001279 return null;
1280 }
1281
1282 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001283 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1284 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001285 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001286 return null;
1287 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001288 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1289 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001290 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001291 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1292 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001293 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1294 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001295 restrictedProfileParentId = readIntAttribute(parser,
1296 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001297 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1298 if ("true".equals(valueString)) {
1299 partial = true;
1300 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001301 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1302 if ("true".equals(valueString)) {
1303 guestToRemove = true;
1304 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001305
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001306 int outerDepth = parser.getDepth();
1307 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1308 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1309 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1310 continue;
1311 }
1312 String tag = parser.getName();
1313 if (TAG_NAME.equals(tag)) {
1314 type = parser.next();
1315 if (type == XmlPullParser.TEXT) {
1316 name = parser.getText();
1317 }
1318 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001319 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001320 }
1321 }
1322 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001323
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001324 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001325 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001326 userInfo.creationTime = creationTime;
1327 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001328 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001329 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001330 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001331 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001332 synchronized (mRestrictionsLock) {
1333 mBaseUserRestrictions.append(id, restrictions);
1334 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001335 return userInfo;
1336
1337 } catch (IOException ioe) {
1338 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001339 } finally {
1340 if (fis != null) {
1341 try {
1342 fis.close();
1343 } catch (IOException e) {
1344 }
1345 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001346 }
1347 return null;
1348 }
1349
Amith Yamasani920ace02012-09-20 22:15:37 -07001350 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1351 String valueString = parser.getAttributeValue(null, attr);
1352 if (valueString == null) return defaultValue;
1353 try {
1354 return Integer.parseInt(valueString);
1355 } catch (NumberFormatException nfe) {
1356 return defaultValue;
1357 }
1358 }
1359
1360 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1361 String valueString = parser.getAttributeValue(null, attr);
1362 if (valueString == null) return defaultValue;
1363 try {
1364 return Long.parseLong(valueString);
1365 } catch (NumberFormatException nfe) {
1366 return defaultValue;
1367 }
1368 }
1369
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001370 private boolean isPackageInstalled(String pkg, int userId) {
1371 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1372 PackageManager.GET_UNINSTALLED_PACKAGES,
1373 userId);
1374 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1375 return false;
1376 }
1377 return true;
1378 }
1379
Amith Yamasanib82add22013-07-09 11:24:44 -07001380 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001381 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001382 * Does not do any permissions checking.
1383 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001384 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001385 synchronized (mPackagesLock) {
1386 File dir = Environment.getUserSystemDirectory(userId);
1387 String[] files = dir.list();
1388 if (files == null) return;
1389 for (String fileName : files) {
1390 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1391 File resFile = new File(dir, fileName);
1392 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001393 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001394 }
1395 }
1396 }
1397 }
1398 }
1399
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001400 /**
1401 * Removes the app restrictions file for a specific package and user id, if it exists.
1402 */
1403 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1404 synchronized (mPackagesLock) {
1405 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001406 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001407 if (resFile.exists()) {
1408 resFile.delete();
1409 }
1410 }
1411 }
1412
Kenny Guya52dc3e2014-02-11 15:33:14 +00001413 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001414 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001415 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001416 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001417 }
1418
Amith Yamasani258848d2012-08-10 17:06:33 -07001419 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001420 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001421 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001422 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001423 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001424
Jessica Hummelbe81c802014-04-22 15:49:22 +01001425 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001426 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1427 UserManager.DISALLOW_ADD_USER, false)) {
1428 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1429 return null;
1430 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001431 if (ActivityManager.isLowRamDeviceStatic()) {
1432 return null;
1433 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001434 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001435 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001436 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001437 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001438 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001439 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001440 try {
1441 synchronized (mInstallLock) {
1442 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001443 UserInfo parent = null;
1444 if (parentId != UserHandle.USER_NULL) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001445 synchronized (mUsersLock) {
1446 parent = getUserInfoLU(parentId);
1447 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001448 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001449 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001450 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1451 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001452 return null;
1453 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001454 if (!isGuest && !isManagedProfile && isUserLimitReached()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -07001455 // If we're not adding a guest user or a managed profile and the limit has
1456 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001457 return null;
1458 }
1459 // If we're adding a guest and there already exists one, bail.
Fyodor Kupolov82402752015-10-28 14:54:51 -07001460 if (isGuest && findCurrentGuestUser() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001461 return null;
1462 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001463 // In legacy mode, restricted profile's parent can only be the owner user
1464 if (isRestricted && !UserManager.isSplitSystemUser()
1465 && (parentId != UserHandle.USER_SYSTEM)) {
1466 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1467 return null;
1468 }
1469 if (isRestricted && UserManager.isSplitSystemUser()) {
1470 if (parent == null) {
1471 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1472 + "specified");
1473 return null;
1474 }
1475 if (!parent.canHaveProfile()) {
1476 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1477 + "created for the specified parent user id " + parentId);
1478 return null;
1479 }
1480 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001481 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001482 // And if there is no device owner, we also assign the admin flag to primary
1483 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001484 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001485 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001486 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001487 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1488 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1489 if (devicePolicyManager == null
1490 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001491 flags |= UserInfo.FLAG_ADMIN;
1492 }
1493 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07001494 userId = getNextAvailableId();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001495 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001496 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001497 long now = System.currentTimeMillis();
1498 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001499 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001500 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001501 mUsers.put(userId, userInfo);
Fyodor Kupolov82402752015-10-28 14:54:51 -07001502 writeUserListLILP();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001503 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001504 if (isManagedProfile) {
1505 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1506 parent.profileGroupId = parent.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001507 scheduleWriteUserLP(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001508 }
1509 userInfo.profileGroupId = parent.profileGroupId;
1510 } else if (isRestricted) {
1511 if (!parent.canHaveProfile()) {
1512 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1513 }
1514 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1515 parent.restrictedProfileParentId = parent.id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001516 scheduleWriteUserLP(parent);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001517 }
1518 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001519 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001520 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001521 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1522 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1523 final String volumeUuid = vol.getFsUuid();
1524 try {
1525 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1526 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001527 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001528 enforceSerialNumber(userDir, userInfo.serialNumber);
1529 } catch (IOException e) {
1530 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1531 }
1532 }
1533 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001534 userInfo.partial = false;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001535 scheduleWriteUserLP(userInfo);
1536 updateUserIds();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001537 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001538 synchronized (mRestrictionsLock) {
1539 mBaseUserRestrictions.append(userId, restrictions);
1540 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001541 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001542 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001543 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001544 if (userInfo != null) {
1545 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1546 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1547 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1548 android.Manifest.permission.MANAGE_USERS);
1549 }
1550 } finally {
1551 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001552 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001553 return userInfo;
1554 }
1555
Amith Yamasani0b285492011-04-14 17:35:23 -07001556 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001557 * @hide
1558 */
1559 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1560 checkManageUsersPermission("setupRestrictedProfile");
1561 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1562 if (user == null) {
1563 return null;
1564 }
1565 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1566 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1567 // the putIntForUser() will fail.
1568 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1569 android.provider.Settings.Secure.LOCATION_MODE,
1570 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1571 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1572 return user;
1573 }
1574
1575 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001576 * Find the current guest user. If the Guest user is partial,
1577 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001578 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07001579 private UserInfo findCurrentGuestUser() {
1580 synchronized (mUsersLock) {
1581 final int size = mUsers.size();
1582 for (int i = 0; i < size; i++) {
1583 final UserInfo user = mUsers.valueAt(i);
1584 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1585 return user;
1586 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001587 }
1588 }
1589 return null;
1590 }
1591
1592 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001593 * Mark this guest user for deletion to allow us to create another guest
1594 * and switch to that user before actually removing this guest.
1595 * @param userHandle the userid of the current guest
1596 * @return whether the user could be marked for deletion
1597 */
1598 public boolean markGuestForDeletion(int userHandle) {
1599 checkManageUsersPermission("Only the system can remove users");
1600 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1601 UserManager.DISALLOW_REMOVE_USER, false)) {
1602 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1603 return false;
1604 }
1605
1606 long ident = Binder.clearCallingIdentity();
1607 try {
1608 final UserInfo user;
1609 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001610 synchronized (mUsersLock) {
1611 user = mUsers.get(userHandle);
1612 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1613 return false;
1614 }
Amith Yamasani1df14732014-08-29 21:37:27 -07001615 }
1616 if (!user.isGuest()) {
1617 return false;
1618 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001619 // We set this to a guest user that is to be removed. This is a temporary state
1620 // where we are allowed to add new Guest users, even if this one is still not
1621 // removed. This user will still show up in getUserInfo() calls.
1622 // If we don't get around to removing this Guest user, it will be purged on next
1623 // startup.
1624 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001625 // Mark it as disabled, so that it isn't returned any more when
1626 // profiles are queried.
1627 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001628 writeUserLP(user);
Amith Yamasani1df14732014-08-29 21:37:27 -07001629 }
1630 } finally {
1631 Binder.restoreCallingIdentity(ident);
1632 }
1633 return true;
1634 }
1635
1636 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001637 * Removes a user and all data directories created for that user. This method should be called
1638 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001639 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001640 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001641 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001642 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001643 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1644 UserManager.DISALLOW_REMOVE_USER, false)) {
1645 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1646 return false;
1647 }
1648
Kenny Guyee58b4f2014-05-23 15:19:53 +01001649 long ident = Binder.clearCallingIdentity();
1650 try {
1651 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001652 int currentUser = ActivityManager.getCurrentUser();
1653 if (currentUser == userHandle) {
1654 Log.w(LOG_TAG, "Current user cannot be removed");
1655 return false;
1656 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001657 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001658 synchronized (mUsersLock) {
1659 user = mUsers.get(userHandle);
1660 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1661 return false;
1662 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001663
Fyodor Kupolov82402752015-10-28 14:54:51 -07001664 // We remember deleted user IDs to prevent them from being
1665 // reused during the current boot; they can still be reused
1666 // after a reboot.
1667 mRemovingUserIds.put(userHandle, true);
1668 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001669
Kenny Guyee58b4f2014-05-23 15:19:53 +01001670 try {
1671 mAppOpsService.removeUser(userHandle);
1672 } catch (RemoteException e) {
1673 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1674 }
1675 // Set this to a partially created user, so that the user will be purged
1676 // on next startup, in case the runtime stops now before stopping and
1677 // removing the user completely.
1678 user.partial = true;
1679 // Mark it as disabled, so that it isn't returned any more when
1680 // profiles are queried.
1681 user.flags |= UserInfo.FLAG_DISABLED;
Fyodor Kupolov82402752015-10-28 14:54:51 -07001682 writeUserLP(user);
Kenny Guyee58b4f2014-05-23 15:19:53 +01001683 }
1684
1685 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1686 && user.isManagedProfile()) {
1687 // Send broadcast to notify system that the user removed was a
1688 // managed user.
1689 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1690 }
1691
1692 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1693 int res;
1694 try {
1695 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1696 new IStopUserCallback.Stub() {
1697 @Override
1698 public void userStopped(int userId) {
1699 finishRemoveUser(userId);
1700 }
1701 @Override
1702 public void userStopAborted(int userId) {
1703 }
1704 });
1705 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001706 return false;
1707 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001708 return res == ActivityManager.USER_OP_SUCCESS;
1709 } finally {
1710 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001711 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001712 }
1713
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001714 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001715 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001716 // Let other services shutdown any activity and clean up their state before completely
1717 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001718 long ident = Binder.clearCallingIdentity();
1719 try {
1720 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1721 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001722 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1723 android.Manifest.permission.MANAGE_USERS,
1724
1725 new BroadcastReceiver() {
1726 @Override
1727 public void onReceive(Context context, Intent intent) {
1728 if (DBG) {
1729 Slog.i(LOG_TAG,
1730 "USER_REMOVED broadcast sent, cleaning up user data "
1731 + userHandle);
1732 }
1733 new Thread() {
1734 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001735 // Clean up any ActivityManager state
1736 LocalServices.getService(ActivityManagerInternal.class)
1737 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001738 synchronized (mInstallLock) {
1739 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07001740 removeUserStateLILP(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001741 }
1742 }
1743 }
1744 }.start();
1745 }
1746 },
1747
1748 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001749 } finally {
1750 Binder.restoreCallingIdentity(ident);
1751 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001752 }
1753
Fyodor Kupolov82402752015-10-28 14:54:51 -07001754 private void removeUserStateLILP(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001755 mContext.getSystemService(StorageManager.class)
1756 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001757 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001758 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001759
1760 // Remove this user from the list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001761 synchronized (mUsersLock) {
1762 mUsers.remove(userHandle);
1763 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001764 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001765 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001766 userFile.delete();
1767 // Update the user list
Fyodor Kupolov82402752015-10-28 14:54:51 -07001768 writeUserListLILP();
1769 updateUserIds();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001770 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1771 }
1772
Amith Yamasani61f57372012-08-31 12:12:28 -07001773 private void removeDirectoryRecursive(File parent) {
1774 if (parent.isDirectory()) {
1775 String[] files = parent.list();
1776 for (String filename : files) {
1777 File child = new File(parent, filename);
1778 removeDirectoryRecursive(child);
1779 }
1780 }
1781 parent.delete();
1782 }
1783
Kenny Guyf8d3a232014-05-15 16:09:52 +01001784 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001785 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001786 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1787 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001788 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1789 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001790 }
1791
Amith Yamasani2a003292012-08-14 18:25:45 -07001792 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001793 public Bundle getApplicationRestrictions(String packageName) {
1794 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1795 }
1796
1797 @Override
1798 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001799 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001800 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001801 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001802 }
1803 synchronized (mPackagesLock) {
1804 // Read the restrictions from XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001805 return readApplicationRestrictionsLP(packageName, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001806 }
1807 }
1808
1809 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001810 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001811 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001812 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001813 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001814 if (restrictions == null || restrictions.isEmpty()) {
1815 cleanAppRestrictionsForPackage(packageName, userId);
1816 } else {
1817 // Write the restrictions to XML
Fyodor Kupolov82402752015-10-28 14:54:51 -07001818 writeApplicationRestrictionsLP(packageName, restrictions, userId);
Kenny Guyd21b2182014-07-17 16:38:55 +01001819 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001820 }
Robin Lee66e5d962014-04-09 16:44:21 +01001821
Kenny Guyd21b2182014-07-17 16:38:55 +01001822 if (isPackageInstalled(packageName, userId)) {
1823 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1824 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1825 changeIntent.setPackage(packageName);
1826 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1827 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1828 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001829 }
1830
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001831 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001832 mHandler.post(new Runnable() {
1833 @Override
1834 public void run() {
1835 List<ApplicationInfo> apps =
1836 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1837 userHandle).getList();
1838 final long ident = Binder.clearCallingIdentity();
1839 try {
1840 for (ApplicationInfo appInfo : apps) {
1841 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001842 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1843 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001844 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001845 userHandle);
1846 }
1847 }
1848 } finally {
1849 Binder.restoreCallingIdentity(ident);
1850 }
1851 }
1852 });
1853 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001854 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001855 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001856 try {
1857 return mContext.getPackageManager().getApplicationInfo(packageName,
1858 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1859 } catch (NameNotFoundException nnfe) {
1860 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001861 } finally {
1862 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001863 }
1864 }
1865
Fyodor Kupolov82402752015-10-28 14:54:51 -07001866 private Bundle readApplicationRestrictionsLP(String packageName, int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001867 AtomicFile restrictionsFile =
1868 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1869 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001870 return readApplicationRestrictionsLP(restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001871 }
1872
1873 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001874 static Bundle readApplicationRestrictionsLP(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001875 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001876 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001877 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001878 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001879 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001880
1881 FileInputStream fis = null;
1882 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001883 fis = restrictionsFile.openRead();
1884 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001885 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001886 XmlUtils.nextElement(parser);
1887 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001888 Slog.e(LOG_TAG, "Unable to read restrictions file "
1889 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001890 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001891 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001892 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1893 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001894 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001895 } catch (IOException|XmlPullParserException e) {
1896 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001897 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001898 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001899 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001900 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001901 }
1902
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001903 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1904 XmlPullParser parser) throws XmlPullParserException, IOException {
1905 int type = parser.getEventType();
1906 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1907 String key = parser.getAttributeValue(null, ATTR_KEY);
1908 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1909 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1910 if (multiple != null) {
1911 values.clear();
1912 int count = Integer.parseInt(multiple);
1913 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1914 if (type == XmlPullParser.START_TAG
1915 && parser.getName().equals(TAG_VALUE)) {
1916 values.add(parser.nextText().trim());
1917 count--;
1918 }
1919 }
1920 String [] valueStrings = new String[values.size()];
1921 values.toArray(valueStrings);
1922 restrictions.putStringArray(key, valueStrings);
1923 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1924 restrictions.putBundle(key, readBundleEntry(parser, values));
1925 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1926 final int outerDepth = parser.getDepth();
1927 ArrayList<Bundle> bundleList = new ArrayList<>();
1928 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1929 Bundle childBundle = readBundleEntry(parser, values);
1930 bundleList.add(childBundle);
1931 }
1932 restrictions.putParcelableArray(key,
1933 bundleList.toArray(new Bundle[bundleList.size()]));
1934 } else {
1935 String value = parser.nextText().trim();
1936 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1937 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1938 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1939 restrictions.putInt(key, Integer.parseInt(value));
1940 } else {
1941 restrictions.putString(key, value);
1942 }
1943 }
1944 }
1945 }
1946
1947 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1948 throws IOException, XmlPullParserException {
1949 Bundle childBundle = new Bundle();
1950 final int outerDepth = parser.getDepth();
1951 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1952 readEntry(childBundle, values, parser);
1953 }
1954 return childBundle;
1955 }
1956
Fyodor Kupolov82402752015-10-28 14:54:51 -07001957 private void writeApplicationRestrictionsLP(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001958 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001959 AtomicFile restrictionsFile = new AtomicFile(
1960 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001961 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov82402752015-10-28 14:54:51 -07001962 writeApplicationRestrictionsLP(restrictions, restrictionsFile);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001963 }
1964
1965 @VisibleForTesting
Fyodor Kupolov82402752015-10-28 14:54:51 -07001966 static void writeApplicationRestrictionsLP(Bundle restrictions, AtomicFile restrictionsFile) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001967 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001968 try {
1969 fos = restrictionsFile.startWrite();
1970 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1971
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001972 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001973 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001974 serializer.startDocument(null, true);
1975 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1976
1977 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001978 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001979 serializer.endTag(null, TAG_RESTRICTIONS);
1980
1981 serializer.endDocument();
1982 restrictionsFile.finishWrite(fos);
1983 } catch (Exception e) {
1984 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001985 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1986 }
1987 }
1988
1989 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1990 throws IOException {
1991 for (String key : restrictions.keySet()) {
1992 Object value = restrictions.get(key);
1993 serializer.startTag(null, TAG_ENTRY);
1994 serializer.attribute(null, ATTR_KEY, key);
1995
1996 if (value instanceof Boolean) {
1997 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1998 serializer.text(value.toString());
1999 } else if (value instanceof Integer) {
2000 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
2001 serializer.text(value.toString());
2002 } else if (value == null || value instanceof String) {
2003 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
2004 serializer.text(value != null ? (String) value : "");
2005 } else if (value instanceof Bundle) {
2006 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2007 writeBundle((Bundle) value, serializer);
2008 } else if (value instanceof Parcelable[]) {
2009 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
2010 Parcelable[] array = (Parcelable[]) value;
2011 for (Parcelable parcelable : array) {
2012 if (!(parcelable instanceof Bundle)) {
2013 throw new IllegalArgumentException("bundle-array can only hold Bundles");
2014 }
2015 serializer.startTag(null, TAG_ENTRY);
2016 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
2017 writeBundle((Bundle) parcelable, serializer);
2018 serializer.endTag(null, TAG_ENTRY);
2019 }
2020 } else {
2021 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
2022 String[] values = (String[]) value;
2023 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
2024 for (String choice : values) {
2025 serializer.startTag(null, TAG_VALUE);
2026 serializer.text(choice != null ? choice : "");
2027 serializer.endTag(null, TAG_VALUE);
2028 }
2029 }
2030 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002031 }
2032 }
2033
2034 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07002035 public int getUserSerialNumber(int userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002036 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002037 if (!exists(userHandle)) return -1;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002038 return getUserInfoLU(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07002039 }
2040 }
2041
2042 @Override
2043 public int getUserHandle(int userSerialNumber) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002044 synchronized (mUsersLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07002045 for (int userId : mUserIds) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002046 UserInfo info = getUserInfoLU(userId);
Kenny Guy945f8832015-02-10 15:17:26 +00002047 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07002048 }
2049 // Not found
2050 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07002051 }
2052 }
2053
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002054 @Override
2055 public long getUserCreationTime(int userHandle) {
2056 int callingUserId = UserHandle.getCallingUserId();
2057 UserInfo userInfo = null;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002058 synchronized (mUsersLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002059 if (callingUserId == userHandle) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002060 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002061 } else {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002062 UserInfo parent = getProfileParentLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002063 if (parent != null && parent.id == callingUserId) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002064 userInfo = getUserInfoLU(userHandle);
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07002065 }
2066 }
2067 }
2068 if (userInfo == null) {
2069 throw new SecurityException("userHandle can only be the calling user or a managed "
2070 + "profile associated with this user");
2071 }
2072 return userInfo.creationTime;
2073 }
2074
Amith Yamasani0b285492011-04-14 17:35:23 -07002075 /**
2076 * Caches the list of user ids in an array, adjusting the array size when necessary.
2077 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002078 private void updateUserIds() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002079 int num = 0;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002080 synchronized (mUsersLock) {
2081 final int userSize = mUsers.size();
2082 for (int i = 0; i < userSize; i++) {
2083 if (!mUsers.valueAt(i).partial) {
2084 num++;
2085 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002086 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002087 final int[] newUsers = new int[num];
2088 int n = 0;
2089 for (int i = 0; i < userSize; i++) {
2090 if (!mUsers.valueAt(i).partial) {
2091 newUsers[n++] = mUsers.keyAt(i);
2092 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002093 }
Fyodor Kupolov82402752015-10-28 14:54:51 -07002094 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002095 }
2096 }
2097
2098 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002099 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002100 * @param userId the user that was just foregrounded
2101 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002102 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002103 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002104 UserInfo user = getUserInfoNoChecks(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -07002105 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002106 if (user == null || user.partial) {
2107 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2108 return;
2109 }
2110 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002111 user.lastLoggedInTime = now;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002112 scheduleWriteUserLP(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002113 }
2114 }
2115 }
2116
2117 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002118 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002119 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2120 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002121 * @return
2122 */
Fyodor Kupolov82402752015-10-28 14:54:51 -07002123 private int getNextAvailableId() {
2124 synchronized (mUsersLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002125 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002126 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002127 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002128 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002129 }
2130 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002131 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002132 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002133 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002134 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002135
Amith Yamasanifc95e702013-09-26 13:20:17 -07002136 private String packageToRestrictionsFileName(String packageName) {
2137 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2138 }
2139
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002140 /**
2141 * Create new {@code /data/user/[id]} directory and sets default
2142 * permissions.
2143 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002144 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2145 final StorageManager storage = context.getSystemService(StorageManager.class);
2146 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2147 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002148 }
2149
2150 /**
2151 * Enforce that serial number stored in user directory inode matches the
2152 * given expected value. Gracefully sets the serial number if currently
2153 * undefined.
2154 *
2155 * @throws IOException when problem extracting serial number, or serial
2156 * number is mismatched.
2157 */
2158 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2159 final int foundSerial = getSerialNumber(file);
2160 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2161
2162 if (foundSerial == -1) {
2163 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2164 try {
2165 setSerialNumber(file, serialNumber);
2166 } catch (IOException e) {
2167 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2168 }
2169
2170 } else if (foundSerial != serialNumber) {
2171 throw new IOException("Found serial number " + foundSerial
2172 + " doesn't match expected " + serialNumber);
2173 }
2174 }
2175
2176 /**
2177 * Set serial number stored in user directory inode.
2178 *
2179 * @throws IOException if serial number was already set
2180 */
2181 private static void setSerialNumber(File file, int serialNumber)
2182 throws IOException {
2183 try {
2184 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2185 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2186 } catch (ErrnoException e) {
2187 throw e.rethrowAsIOException();
2188 }
2189 }
2190
2191 /**
2192 * Return serial number stored in user directory inode.
2193 *
2194 * @return parsed serial number, or -1 if not set
2195 */
2196 private static int getSerialNumber(File file) throws IOException {
2197 try {
2198 final byte[] buf = new byte[256];
2199 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2200 final String serial = new String(buf, 0, len);
2201 try {
2202 return Integer.parseInt(serial);
2203 } catch (NumberFormatException e) {
2204 throw new IOException("Bad serial number: " + serial);
2205 }
2206 } catch (ErrnoException e) {
2207 if (e.errno == OsConstants.ENODATA) {
2208 return -1;
2209 } else {
2210 throw e.rethrowAsIOException();
2211 }
2212 }
2213 }
2214
Amith Yamasani920ace02012-09-20 22:15:37 -07002215 @Override
2216 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2217 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2218 != PackageManager.PERMISSION_GRANTED) {
2219 pw.println("Permission Denial: can't dump UserManager from from pid="
2220 + Binder.getCallingPid()
2221 + ", uid=" + Binder.getCallingUid()
2222 + " without permission "
2223 + android.Manifest.permission.DUMP);
2224 return;
2225 }
2226
2227 long now = System.currentTimeMillis();
2228 StringBuilder sb = new StringBuilder();
2229 synchronized (mPackagesLock) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002230 synchronized (mUsersLock) {
2231 pw.println("Users:");
2232 for (int i = 0; i < mUsers.size(); i++) {
2233 UserInfo user = mUsers.valueAt(i);
2234 if (user == null) {
2235 continue;
2236 }
2237 pw.print(" "); pw.print(user);
2238 pw.print(" serialNo="); pw.print(user.serialNumber);
2239 if (mRemovingUserIds.get(mUsers.keyAt(i))) {
2240 pw.print(" <removing> ");
2241 }
2242 if (user.partial) {
2243 pw.print(" <partial>");
2244 }
2245 pw.println();
2246 pw.print(" Created: ");
2247 if (user.creationTime == 0) {
2248 pw.println("<unknown>");
2249 } else {
2250 sb.setLength(0);
2251 TimeUtils.formatDuration(now - user.creationTime, sb);
2252 sb.append(" ago");
2253 pw.println(sb);
2254 }
2255 pw.print(" Last logged in: ");
2256 if (user.lastLoggedInTime == 0) {
2257 pw.println("<unknown>");
2258 } else {
2259 sb.setLength(0);
2260 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2261 sb.append(" ago");
2262 pw.println(sb);
2263 }
2264 pw.println(" Restrictions:");
2265 synchronized (mRestrictionsLock) {
2266 UserRestrictionsUtils.dumpRestrictions(
2267 pw, " ", mBaseUserRestrictions.get(user.id));
2268 pw.println(" Effective restrictions:");
2269 UserRestrictionsUtils.dumpRestrictions(
2270 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
2271 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002272 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002273 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002274 pw.println();
2275 pw.println("Guest restrictions:");
2276 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002277 }
2278 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002279
2280 final class MainHandler extends Handler {
2281
2282 @Override
2283 public void handleMessage(Message msg) {
2284 switch (msg.what) {
2285 case WRITE_USER_MSG:
2286 removeMessages(WRITE_USER_MSG, msg.obj);
2287 synchronized (mPackagesLock) {
2288 int userId = ((UserInfo) msg.obj).id;
Fyodor Kupolov82402752015-10-28 14:54:51 -07002289 UserInfo userInfo = getUserInfoNoChecks(userId);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002290 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002291 writeUserLP(userInfo);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002292 }
2293 }
2294 }
2295 }
2296 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002297
2298 /**
2299 * @param userId
2300 * @return whether the user has been initialized yet
2301 */
2302 boolean isInitialized(int userId) {
2303 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2304 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002305
2306 private class LocalService extends UserManagerInternal {
2307
2308 @Override
2309 public Object getUserRestrictionsLock() {
2310 return mRestrictionsLock;
2311 }
2312
2313 @Override
2314 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002315 public void updateEffectiveUserRestrictionsLR(int userId) {
2316 UserManagerService.this.updateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002317 }
2318
2319 @Override
2320 @GuardedBy("mRestrictionsLock")
Fyodor Kupolov82402752015-10-28 14:54:51 -07002321 public void updateEffectiveUserRestrictionsForAllUsersLR() {
2322 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersLR();
Makoto Onuki068c54a2015-10-13 14:34:03 -07002323 }
2324
2325 @Override
2326 public Bundle getBaseUserRestrictions(int userId) {
2327 synchronized (mRestrictionsLock) {
2328 return mBaseUserRestrictions.get(userId);
2329 }
2330 }
2331
2332 @Override
2333 public void setBaseUserRestrictionsByDpmsForMigration(
2334 int userId, Bundle baseRestrictions) {
2335 synchronized (mRestrictionsLock) {
2336 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
Fyodor Kupolov82402752015-10-28 14:54:51 -07002337 invalidateEffectiveUserRestrictionsLR(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002338 }
2339
Fyodor Kupolov82402752015-10-28 14:54:51 -07002340 final UserInfo userInfo = getUserInfoNoChecks(userId);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002341 synchronized (mPackagesLock) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07002342 if (userInfo != null) {
Fyodor Kupolov82402752015-10-28 14:54:51 -07002343 writeUserLP(userInfo);
Makoto Onuki068c54a2015-10-13 14:34:03 -07002344 } else {
2345 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2346 }
2347 }
2348 }
2349 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002350}