blob: 0b13fb10e78a01a15afb47d9bb6790a3a7acacf2 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Xiaohui Chen594f2082015-08-18 11:04:20 -070019import android.annotation.NonNull;
Makoto Onuki068c54a2015-10-13 14:34:03 -070020import android.annotation.Nullable;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Amith Yamasani515d4062015-09-28 11:30:06 -070023import android.app.ActivityManagerInternal;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070024import android.app.ActivityManagerNative;
Todd Kennedy60459ab2015-10-30 11:32:16 -070025import android.app.IActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.IStopUserCallback;
Xiaohui Chen203243a2015-07-16 11:55:47 -070027import android.app.admin.DevicePolicyManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070028import android.app.admin.DevicePolicyManagerInternal;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070029import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070030import android.content.Context;
31import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070032import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070033import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080034import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070036import android.graphics.Bitmap;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080038import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070039import android.os.Environment;
40import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080041import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080043import android.os.Message;
Adrian Roos1bdff912015-02-17 15:51:35 +010044import android.os.ParcelFileDescriptor;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070045import android.os.Parcelable;
Amith Yamasani258848d2012-08-10 17:06:33 -070046import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070047import android.os.RemoteException;
Todd Kennedy60459ab2015-10-30 11:32:16 -070048import android.os.ResultReceiver;
Jason Monk62062992014-05-06 09:55:28 -040049import android.os.ServiceManager;
Todd Kennedy60459ab2015-10-30 11:32:16 -070050import android.os.ShellCommand;
Clara Bayarrif05b9d02015-10-23 13:25:19 +010051import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070052import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070053import android.os.UserManager;
Makoto Onuki068c54a2015-10-13 14:34:03 -070054import android.os.UserManagerInternal;
Paul Crowley85e4e812015-05-19 12:42:00 +010055import android.os.storage.StorageManager;
Jeff Sharkey6dce4962015-07-03 18:08:41 -070056import android.os.storage.VolumeInfo;
57import android.system.ErrnoException;
58import android.system.Os;
59import android.system.OsConstants;
Amith Yamasani2a003292012-08-14 18:25:45 -070060import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070061import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import android.util.Slog;
63import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080064import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import android.util.Xml;
67
Makoto Onuki068c54a2015-10-13 14:34:03 -070068import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070069import com.android.internal.annotations.VisibleForTesting;
Jason Monk62062992014-05-06 09:55:28 -040070import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080071import com.android.internal.util.FastXmlSerializer;
Makoto Onuki068c54a2015-10-13 14:34:03 -070072import com.android.internal.util.Preconditions;
Fyodor Kupolov262f9952015-03-23 18:55:11 -070073import com.android.internal.util.XmlUtils;
Amith Yamasani515d4062015-09-28 11:30:06 -070074import com.android.server.LocalServices;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080075
76import org.xmlpull.v1.XmlPullParser;
77import org.xmlpull.v1.XmlPullParserException;
78import org.xmlpull.v1.XmlSerializer;
79
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080import java.io.BufferedOutputStream;
81import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070082import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085import java.io.FileOutputStream;
86import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070087import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010088import java.nio.charset.StandardCharsets;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070089import java.util.ArrayList;
90import java.util.List;
91
Fyodor Kupolov262f9952015-03-23 18:55:11 -070092import libcore.io.IoUtils;
93
Makoto Onuki068c54a2015-10-13 14:34:03 -070094/**
95 * Service for {@link UserManager}.
96 *
97 * Method naming convention:
98 * - Methods suffixed with "Locked" should be called within the {@code this} lock.
99 * - Methods suffixed with "RL" should be called within the {@link #mRestrictionsLock} lock.
100 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700101public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700102
Amith Yamasani2a003292012-08-14 18:25:45 -0700103 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700104
Makoto Onuki068c54a2015-10-13 14:34:03 -0700105 private static final boolean DBG = false; // DO NOT SUBMIT WITH TRUE
Amith Yamasani16389312012-10-17 21:20:14 -0700106
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700108 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700109 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -0700111 private static final String ATTR_CREATION_TIME = "created";
112 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -0700113 private static final String ATTR_SERIAL_NO = "serialNumber";
114 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700115 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -0700116 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -0700117 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +0100118 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700119 private static final String ATTR_RESTRICTED_PROFILE_PARENT_ID = "restrictedProfileParentId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530120 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700121 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700122 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800123 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800124 private static final String TAG_ENTRY = "entry";
125 private static final String TAG_VALUE = "value";
126 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700127 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800128 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700129
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700130 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
131 private static final String ATTR_TYPE_STRING = "s";
132 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700133 private static final String ATTR_TYPE_INTEGER = "i";
Fyodor Kupolov262f9952015-03-23 18:55:11 -0700134 private static final String ATTR_TYPE_BUNDLE = "B";
135 private static final String ATTR_TYPE_BUNDLE_ARRAY = "BA";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700136
Amith Yamasani0b285492011-04-14 17:35:23 -0700137 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700139 private static final String USER_PHOTO_FILENAME = "photo.png";
Adrian Roos1bdff912015-02-17 15:51:35 +0100140 private static final String USER_PHOTO_FILENAME_TMP = USER_PHOTO_FILENAME + ".tmp";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800142 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700143 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800144
Amith Yamasani634cf312012-10-04 17:34:21 -0700145 private static final int MIN_USER_ID = 10;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700146 // We need to keep process uid within Integer.MAX_VALUE.
147 private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
Amith Yamasani634cf312012-10-04 17:34:21 -0700148
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700149 private static final int USER_VERSION = 6;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700150
Amith Yamasani920ace02012-09-20 22:15:37 -0700151 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
152
Nicolas Prevotb8186812015-08-06 15:00:03 +0100153 // Maximum number of managed profiles permitted per user is 1. This cannot be increased
Amith Yamasani95ab7842014-08-11 17:09:26 -0700154 // without first making sure that the rest of the framework is prepared for it.
155 private static final int MAX_MANAGED_PROFILES = 1;
156
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800157 static final int WRITE_USER_MSG = 1;
158 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530159
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700160 private static final String XATTR_SERIAL = "user.serial";
161
Dianne Hackborn4428e172012-08-24 17:43:05 -0700162 private final Context mContext;
163 private final PackageManagerService mPm;
164 private final Object mInstallLock;
165 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700166
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800167 private final Handler mHandler;
168
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700169 private final File mUsersDir;
170 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700171
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800172 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Makoto Onuki068c54a2015-10-13 14:34:03 -0700173
174 private final Object mRestrictionsLock = new Object();
175
176 /**
177 * User restrictions set via UserManager. This doesn't include restrictions set by
178 * device owner / profile owners.
179 *
180 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
181 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
182 * maybe shared between {@link #mBaseUserRestrictions} and
183 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
184 * (Otherwise we won't be able to detect what restrictions have changed in
185 * {@link #updateUserRestrictionsInternalRL).
186 */
187 @GuardedBy("mRestrictionsLock")
188 private final SparseArray<Bundle> mBaseUserRestrictions = new SparseArray<>();
189
190 /**
191 * Cached user restrictions that are in effect -- i.e. {@link #mBaseUserRestrictions} combined
192 * with device / profile owner restrictions. We'll initialize it lazily; use
193 * {@link #getEffectiveUserRestrictions} to access it.
194 *
195 * DO NOT Change existing {@link Bundle} in it. When changing a restriction for a user,
196 * a new {@link Bundle} should always be created and set. This is because a {@link Bundle}
197 * maybe shared between {@link #mBaseUserRestrictions} and
198 * {@link #mCachedEffectiveUserRestrictions}, but they should always updated separately.
199 * (Otherwise we won't be able to detect what restrictions have changed in
200 * {@link #updateUserRestrictionsInternalRL).
201 */
202 @GuardedBy("mRestrictionsLock")
203 private final SparseArray<Bundle> mCachedEffectiveUserRestrictions = new SparseArray<>();
204
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530205 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800206
207 /**
208 * Set of user IDs being actively removed. Removed IDs linger in this set
209 * for several seconds to work around a VFS caching issue.
210 */
211 // @GuardedBy("mPackagesLock")
212 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700213
Amith Yamasani0b285492011-04-14 17:35:23 -0700214 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700215 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700216 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700217
Jason Monk62062992014-05-06 09:55:28 -0400218 private IAppOpsService mAppOpsService;
219
Makoto Onuki068c54a2015-10-13 14:34:03 -0700220 private final LocalService mLocalService;
221
Amith Yamasani258848d2012-08-10 17:06:33 -0700222 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700223
Dianne Hackborn4428e172012-08-24 17:43:05 -0700224 public static UserManagerService getInstance() {
225 synchronized (UserManagerService.class) {
226 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700227 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700228 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700229
230 /**
231 * Available for testing purposes.
232 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700233 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700235 }
236
Dianne Hackborn4428e172012-08-24 17:43:05 -0700237 /**
238 * Called by package manager to create the service. This is closely
239 * associated with the package manager, and the given lock is the
240 * package manager's own lock.
241 */
242 UserManagerService(Context context, PackageManagerService pm,
243 Object installLock, Object packagesLock) {
244 this(context, pm, installLock, packagesLock,
245 Environment.getDataDirectory(),
246 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700247 }
248
Dianne Hackborn4428e172012-08-24 17:43:05 -0700249 /**
250 * Available for testing purposes.
251 */
252 private UserManagerService(Context context, PackageManagerService pm,
253 Object installLock, Object packagesLock,
254 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 mContext = context;
256 mPm = pm;
257 mInstallLock = installLock;
258 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800259 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700260 synchronized (mInstallLock) {
261 synchronized (mPackagesLock) {
262 mUsersDir = new File(dataDir, USER_INFO_DIR);
263 mUsersDir.mkdirs();
264 // Make zeroth user directory, for services to migrate their files to that location
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700265 File userZeroDir = new File(mUsersDir, String.valueOf(UserHandle.USER_SYSTEM));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700266 userZeroDir.mkdirs();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700267 FileUtils.setPermissions(mUsersDir.toString(),
268 FileUtils.S_IRWXU|FileUtils.S_IRWXG
269 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
270 -1, -1);
271 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800272 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700273 readUserListLocked();
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700274 sInstance = this;
275 }
276 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700277 mLocalService = new LocalService();
278 LocalServices.addService(UserManagerInternal.class, mLocalService);
Xiaohui Chen4be96e42015-05-06 09:55:43 -0700279 }
280
281 void systemReady() {
282 synchronized (mInstallLock) {
283 synchronized (mPackagesLock) {
Amith Yamasani756901d2012-10-12 12:30:07 -0700284 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700285 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
Amith Yamasani515d4062015-09-28 11:30:06 -0700286 final int userSize = mUsers.size();
287 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700288 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700289 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700290 partials.add(ui);
291 }
292 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700293 final int partialsSize = partials.size();
294 for (int i = 0; i < partialsSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700295 UserInfo ui = partials.get(i);
Amith Yamasania7892482015-08-07 11:09:05 -0700296 Slog.w(LOG_TAG, "Removing partially created user " + ui.id
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700297 + " (name=" + ui.name + ")");
298 removeUserStateLocked(ui.id);
299 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700300 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700301 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700302 onUserForeground(UserHandle.USER_SYSTEM);
Jason Monk62062992014-05-06 09:55:28 -0400303 mAppOpsService = IAppOpsService.Stub.asInterface(
304 ServiceManager.getService(Context.APP_OPS_SERVICE));
305 for (int i = 0; i < mUserIds.length; ++i) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700306 final int userId = mUserIds[i];
Jason Monk62062992014-05-06 09:55:28 -0400307 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700308 mAppOpsService.setUserRestrictions(getEffectiveUserRestrictions(userId), userId);
Jason Monk62062992014-05-06 09:55:28 -0400309 } catch (RemoteException e) {
310 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
311 }
312 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700313 }
314
315 @Override
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700316 public UserInfo getPrimaryUser() {
317 checkManageUsersPermission("query users");
318 synchronized (mPackagesLock) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700319 final int userSize = mUsers.size();
320 for (int i = 0; i < userSize; i++) {
Xiaohui Chen70f6c382015-04-28 14:21:43 -0700321 UserInfo ui = mUsers.valueAt(i);
322 if (ui.isPrimary()) {
323 return ui;
324 }
325 }
326 }
327 return null;
328 }
329
330 @Override
Xiaohui Chen594f2082015-08-18 11:04:20 -0700331 public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700332 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700333 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700334 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasani515d4062015-09-28 11:30:06 -0700335 final int userSize = mUsers.size();
336 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700337 UserInfo ui = mUsers.valueAt(i);
338 if (ui.partial) {
339 continue;
340 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800341 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700342 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700343 }
Amith Yamasani13593602012-03-22 16:16:17 -0700344 }
345 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700346 }
Amith Yamasani13593602012-03-22 16:16:17 -0700347 }
348
Amith Yamasani258848d2012-08-10 17:06:33 -0700349 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100350 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800351 if (userId != UserHandle.getCallingUserId()) {
352 checkManageUsersPermission("getting profiles related to user " + userId);
353 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700354 final long ident = Binder.clearCallingIdentity();
355 try {
356 synchronized (mPackagesLock) {
357 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100358 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700359 } finally {
360 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000361 }
362 }
363
Amith Yamasanibe465322014-04-24 13:45:17 -0700364 /** Assume permissions already checked and caller's identity cleared */
365 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700366 UserInfo user = getUserInfoLocked(userId);
367 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700368 if (user == null) {
369 // Probably a dying user
370 return users;
371 }
Amith Yamasani515d4062015-09-28 11:30:06 -0700372 final int userSize = mUsers.size();
373 for (int i = 0; i < userSize; i++) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700374 UserInfo profile = mUsers.valueAt(i);
375 if (!isProfileOf(user, profile)) {
376 continue;
377 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100378 if (enabledOnly && !profile.isEnabled()) {
379 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700380 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700381 if (mRemovingUserIds.get(profile.id)) {
382 continue;
383 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700384 users.add(profile);
385 }
386 return users;
387 }
388
Jessica Hummelbe81c802014-04-22 15:49:22 +0100389 @Override
Andres Moralesc5548c02015-08-05 10:23:12 -0700390 public int getCredentialOwnerProfile(int userHandle) {
391 checkManageUsersPermission("get the credential owner");
Clara Bayarrif05b9d02015-10-23 13:25:19 +0100392 if (!"file".equals(SystemProperties.get("ro.crypto.type", "none"))) {
Andres Moralesc5548c02015-08-05 10:23:12 -0700393 synchronized (mPackagesLock) {
394 UserInfo profileParent = getProfileParentLocked(userHandle);
395 if (profileParent != null) {
396 return profileParent.id;
397 }
398 }
399 }
400
401 return userHandle;
402 }
403
404 @Override
Xiaohui Chenfd5b7742015-10-14 15:47:04 -0700405 public boolean isSameProfileGroup(int userId, int otherUserId) {
406 if (userId == otherUserId) return true;
407 checkManageUsersPermission("check if in the same profile group");
408 synchronized (mPackagesLock) {
409 return isSameProfileGroupLocked(userId, otherUserId);
410 }
411 }
412
413 private boolean isSameProfileGroupLocked(int userId, int otherUserId) {
414 UserInfo userInfo = getUserInfoLocked(userId);
415 if (userInfo == null || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
416 return false;
417 }
418 UserInfo otherUserInfo = getUserInfoLocked(otherUserId);
419 if (otherUserInfo == null || otherUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
420 return false;
421 }
422 return userInfo.profileGroupId == otherUserInfo.profileGroupId;
423 }
424
425 @Override
Jessica Hummelbe81c802014-04-22 15:49:22 +0100426 public UserInfo getProfileParent(int userHandle) {
427 checkManageUsersPermission("get the profile parent");
428 synchronized (mPackagesLock) {
Fyodor Kupolovff7233e2015-04-08 11:28:52 -0700429 return getProfileParentLocked(userHandle);
430 }
431 }
432
433 private UserInfo getProfileParentLocked(int userHandle) {
434 UserInfo profile = getUserInfoLocked(userHandle);
435 if (profile == null) {
436 return null;
437 }
438 int parentUserId = profile.profileGroupId;
439 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
440 return null;
441 } else {
442 return getUserInfoLocked(parentUserId);
Jessica Hummelbe81c802014-04-22 15:49:22 +0100443 }
444 }
445
Kenny Guy2a764942014-04-02 13:29:20 +0100446 private boolean isProfileOf(UserInfo user, UserInfo profile) {
447 return user.id == profile.id ||
448 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
449 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000450 }
451
452 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100453 public void setUserEnabled(int userId) {
454 checkManageUsersPermission("enable user");
455 synchronized (mPackagesLock) {
456 UserInfo info = getUserInfoLocked(userId);
457 if (info != null && !info.isEnabled()) {
458 info.flags ^= UserInfo.FLAG_DISABLED;
459 writeUserLocked(info);
460 }
461 }
462 }
463
464 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700465 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700466 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700467 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700468 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700469 }
470 }
471
Amith Yamasani71e6c692013-03-24 17:39:28 -0700472 @Override
473 public boolean isRestricted() {
474 synchronized (mPackagesLock) {
475 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
476 }
477 }
478
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700479 @Override
480 public boolean canHaveRestrictedProfile(int userId) {
481 checkManageUsersPermission("canHaveRestrictedProfile");
482 synchronized (mPackagesLock) {
483 final UserInfo userInfo = getUserInfoLocked(userId);
484 if (userInfo == null || !userInfo.canHaveProfile()) {
485 return false;
486 }
487 if (!userInfo.isAdmin()) {
488 return false;
489 }
490 }
491 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
492 Context.DEVICE_POLICY_SERVICE);
493 // restricted profile can be created if there is no DO set and the admin user has no PO
494 return dpm.getDeviceOwner() == null && dpm.getProfileOwnerAsUser(userId) == null;
495 }
496
Amith Yamasani195263742012-08-21 15:40:12 -0700497 /*
498 * Should be locked on mUsers before calling this.
499 */
500 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700501 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700502 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800503 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700504 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
505 return null;
506 }
507 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700508 }
509
Amith Yamasani236b2b52015-08-18 14:32:14 -0700510 /** Called by PackageManagerService */
Amith Yamasani13593602012-03-22 16:16:17 -0700511 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700512 synchronized (mPackagesLock) {
Amith Yamasani236b2b52015-08-18 14:32:14 -0700513 return mUsers.get(userId) != null;
Amith Yamasani13593602012-03-22 16:16:17 -0700514 }
515 }
516
Amith Yamasani258848d2012-08-10 17:06:33 -0700517 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700518 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700519 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700520 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700521 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700522 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700523 if (info == null || info.partial) {
524 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
525 return;
526 }
Amith Yamasani13593602012-03-22 16:16:17 -0700527 if (name != null && !name.equals(info.name)) {
528 info.name = name;
529 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700530 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700531 }
532 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700533 if (changed) {
534 sendUserInfoChangedBroadcast(userId);
535 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700536 }
537
Amith Yamasani258848d2012-08-10 17:06:33 -0700538 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700539 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700540 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400541 long ident = Binder.clearCallingIdentity();
542 try {
543 synchronized (mPackagesLock) {
544 UserInfo info = mUsers.get(userId);
545 if (info == null || info.partial) {
546 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
547 return;
548 }
549 writeBitmapLocked(info, bitmap);
550 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700551 }
Jason Monk9a944532014-07-08 09:31:21 -0400552 sendUserInfoChangedBroadcast(userId);
553 } finally {
554 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700555 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700556 }
557
558 private void sendUserInfoChangedBroadcast(int userId) {
559 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
560 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
561 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700562 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700563 }
564
Amith Yamasani258848d2012-08-10 17:06:33 -0700565 @Override
Adrian Roos1bdff912015-02-17 15:51:35 +0100566 public ParcelFileDescriptor getUserIcon(int userId) {
567 String iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700568 synchronized (mPackagesLock) {
569 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700570 if (info == null || info.partial) {
571 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
572 return null;
573 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100574 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
575 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
576 || callingGroupId != info.profileGroupId) {
577 checkManageUsersPermission("get the icon of a user who is not related");
578 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700579 if (info.iconPath == null) {
580 return null;
581 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100582 iconPath = info.iconPath;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700583 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100584
585 try {
586 return ParcelFileDescriptor.open(
587 new File(iconPath), ParcelFileDescriptor.MODE_READ_ONLY);
588 } catch (FileNotFoundException e) {
589 Log.e(LOG_TAG, "Couldn't find icon file", e);
590 }
591 return null;
Amith Yamasani3b49f072012-09-17 10:21:43 -0700592 }
593
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700594 public void makeInitialized(int userId) {
595 checkManageUsersPermission("makeInitialized");
596 synchronized (mPackagesLock) {
597 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700598 if (info == null || info.partial) {
599 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
600 }
601 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700602 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800603 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700604 }
605 }
606 }
607
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700608 /**
609 * If default guest restrictions haven't been initialized yet, add the basic
610 * restrictions.
611 */
612 private void initDefaultGuestRestrictions() {
613 if (mGuestRestrictions.isEmpty()) {
614 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800615 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700616 }
617 }
618
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800619 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530620 public Bundle getDefaultGuestRestrictions() {
621 checkManageUsersPermission("getDefaultGuestRestrictions");
622 synchronized (mPackagesLock) {
623 return new Bundle(mGuestRestrictions);
624 }
625 }
626
627 @Override
628 public void setDefaultGuestRestrictions(Bundle restrictions) {
629 checkManageUsersPermission("setDefaultGuestRestrictions");
630 synchronized (mPackagesLock) {
631 mGuestRestrictions.clear();
632 mGuestRestrictions.putAll(restrictions);
633 writeUserListLocked();
634 }
635 }
636
Makoto Onuki068c54a2015-10-13 14:34:03 -0700637 @GuardedBy("mRestrictionsLock")
638 private Bundle computeEffectiveUserRestrictionsRL(int userId) {
639 final DevicePolicyManagerInternal dpmi =
640 LocalServices.getService(DevicePolicyManagerInternal.class);
641 final Bundle systemRestrictions = mBaseUserRestrictions.get(userId);
642
643 final Bundle effective;
644 if (dpmi == null) {
645 // TODO Make sure it's because DPMS is disabled and not because we called it too early.
646 effective = systemRestrictions;
647 } else {
648 effective = dpmi.getComposedUserRestrictions(userId, systemRestrictions);
649 }
650 return effective;
651 }
652
653 @GuardedBy("mRestrictionsLock")
654 private void invalidateEffectiveUserRestrictionsRL(int userId) {
655 if (DBG) {
656 Log.d(LOG_TAG, "invalidateEffectiveUserRestrictions userId=" + userId);
657 }
658 mCachedEffectiveUserRestrictions.remove(userId);
659 }
660
661 private Bundle getEffectiveUserRestrictions(int userId) {
662 synchronized (mRestrictionsLock) {
663 Bundle restrictions = mCachedEffectiveUserRestrictions.get(userId);
664 if (restrictions == null) {
665 restrictions = computeEffectiveUserRestrictionsRL(userId);
666 mCachedEffectiveUserRestrictions.put(userId, restrictions);
667 }
668 return restrictions;
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700669 }
670 }
671
Makoto Onuki068c54a2015-10-13 14:34:03 -0700672 /** @return a specific user restriction that's in effect currently. */
673 @Override
674 public boolean hasUserRestriction(String restrictionKey, int userId) {
675 Bundle restrictions = getEffectiveUserRestrictions(userId);
676 return restrictions != null && restrictions.getBoolean(restrictionKey);
677 }
678
679 /**
680 * @return UserRestrictions that are in effect currently. This always returns a new
681 * {@link Bundle}.
682 */
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700683 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800684 public Bundle getUserRestrictions(int userId) {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700685 Bundle restrictions = getEffectiveUserRestrictions(userId);
686 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800687 }
688
689 @Override
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700690 public void setUserRestriction(String key, boolean value, int userId) {
Fyodor Kupolovd4b26042015-07-27 14:30:59 -0700691 checkManageUsersPermission("setUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700692 if (!UserRestrictionsUtils.SYSTEM_CONTROLLED_USER_RESTRICTIONS.contains(key)) {
693 setUserRestrictionNoCheck(key, value, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700694 }
695 }
696
697 @Override
698 public void setSystemControlledUserRestriction(String key, boolean value, int userId) {
699 checkSystemOrRoot("setSystemControlledUserRestriction");
Makoto Onuki068c54a2015-10-13 14:34:03 -0700700 setUserRestrictionNoCheck(key, value, userId);
701 }
702
703 private void setUserRestrictionNoCheck(String key, boolean value, int userId) {
704 synchronized (mRestrictionsLock) {
705 // Note we can't modify Bundles stored in mBaseUserRestrictions directly, so create
706 // a copy.
707 final Bundle newRestrictions = new Bundle();
708 UserRestrictionsUtils.merge(newRestrictions, mBaseUserRestrictions.get(userId));
709 newRestrictions.putBoolean(key, value);
710
711 updateUserRestrictionsInternalRL(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700712 }
713 }
714
Makoto Onuki068c54a2015-10-13 14:34:03 -0700715 /**
716 * Optionally updating user restrictions, calculate the effective user restrictions by
717 * consulting {@link com.android.server.devicepolicy.DevicePolicyManagerService} and also
718 * apply it to {@link com.android.server.AppOpsService}.
719 * TODO applyUserRestrictionsLocked() should also apply to system settings.
720 *
721 * @param newRestrictions User restrictions to set. If null, only the effective restrictions
722 * will be updated. Note don't pass an existing Bundle in {@link #mBaseUserRestrictions}
723 * or {@link #mCachedEffectiveUserRestrictions}; that'll most likely cause a sub
724 * @param userId target user ID.
725 */
726 @GuardedBy("mRestrictionsLock")
727 private void updateUserRestrictionsInternalRL(
728 @Nullable Bundle newRestrictions, int userId) {
729 if (DBG) {
730 Log.d(LOG_TAG, "updateUserRestrictionsInternalLocked userId=" + userId
731 + " bundle=" + newRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800732 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700733 final Bundle prevRestrictions = getEffectiveUserRestrictions(userId);
734
735 // Update system restrictions.
736 if (newRestrictions != null) {
737 // If newRestrictions == the current one, it's probably a bug.
738 Preconditions.checkState(mBaseUserRestrictions.get(userId) != newRestrictions);
739 Preconditions.checkState(mCachedEffectiveUserRestrictions.get(userId)
740 != newRestrictions);
741 mBaseUserRestrictions.put(userId, newRestrictions);
742 }
743
744 mCachedEffectiveUserRestrictions.put(
745 userId, computeEffectiveUserRestrictionsRL(userId));
746
747 applyUserRestrictionsRL(userId, mBaseUserRestrictions.get(userId), prevRestrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800748 }
749
Makoto Onuki068c54a2015-10-13 14:34:03 -0700750 @GuardedBy("mRestrictionsLock")
751 private void applyUserRestrictionsRL(int userId,
752 Bundle newRestrictions, Bundle prevRestrictions) {
753 final long token = Binder.clearCallingIdentity();
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700754 try {
Makoto Onuki068c54a2015-10-13 14:34:03 -0700755 mAppOpsService.setUserRestrictions(newRestrictions, userId);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700756 } catch (RemoteException e) {
757 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
758 } finally {
759 Binder.restoreCallingIdentity(token);
760 }
Makoto Onuki068c54a2015-10-13 14:34:03 -0700761
762 // TODO Move the code from DPMS.setUserRestriction().
763 }
764
765 @GuardedBy("mRestrictionsLock")
766 private void updateEffectiveUserRestrictionsRL(int userId) {
767 updateUserRestrictionsInternalRL(null, userId);
768 }
769
770 @GuardedBy("mRestrictionsLock")
771 private void updateEffectiveUserRestrictionsForAllUsersRL() {
772 // First, invalidate all cached values.
773 synchronized (mRestrictionsLock) {
774 mCachedEffectiveUserRestrictions.clear();
775 }
776 // We don't want to call into ActivityManagerNative while taking a lock, so we'll call
777 // it on a handler.
778 final Runnable r = new Runnable() {
779 @Override
780 public void run() {
781 // Then get the list of running users.
782 final int[] runningUsers;
783 try {
784 runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
785 } catch (RemoteException e) {
786 Log.w(LOG_TAG, "Unable to access ActivityManagerNative");
787 return;
788 }
789 // Then re-calculate the effective restrictions and apply, only for running users.
790 // It's okay if a new user has started after the getRunningUserIds() call,
791 // because we'll do the same thing (re-calculate the restrictions and apply)
792 // when we start a user.
793 // TODO: "Apply restrictions upon user start hasn't been implemented. Implement it.
794 synchronized (mRestrictionsLock) {
795 for (int i = 0; i < runningUsers.length; i++) {
796 updateUserRestrictionsInternalRL(null, runningUsers[i]);
797 }
798 }
799 }
800 };
801 mHandler.post(r);
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700802 }
803
Amith Yamasani258848d2012-08-10 17:06:33 -0700804 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700805 * Check if we've hit the limit of how many users can be created.
806 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700807 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700808 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
809 }
810
811 @Override
Nicolas Prevotb8186812015-08-06 15:00:03 +0100812 public boolean canAddMoreManagedProfiles(int userId) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700813 checkManageUsersPermission("check if more managed profiles can be added.");
814 if (ActivityManager.isLowRamDeviceStatic()) {
815 return false;
816 }
Fyodor Kupolovb6157992015-06-05 15:32:28 -0700817 if (!mContext.getPackageManager().hasSystemFeature(
818 PackageManager.FEATURE_MANAGED_USERS)) {
819 return false;
820 }
Nicolas Prevotb8186812015-08-06 15:00:03 +0100821 // Limit number of managed profiles that can be created
822 int managedProfilesCount = getProfiles(userId, true).size() - 1;
823 if (managedProfilesCount >= MAX_MANAGED_PROFILES) {
824 return false;
825 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700826 synchronized(mPackagesLock) {
Nicolas Prevotb8186812015-08-06 15:00:03 +0100827 UserInfo userInfo = getUserInfoLocked(userId);
828 if (!userInfo.canHaveProfile()) {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700829 return false;
830 }
831 int usersCount = getAliveUsersExcludingGuestsCountLocked();
832 // We allow creating a managed profile in the special case where there is only one user.
833 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
834 }
835 }
836
837 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700838 int aliveUserCount = 0;
839 final int totalUserCount = mUsers.size();
840 // Skip over users being removed
841 for (int i = 0; i < totalUserCount; i++) {
842 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700843 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700844 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700845 aliveUserCount++;
846 }
847 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700848 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700849 }
850
851 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700852 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700853 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700854 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700855 *
856 * @param message used as message if SecurityException is thrown
857 * @throws SecurityException if the caller is not system or root
858 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700859 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700860 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700861 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400862 && ActivityManager.checkComponentPermission(
863 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700864 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
865 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
866 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400867 }
868
Fyodor Kupolovb5013302015-04-17 17:59:14 -0700869 private static void checkSystemOrRoot(String message) {
870 final int uid = Binder.getCallingUid();
871 if (uid != Process.SYSTEM_UID && uid != 0) {
872 throw new SecurityException("Only system may call: " + message);
873 }
874 }
875
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700876 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700877 try {
878 File dir = new File(mUsersDir, Integer.toString(info.id));
879 File file = new File(dir, USER_PHOTO_FILENAME);
Adrian Roos1bdff912015-02-17 15:51:35 +0100880 File tmp = new File(dir, USER_PHOTO_FILENAME_TMP);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700881 if (!dir.exists()) {
882 dir.mkdir();
883 FileUtils.setPermissions(
884 dir.getPath(),
885 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
886 -1, -1);
887 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700888 FileOutputStream os;
Adrian Roos1bdff912015-02-17 15:51:35 +0100889 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(tmp))
890 && tmp.renameTo(file)) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700891 info.iconPath = file.getAbsolutePath();
892 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700893 try {
894 os.close();
895 } catch (IOException ioe) {
896 // What the ... !
897 }
Adrian Roos1bdff912015-02-17 15:51:35 +0100898 tmp.delete();
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700899 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700900 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700901 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700902 }
903
Amith Yamasani0b285492011-04-14 17:35:23 -0700904 /**
905 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
906 * cache it elsewhere.
907 * @return the array of user ids.
908 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700909 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700910 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700911 return mUserIds;
912 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700913 }
914
Dianne Hackborn4428e172012-08-24 17:43:05 -0700915 int[] getUserIdsLPr() {
916 return mUserIds;
917 }
918
Amith Yamasani13593602012-03-22 16:16:17 -0700919 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700920 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700921 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700922 return;
923 }
924 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700925 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700926 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700927 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100929 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700930 int type;
931 while ((type = parser.next()) != XmlPullParser.START_TAG
932 && type != XmlPullParser.END_DOCUMENT) {
933 ;
934 }
935
936 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700937 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700938 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700939 return;
940 }
941
Amith Yamasani2a003292012-08-14 18:25:45 -0700942 mNextSerialNumber = -1;
943 if (parser.getName().equals(TAG_USERS)) {
944 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
945 if (lastSerialNumber != null) {
946 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
947 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700948 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
949 if (versionNumber != null) {
950 mUserVersion = Integer.parseInt(versionNumber);
951 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700952 }
953
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700954 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530955 if (type == XmlPullParser.START_TAG) {
956 final String name = parser.getName();
957 if (name.equals(TAG_USER)) {
958 String id = parser.getAttributeValue(null, ATTR_ID);
959 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700960
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530961 if (user != null) {
962 mUsers.put(user.id, user);
963 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
964 mNextSerialNumber = user.id + 1;
965 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700966 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530967 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800968 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
969 && type != XmlPullParser.END_TAG) {
970 if (type == XmlPullParser.START_TAG) {
971 if (parser.getName().equals(TAG_RESTRICTIONS)) {
Makoto Onukia4f11972015-10-01 13:19:58 -0700972 UserRestrictionsUtils
973 .readRestrictions(parser, mGuestRestrictions);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800974 }
975 break;
976 }
977 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700978 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700979 }
980 }
Amith Yamasani13593602012-03-22 16:16:17 -0700981 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700982 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700983 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700984 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700985 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700986 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800987 } finally {
988 if (fis != null) {
989 try {
990 fis.close();
991 } catch (IOException e) {
992 }
993 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700994 }
995 }
996
Amith Yamasani6f34b412012-10-22 18:19:27 -0700997 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800998 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700999 */
Amith Yamasani350962c2013-08-06 11:18:53 -07001000 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -07001001 int userVersion = mUserVersion;
1002 if (userVersion < 1) {
1003 // Assign a proper name for the owner, if not initialized correctly before
Xiaohui Chen47f07952015-10-02 14:40:27 -07001004 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001005 if ("Primary".equals(user.name)) {
1006 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001007 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -07001008 }
1009 userVersion = 1;
1010 }
1011
Amith Yamasanibc9625052012-11-15 14:39:18 -08001012 if (userVersion < 2) {
1013 // Owner should be marked as initialized
Xiaohui Chen47f07952015-10-02 14:40:27 -07001014 UserInfo user = mUsers.get(UserHandle.USER_SYSTEM);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001015 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
1016 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001017 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -08001018 }
1019 userVersion = 2;
1020 }
1021
Amith Yamasani350962c2013-08-06 11:18:53 -07001022
Amith Yamasani5e486f52013-08-07 11:06:44 -07001023 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -07001024 userVersion = 4;
1025 }
1026
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001027 if (userVersion < 5) {
1028 initDefaultGuestRestrictions();
1029 userVersion = 5;
1030 }
1031
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001032 if (userVersion < 6) {
1033 final boolean splitSystemUser = UserManager.isSplitSystemUser();
1034 for (int i = 0; i < mUsers.size(); i++) {
1035 UserInfo user = mUsers.valueAt(i);
1036 // In non-split mode, only user 0 can have restricted profiles
1037 if (!splitSystemUser && user.isRestricted()
1038 && (user.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID)) {
1039 user.restrictedProfileParentId = UserHandle.USER_SYSTEM;
1040 scheduleWriteUserLocked(user);
1041 }
1042 }
1043 userVersion = 6;
1044 }
1045
Amith Yamasani6f34b412012-10-22 18:19:27 -07001046 if (userVersion < USER_VERSION) {
1047 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
1048 + USER_VERSION);
1049 } else {
1050 mUserVersion = userVersion;
1051 writeUserListLocked();
1052 }
1053 }
1054
Amith Yamasani13593602012-03-22 16:16:17 -07001055 private void fallbackToSingleUserLocked() {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001056 int flags = UserInfo.FLAG_INITIALIZED;
1057 // In split system user mode, the admin and primary flags are assigned to the first human
1058 // user.
1059 if (!UserManager.isSplitSystemUser()) {
1060 flags |= UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY;
1061 }
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001062 // Create the system user
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001063 UserInfo system = new UserInfo(UserHandle.USER_SYSTEM,
Amith Yamasani6f34b412012-10-22 18:19:27 -07001064 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001065 flags);
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001066 mUsers.put(system.id, system);
Amith Yamasani634cf312012-10-04 17:34:21 -07001067 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -04001068 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001069
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001070 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001071 synchronized (mRestrictionsLock) {
1072 mBaseUserRestrictions.append(UserHandle.USER_SYSTEM, restrictions);
1073 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001074
Amith Yamasani13593602012-03-22 16:16:17 -07001075 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -07001076 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001077
Amith Yamasani13593602012-03-22 16:16:17 -07001078 writeUserListLocked();
Xiaohui Chen70f6c382015-04-28 14:21:43 -07001079 writeUserLocked(system);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001080 }
1081
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001082 private void scheduleWriteUserLocked(UserInfo userInfo) {
1083 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
1084 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
1085 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
1086 }
1087 }
1088
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001089 /*
1090 * Writes the user file in this format:
1091 *
1092 * <user flags="20039023" id="0">
1093 * <name>Primary</name>
1094 * </user>
1095 */
Amith Yamasani13593602012-03-22 16:16:17 -07001096 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001097 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -07001098 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001099 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001100 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001101 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1102
1103 // XmlSerializer serializer = XmlUtils.serializerInstance();
1104 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001105 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001106 serializer.startDocument(null, true);
1107 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1108
1109 serializer.startTag(null, TAG_USER);
1110 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -07001111 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001112 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -07001113 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
1114 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
1115 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001116 if (userInfo.iconPath != null) {
1117 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
1118 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001119 if (userInfo.partial) {
1120 serializer.attribute(null, ATTR_PARTIAL, "true");
1121 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001122 if (userInfo.guestToRemove) {
1123 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
1124 }
Kenny Guy2a764942014-04-02 13:29:20 +01001125 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1126 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
1127 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +00001128 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001129 if (userInfo.restrictedProfileParentId != UserInfo.NO_PROFILE_GROUP_ID) {
1130 serializer.attribute(null, ATTR_RESTRICTED_PROFILE_PARENT_ID,
1131 Integer.toString(userInfo.restrictedProfileParentId));
1132 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001133 serializer.startTag(null, TAG_NAME);
1134 serializer.text(userInfo.name);
1135 serializer.endTag(null, TAG_NAME);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001136 Bundle restrictions;
1137 synchronized (mRestrictionsLock) {
1138 restrictions = mBaseUserRestrictions.get(userInfo.id);
1139 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001140 if (restrictions != null) {
Makoto Onuki068c54a2015-10-13 14:34:03 -07001141 UserRestrictionsUtils
1142 .writeRestrictions(serializer, restrictions, TAG_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001143 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001144 serializer.endTag(null, TAG_USER);
1145
1146 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001147 userFile.finishWrite(fos);
1148 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001149 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -07001150 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001151 }
1152 }
1153
1154 /*
1155 * Writes the user list file in this format:
1156 *
Amith Yamasani2a003292012-08-14 18:25:45 -07001157 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001158 * <user id="0"></user>
1159 * <user id="2"></user>
1160 * </users>
1161 */
Amith Yamasani13593602012-03-22 16:16:17 -07001162 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -07001163 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -07001164 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001165 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001166 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001167 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1168
1169 // XmlSerializer serializer = XmlUtils.serializerInstance();
1170 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001171 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001172 serializer.startDocument(null, true);
1173 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1174
1175 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -07001176 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -07001177 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001178
Adam Lesinskieddeb492014-09-08 17:50:03 -07001179 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001180 UserRestrictionsUtils
1181 .writeRestrictions(serializer, mGuestRestrictions, TAG_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301182 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani515d4062015-09-28 11:30:06 -07001183 final int userSize = mUsers.size();
1184 for (int i = 0; i < userSize; i++) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001185 UserInfo user = mUsers.valueAt(i);
1186 serializer.startTag(null, TAG_USER);
1187 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
1188 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001189 }
1190
1191 serializer.endTag(null, TAG_USERS);
1192
1193 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -07001194 userListFile.finishWrite(fos);
1195 } catch (Exception e) {
1196 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -07001197 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001198 }
1199 }
1200
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001201 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001202 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -07001203 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001204 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001205 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -07001206 long creationTime = 0L;
1207 long lastLoggedInTime = 0L;
Kenny Guy2a764942014-04-02 13:29:20 +01001208 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001209 int restrictedProfileParentId = UserInfo.NO_PROFILE_GROUP_ID;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001210 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001211 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001212 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001213
1214 FileInputStream fis = null;
1215 try {
Amith Yamasani2a003292012-08-14 18:25:45 -07001216 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -07001217 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -07001218 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001219 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001220 parser.setInput(fis, StandardCharsets.UTF_8.name());
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001221 int type;
1222 while ((type = parser.next()) != XmlPullParser.START_TAG
1223 && type != XmlPullParser.END_DOCUMENT) {
1224 ;
1225 }
1226
1227 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001228 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001229 return null;
1230 }
1231
1232 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001233 int storedId = readIntAttribute(parser, ATTR_ID, -1);
1234 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -07001235 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001236 return null;
1237 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001238 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
1239 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001240 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -07001241 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
1242 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Kenny Guy2a764942014-04-02 13:29:20 +01001243 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
1244 UserInfo.NO_PROFILE_GROUP_ID);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001245 restrictedProfileParentId = readIntAttribute(parser,
1246 ATTR_RESTRICTED_PROFILE_PARENT_ID, UserInfo.NO_PROFILE_GROUP_ID);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001247 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
1248 if ("true".equals(valueString)) {
1249 partial = true;
1250 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001251 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
1252 if ("true".equals(valueString)) {
1253 guestToRemove = true;
1254 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001255
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001256 int outerDepth = parser.getDepth();
1257 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1258 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1259 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1260 continue;
1261 }
1262 String tag = parser.getName();
1263 if (TAG_NAME.equals(tag)) {
1264 type = parser.next();
1265 if (type == XmlPullParser.TEXT) {
1266 name = parser.getText();
1267 }
1268 } else if (TAG_RESTRICTIONS.equals(tag)) {
Makoto Onukia4f11972015-10-01 13:19:58 -07001269 UserRestrictionsUtils.readRestrictions(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001270 }
1271 }
1272 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001273
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001274 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001275 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001276 userInfo.creationTime = creationTime;
1277 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001278 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001279 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001280 userInfo.profileGroupId = profileGroupId;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001281 userInfo.restrictedProfileParentId = restrictedProfileParentId;
Makoto Onuki068c54a2015-10-13 14:34:03 -07001282 synchronized (mRestrictionsLock) {
1283 mBaseUserRestrictions.append(id, restrictions);
1284 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001285 return userInfo;
1286
1287 } catch (IOException ioe) {
1288 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001289 } finally {
1290 if (fis != null) {
1291 try {
1292 fis.close();
1293 } catch (IOException e) {
1294 }
1295 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001296 }
1297 return null;
1298 }
1299
Amith Yamasani920ace02012-09-20 22:15:37 -07001300 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1301 String valueString = parser.getAttributeValue(null, attr);
1302 if (valueString == null) return defaultValue;
1303 try {
1304 return Integer.parseInt(valueString);
1305 } catch (NumberFormatException nfe) {
1306 return defaultValue;
1307 }
1308 }
1309
1310 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1311 String valueString = parser.getAttributeValue(null, attr);
1312 if (valueString == null) return defaultValue;
1313 try {
1314 return Long.parseLong(valueString);
1315 } catch (NumberFormatException nfe) {
1316 return defaultValue;
1317 }
1318 }
1319
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001320 private boolean isPackageInstalled(String pkg, int userId) {
1321 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1322 PackageManager.GET_UNINSTALLED_PACKAGES,
1323 userId);
1324 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1325 return false;
1326 }
1327 return true;
1328 }
1329
Amith Yamasanib82add22013-07-09 11:24:44 -07001330 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001331 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001332 * Does not do any permissions checking.
1333 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001334 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001335 synchronized (mPackagesLock) {
1336 File dir = Environment.getUserSystemDirectory(userId);
1337 String[] files = dir.list();
1338 if (files == null) return;
1339 for (String fileName : files) {
1340 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1341 File resFile = new File(dir, fileName);
1342 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001343 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001344 }
1345 }
1346 }
1347 }
1348 }
1349
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001350 /**
1351 * Removes the app restrictions file for a specific package and user id, if it exists.
1352 */
1353 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1354 synchronized (mPackagesLock) {
1355 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001356 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001357 if (resFile.exists()) {
1358 resFile.delete();
1359 }
1360 }
1361 }
1362
Kenny Guya52dc3e2014-02-11 15:33:14 +00001363 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001364 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001365 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001366 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001367 }
1368
Amith Yamasani258848d2012-08-10 17:06:33 -07001369 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001370 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001371 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001372 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001373 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001374
Jessica Hummelbe81c802014-04-22 15:49:22 +01001375 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001376 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1377 UserManager.DISALLOW_ADD_USER, false)) {
1378 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1379 return null;
1380 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001381 if (ActivityManager.isLowRamDeviceStatic()) {
1382 return null;
1383 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001384 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001385 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001386 final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001387 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001388 UserInfo userInfo = null;
Amith Yamasanibb054c92015-07-09 14:16:27 -07001389 final int userId;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001390 try {
1391 synchronized (mInstallLock) {
1392 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001393 UserInfo parent = null;
1394 if (parentId != UserHandle.USER_NULL) {
1395 parent = getUserInfoLocked(parentId);
1396 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001397 }
Nicolas Prevotb8186812015-08-06 15:00:03 +01001398 if (isManagedProfile && !canAddMoreManagedProfiles(parentId)) {
1399 Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
Nicolas Prevot12678a92015-05-13 12:15:03 -07001400 return null;
1401 }
1402 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1403 // If we're not adding a guest user or a managed profile and the limit has
1404 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001405 return null;
1406 }
1407 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001408 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001409 return null;
1410 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001411 // In legacy mode, restricted profile's parent can only be the owner user
1412 if (isRestricted && !UserManager.isSplitSystemUser()
1413 && (parentId != UserHandle.USER_SYSTEM)) {
1414 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1415 return null;
1416 }
1417 if (isRestricted && UserManager.isSplitSystemUser()) {
1418 if (parent == null) {
1419 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be "
1420 + "specified");
1421 return null;
1422 }
1423 if (!parent.canHaveProfile()) {
1424 Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be "
1425 + "created for the specified parent user id " + parentId);
1426 return null;
1427 }
1428 }
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001429 // In split system user mode, we assign the first human user the primary flag.
Xiaohui Chen203243a2015-07-16 11:55:47 -07001430 // And if there is no device owner, we also assign the admin flag to primary
1431 // user.
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001432 if (UserManager.isSplitSystemUser()
Xiaohui Chen203243a2015-07-16 11:55:47 -07001433 && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001434 flags |= UserInfo.FLAG_PRIMARY;
Xiaohui Chen203243a2015-07-16 11:55:47 -07001435 DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
1436 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
1437 if (devicePolicyManager == null
1438 || devicePolicyManager.getDeviceOwner() == null) {
Xiaohui Chenb31e14a2015-07-13 16:04:55 -07001439 flags |= UserInfo.FLAG_ADMIN;
1440 }
1441 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001442 userId = getNextAvailableIdLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001443 userInfo = new UserInfo(userId, name, null, flags);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001444 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001445 long now = System.currentTimeMillis();
1446 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001447 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001448 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001449 mUsers.put(userId, userInfo);
1450 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001451 if (parent != null) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001452 if (isManagedProfile) {
1453 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1454 parent.profileGroupId = parent.id;
1455 scheduleWriteUserLocked(parent);
1456 }
1457 userInfo.profileGroupId = parent.profileGroupId;
1458 } else if (isRestricted) {
1459 if (!parent.canHaveProfile()) {
1460 Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
1461 }
1462 if (parent.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
1463 parent.restrictedProfileParentId = parent.id;
1464 scheduleWriteUserLocked(parent);
1465 }
1466 userInfo.restrictedProfileParentId = parent.restrictedProfileParentId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001467 }
Kenny Guya52dc3e2014-02-11 15:33:14 +00001468 }
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001469 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1470 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
1471 final String volumeUuid = vol.getFsUuid();
1472 try {
1473 final File userDir = Environment.getDataUserDirectory(volumeUuid,
1474 userId);
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07001475 prepareUserDirectory(mContext, volumeUuid, userId);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07001476 enforceSerialNumber(userDir, userInfo.serialNumber);
1477 } catch (IOException e) {
1478 Log.wtf(LOG_TAG, "Failed to create user directory on " + volumeUuid, e);
1479 }
1480 }
1481 mPm.createNewUserLILPw(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001482 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001483 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001484 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001485 Bundle restrictions = new Bundle();
Makoto Onuki068c54a2015-10-13 14:34:03 -07001486 synchronized (mRestrictionsLock) {
1487 mBaseUserRestrictions.append(userId, restrictions);
1488 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001489 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001490 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07001491 mPm.newUserCreated(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001492 if (userInfo != null) {
1493 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1494 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1495 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1496 android.Manifest.permission.MANAGE_USERS);
1497 }
1498 } finally {
1499 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001500 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001501 return userInfo;
1502 }
1503
Amith Yamasani0b285492011-04-14 17:35:23 -07001504 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001505 * @hide
1506 */
1507 public UserInfo createRestrictedProfile(String name, int parentUserId) {
1508 checkManageUsersPermission("setupRestrictedProfile");
1509 final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
1510 if (user == null) {
1511 return null;
1512 }
1513 setUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, true, user.id);
1514 // Change the setting before applying the DISALLOW_SHARE_LOCATION restriction, otherwise
1515 // the putIntForUser() will fail.
1516 android.provider.Settings.Secure.putIntForUser(mContext.getContentResolver(),
1517 android.provider.Settings.Secure.LOCATION_MODE,
1518 android.provider.Settings.Secure.LOCATION_MODE_OFF, user.id);
1519 setUserRestriction(UserManager.DISALLOW_SHARE_LOCATION, true, user.id);
1520 return user;
1521 }
1522
1523 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001524 * Find the current guest user. If the Guest user is partial,
1525 * then do not include it in the results as it is about to die.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001526 */
1527 private UserInfo findCurrentGuestUserLocked() {
1528 final int size = mUsers.size();
1529 for (int i = 0; i < size; i++) {
1530 final UserInfo user = mUsers.valueAt(i);
1531 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1532 return user;
1533 }
1534 }
1535 return null;
1536 }
1537
1538 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001539 * Mark this guest user for deletion to allow us to create another guest
1540 * and switch to that user before actually removing this guest.
1541 * @param userHandle the userid of the current guest
1542 * @return whether the user could be marked for deletion
1543 */
1544 public boolean markGuestForDeletion(int userHandle) {
1545 checkManageUsersPermission("Only the system can remove users");
1546 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1547 UserManager.DISALLOW_REMOVE_USER, false)) {
1548 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1549 return false;
1550 }
1551
1552 long ident = Binder.clearCallingIdentity();
1553 try {
1554 final UserInfo user;
1555 synchronized (mPackagesLock) {
1556 user = mUsers.get(userHandle);
1557 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1558 return false;
1559 }
1560 if (!user.isGuest()) {
1561 return false;
1562 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001563 // We set this to a guest user that is to be removed. This is a temporary state
1564 // where we are allowed to add new Guest users, even if this one is still not
1565 // removed. This user will still show up in getUserInfo() calls.
1566 // If we don't get around to removing this Guest user, it will be purged on next
1567 // startup.
1568 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001569 // Mark it as disabled, so that it isn't returned any more when
1570 // profiles are queried.
1571 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001572 writeUserLocked(user);
1573 }
1574 } finally {
1575 Binder.restoreCallingIdentity(ident);
1576 }
1577 return true;
1578 }
1579
1580 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001581 * Removes a user and all data directories created for that user. This method should be called
1582 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001583 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001584 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001585 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001586 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001587 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1588 UserManager.DISALLOW_REMOVE_USER, false)) {
1589 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1590 return false;
1591 }
1592
Kenny Guyee58b4f2014-05-23 15:19:53 +01001593 long ident = Binder.clearCallingIdentity();
1594 try {
1595 final UserInfo user;
Fyodor Kupolov0df68cd2015-10-01 13:54:22 -07001596 int currentUser = ActivityManager.getCurrentUser();
1597 if (currentUser == userHandle) {
1598 Log.w(LOG_TAG, "Current user cannot be removed");
1599 return false;
1600 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001601 synchronized (mPackagesLock) {
1602 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001603 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001604 return false;
1605 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001606
1607 // We remember deleted user IDs to prevent them from being
1608 // reused during the current boot; they can still be reused
1609 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001610 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001611
Kenny Guyee58b4f2014-05-23 15:19:53 +01001612 try {
1613 mAppOpsService.removeUser(userHandle);
1614 } catch (RemoteException e) {
1615 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1616 }
1617 // Set this to a partially created user, so that the user will be purged
1618 // on next startup, in case the runtime stops now before stopping and
1619 // removing the user completely.
1620 user.partial = true;
1621 // Mark it as disabled, so that it isn't returned any more when
1622 // profiles are queried.
1623 user.flags |= UserInfo.FLAG_DISABLED;
1624 writeUserLocked(user);
1625 }
1626
1627 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1628 && user.isManagedProfile()) {
1629 // Send broadcast to notify system that the user removed was a
1630 // managed user.
1631 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1632 }
1633
1634 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1635 int res;
1636 try {
1637 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1638 new IStopUserCallback.Stub() {
1639 @Override
1640 public void userStopped(int userId) {
1641 finishRemoveUser(userId);
1642 }
1643 @Override
1644 public void userStopAborted(int userId) {
1645 }
1646 });
1647 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001648 return false;
1649 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001650 return res == ActivityManager.USER_OP_SUCCESS;
1651 } finally {
1652 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001653 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001654 }
1655
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001656 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001657 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001658 // Let other services shutdown any activity and clean up their state before completely
1659 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001660 long ident = Binder.clearCallingIdentity();
1661 try {
1662 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1663 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001664 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1665 android.Manifest.permission.MANAGE_USERS,
1666
1667 new BroadcastReceiver() {
1668 @Override
1669 public void onReceive(Context context, Intent intent) {
1670 if (DBG) {
1671 Slog.i(LOG_TAG,
1672 "USER_REMOVED broadcast sent, cleaning up user data "
1673 + userHandle);
1674 }
1675 new Thread() {
1676 public void run() {
Amith Yamasani515d4062015-09-28 11:30:06 -07001677 // Clean up any ActivityManager state
1678 LocalServices.getService(ActivityManagerInternal.class)
1679 .onUserRemoved(userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001680 synchronized (mInstallLock) {
1681 synchronized (mPackagesLock) {
1682 removeUserStateLocked(userHandle);
1683 }
1684 }
1685 }
1686 }.start();
1687 }
1688 },
1689
1690 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001691 } finally {
1692 Binder.restoreCallingIdentity(ident);
1693 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001694 }
1695
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001696 private void removeUserStateLocked(final int userHandle) {
Paul Crowley85e4e812015-05-19 12:42:00 +01001697 mContext.getSystemService(StorageManager.class)
1698 .deleteUserKey(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001699 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001700 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001701
1702 // Remove this user from the list
1703 mUsers.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001704 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001705 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001706 userFile.delete();
1707 // Update the user list
1708 writeUserListLocked();
1709 updateUserIdsLocked();
1710 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1711 }
1712
Amith Yamasani61f57372012-08-31 12:12:28 -07001713 private void removeDirectoryRecursive(File parent) {
1714 if (parent.isDirectory()) {
1715 String[] files = parent.list();
1716 for (String filename : files) {
1717 File child = new File(parent, filename);
1718 removeDirectoryRecursive(child);
1719 }
1720 }
1721 parent.delete();
1722 }
1723
Kenny Guyf8d3a232014-05-15 16:09:52 +01001724 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001725 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001726 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1727 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001728 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1729 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001730 }
1731
Amith Yamasani2a003292012-08-14 18:25:45 -07001732 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001733 public Bundle getApplicationRestrictions(String packageName) {
1734 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1735 }
1736
1737 @Override
1738 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001739 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001740 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001741 checkManageUsersPermission("get application restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001742 }
1743 synchronized (mPackagesLock) {
1744 // Read the restrictions from XML
1745 return readApplicationRestrictionsLocked(packageName, userId);
1746 }
1747 }
1748
1749 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001750 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001751 int userId) {
Esteban Talavera2a5d6c62015-10-21 10:55:56 +01001752 checkManageUsersPermission("set application restrictions");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001753 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001754 if (restrictions == null || restrictions.isEmpty()) {
1755 cleanAppRestrictionsForPackage(packageName, userId);
1756 } else {
1757 // Write the restrictions to XML
1758 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1759 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001760 }
Robin Lee66e5d962014-04-09 16:44:21 +01001761
Kenny Guyd21b2182014-07-17 16:38:55 +01001762 if (isPackageInstalled(packageName, userId)) {
1763 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1764 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1765 changeIntent.setPackage(packageName);
1766 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1767 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1768 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001769 }
1770
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001771 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001772 mHandler.post(new Runnable() {
1773 @Override
1774 public void run() {
1775 List<ApplicationInfo> apps =
1776 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1777 userHandle).getList();
1778 final long ident = Binder.clearCallingIdentity();
1779 try {
1780 for (ApplicationInfo appInfo : apps) {
1781 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001782 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1783 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001784 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001785 userHandle);
1786 }
1787 }
1788 } finally {
1789 Binder.restoreCallingIdentity(ident);
1790 }
1791 }
1792 });
1793 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001794 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001795 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001796 try {
1797 return mContext.getPackageManager().getApplicationInfo(packageName,
1798 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1799 } catch (NameNotFoundException nnfe) {
1800 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001801 } finally {
1802 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001803 }
1804 }
1805
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001806 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001807 int userId) {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001808 AtomicFile restrictionsFile =
1809 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1810 packageToRestrictionsFileName(packageName)));
1811 return readApplicationRestrictionsLocked(restrictionsFile);
1812 }
1813
1814 @VisibleForTesting
1815 static Bundle readApplicationRestrictionsLocked(AtomicFile restrictionsFile) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001816 final Bundle restrictions = new Bundle();
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001817 final ArrayList<String> values = new ArrayList<>();
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001818 if (!restrictionsFile.getBaseFile().exists()) {
Fyodor Kupolovf6ee2242015-04-06 10:15:07 -07001819 return restrictions;
Fyodor Kupolov6f34d362015-04-02 12:42:13 -07001820 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001821
1822 FileInputStream fis = null;
1823 try {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001824 fis = restrictionsFile.openRead();
1825 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001826 parser.setInput(fis, StandardCharsets.UTF_8.name());
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001827 XmlUtils.nextElement(parser);
1828 if (parser.getEventType() != XmlPullParser.START_TAG) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001829 Slog.e(LOG_TAG, "Unable to read restrictions file "
1830 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001831 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001832 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001833 while (parser.next() != XmlPullParser.END_DOCUMENT) {
1834 readEntry(restrictions, values, parser);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001835 }
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001836 } catch (IOException|XmlPullParserException e) {
1837 Log.w(LOG_TAG, "Error parsing " + restrictionsFile.getBaseFile(), e);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001838 } finally {
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001839 IoUtils.closeQuietly(fis);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001840 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001841 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001842 }
1843
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001844 private static void readEntry(Bundle restrictions, ArrayList<String> values,
1845 XmlPullParser parser) throws XmlPullParserException, IOException {
1846 int type = parser.getEventType();
1847 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1848 String key = parser.getAttributeValue(null, ATTR_KEY);
1849 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1850 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1851 if (multiple != null) {
1852 values.clear();
1853 int count = Integer.parseInt(multiple);
1854 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1855 if (type == XmlPullParser.START_TAG
1856 && parser.getName().equals(TAG_VALUE)) {
1857 values.add(parser.nextText().trim());
1858 count--;
1859 }
1860 }
1861 String [] valueStrings = new String[values.size()];
1862 values.toArray(valueStrings);
1863 restrictions.putStringArray(key, valueStrings);
1864 } else if (ATTR_TYPE_BUNDLE.equals(valType)) {
1865 restrictions.putBundle(key, readBundleEntry(parser, values));
1866 } else if (ATTR_TYPE_BUNDLE_ARRAY.equals(valType)) {
1867 final int outerDepth = parser.getDepth();
1868 ArrayList<Bundle> bundleList = new ArrayList<>();
1869 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1870 Bundle childBundle = readBundleEntry(parser, values);
1871 bundleList.add(childBundle);
1872 }
1873 restrictions.putParcelableArray(key,
1874 bundleList.toArray(new Bundle[bundleList.size()]));
1875 } else {
1876 String value = parser.nextText().trim();
1877 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1878 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1879 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1880 restrictions.putInt(key, Integer.parseInt(value));
1881 } else {
1882 restrictions.putString(key, value);
1883 }
1884 }
1885 }
1886 }
1887
1888 private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
1889 throws IOException, XmlPullParserException {
1890 Bundle childBundle = new Bundle();
1891 final int outerDepth = parser.getDepth();
1892 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1893 readEntry(childBundle, values, parser);
1894 }
1895 return childBundle;
1896 }
1897
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001898 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001899 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001900 AtomicFile restrictionsFile = new AtomicFile(
1901 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001902 packageToRestrictionsFileName(packageName)));
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001903 writeApplicationRestrictionsLocked(restrictions, restrictionsFile);
1904 }
1905
1906 @VisibleForTesting
1907 static void writeApplicationRestrictionsLocked(Bundle restrictions,
1908 AtomicFile restrictionsFile) {
1909 FileOutputStream fos = null;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001910 try {
1911 fos = restrictionsFile.startWrite();
1912 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1913
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001914 final XmlSerializer serializer = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001915 serializer.setOutput(bos, StandardCharsets.UTF_8.name());
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001916 serializer.startDocument(null, true);
1917 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1918
1919 serializer.startTag(null, TAG_RESTRICTIONS);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001920 writeBundle(restrictions, serializer);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001921 serializer.endTag(null, TAG_RESTRICTIONS);
1922
1923 serializer.endDocument();
1924 restrictionsFile.finishWrite(fos);
1925 } catch (Exception e) {
1926 restrictionsFile.failWrite(fos);
Fyodor Kupolov262f9952015-03-23 18:55:11 -07001927 Slog.e(LOG_TAG, "Error writing application restrictions list", e);
1928 }
1929 }
1930
1931 private static void writeBundle(Bundle restrictions, XmlSerializer serializer)
1932 throws IOException {
1933 for (String key : restrictions.keySet()) {
1934 Object value = restrictions.get(key);
1935 serializer.startTag(null, TAG_ENTRY);
1936 serializer.attribute(null, ATTR_KEY, key);
1937
1938 if (value instanceof Boolean) {
1939 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1940 serializer.text(value.toString());
1941 } else if (value instanceof Integer) {
1942 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1943 serializer.text(value.toString());
1944 } else if (value == null || value instanceof String) {
1945 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1946 serializer.text(value != null ? (String) value : "");
1947 } else if (value instanceof Bundle) {
1948 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1949 writeBundle((Bundle) value, serializer);
1950 } else if (value instanceof Parcelable[]) {
1951 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE_ARRAY);
1952 Parcelable[] array = (Parcelable[]) value;
1953 for (Parcelable parcelable : array) {
1954 if (!(parcelable instanceof Bundle)) {
1955 throw new IllegalArgumentException("bundle-array can only hold Bundles");
1956 }
1957 serializer.startTag(null, TAG_ENTRY);
1958 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BUNDLE);
1959 writeBundle((Bundle) parcelable, serializer);
1960 serializer.endTag(null, TAG_ENTRY);
1961 }
1962 } else {
1963 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1964 String[] values = (String[]) value;
1965 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1966 for (String choice : values) {
1967 serializer.startTag(null, TAG_VALUE);
1968 serializer.text(choice != null ? choice : "");
1969 serializer.endTag(null, TAG_VALUE);
1970 }
1971 }
1972 serializer.endTag(null, TAG_ENTRY);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001973 }
1974 }
1975
1976 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001977 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001978 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001979 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001980 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001981 }
1982 }
1983
1984 @Override
1985 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001986 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001987 for (int userId : mUserIds) {
Kenny Guy945f8832015-02-10 15:17:26 +00001988 UserInfo info = getUserInfoLocked(userId);
1989 if (info != null && info.serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001990 }
1991 // Not found
1992 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001993 }
1994 }
1995
Fyodor Kupolovff7233e2015-04-08 11:28:52 -07001996 @Override
1997 public long getUserCreationTime(int userHandle) {
1998 int callingUserId = UserHandle.getCallingUserId();
1999 UserInfo userInfo = null;
2000 synchronized (mPackagesLock) {
2001 if (callingUserId == userHandle) {
2002 userInfo = getUserInfoLocked(userHandle);
2003 } else {
2004 UserInfo parent = getProfileParentLocked(userHandle);
2005 if (parent != null && parent.id == callingUserId) {
2006 userInfo = getUserInfoLocked(userHandle);
2007 }
2008 }
2009 }
2010 if (userInfo == null) {
2011 throw new SecurityException("userHandle can only be the calling user or a managed "
2012 + "profile associated with this user");
2013 }
2014 return userInfo.creationTime;
2015 }
2016
Amith Yamasani0b285492011-04-14 17:35:23 -07002017 /**
2018 * Caches the list of user ids in an array, adjusting the array size when necessary.
2019 */
Amith Yamasani13593602012-03-22 16:16:17 -07002020 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002021 int num = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07002022 final int userSize = mUsers.size();
2023 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002024 if (!mUsers.valueAt(i).partial) {
2025 num++;
2026 }
2027 }
Amith Yamasani16389312012-10-17 21:20:14 -07002028 final int[] newUsers = new int[num];
2029 int n = 0;
Amith Yamasani515d4062015-09-28 11:30:06 -07002030 for (int i = 0; i < userSize; i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002031 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07002032 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002033 }
Amith Yamasani0b285492011-04-14 17:35:23 -07002034 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07002035 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07002036 }
2037
2038 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07002039 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07002040 * @param userId the user that was just foregrounded
2041 */
Amith Yamasani06bf8242015-05-08 16:36:21 -07002042 public void onUserForeground(int userId) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002043 synchronized (mPackagesLock) {
2044 UserInfo user = mUsers.get(userId);
2045 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002046 if (user == null || user.partial) {
2047 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
2048 return;
2049 }
2050 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07002051 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002052 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07002053 }
2054 }
2055 }
2056
2057 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07002058 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07002059 * TODO: May not be a good idea to recycle ids, in case it results in confusion
2060 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07002061 * @return
2062 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002063 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07002064 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002065 int i = MIN_USER_ID;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002066 while (i < MAX_USER_ID) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002067 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002068 return i;
Amith Yamasani195263742012-08-21 15:40:12 -07002069 }
2070 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002071 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002072 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002073 throw new IllegalStateException("No user id available!");
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002074 }
Amith Yamasani920ace02012-09-20 22:15:37 -07002075
Amith Yamasanifc95e702013-09-26 13:20:17 -07002076 private String packageToRestrictionsFileName(String packageName) {
2077 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
2078 }
2079
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002080 /**
2081 * Create new {@code /data/user/[id]} directory and sets default
2082 * permissions.
2083 */
Jeff Sharkey3bb8c852015-07-06 16:44:23 -07002084 public static void prepareUserDirectory(Context context, String volumeUuid, int userId) {
2085 final StorageManager storage = context.getSystemService(StorageManager.class);
2086 final File userDir = Environment.getDataUserDirectory(volumeUuid, userId);
2087 storage.createNewUserDir(userId, userDir);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07002088 }
2089
2090 /**
2091 * Enforce that serial number stored in user directory inode matches the
2092 * given expected value. Gracefully sets the serial number if currently
2093 * undefined.
2094 *
2095 * @throws IOException when problem extracting serial number, or serial
2096 * number is mismatched.
2097 */
2098 public static void enforceSerialNumber(File file, int serialNumber) throws IOException {
2099 final int foundSerial = getSerialNumber(file);
2100 Slog.v(LOG_TAG, "Found " + file + " with serial number " + foundSerial);
2101
2102 if (foundSerial == -1) {
2103 Slog.d(LOG_TAG, "Serial number missing on " + file + "; assuming current is valid");
2104 try {
2105 setSerialNumber(file, serialNumber);
2106 } catch (IOException e) {
2107 Slog.w(LOG_TAG, "Failed to set serial number on " + file, e);
2108 }
2109
2110 } else if (foundSerial != serialNumber) {
2111 throw new IOException("Found serial number " + foundSerial
2112 + " doesn't match expected " + serialNumber);
2113 }
2114 }
2115
2116 /**
2117 * Set serial number stored in user directory inode.
2118 *
2119 * @throws IOException if serial number was already set
2120 */
2121 private static void setSerialNumber(File file, int serialNumber)
2122 throws IOException {
2123 try {
2124 final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8);
2125 Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE);
2126 } catch (ErrnoException e) {
2127 throw e.rethrowAsIOException();
2128 }
2129 }
2130
2131 /**
2132 * Return serial number stored in user directory inode.
2133 *
2134 * @return parsed serial number, or -1 if not set
2135 */
2136 private static int getSerialNumber(File file) throws IOException {
2137 try {
2138 final byte[] buf = new byte[256];
2139 final int len = Os.getxattr(file.getAbsolutePath(), XATTR_SERIAL, buf);
2140 final String serial = new String(buf, 0, len);
2141 try {
2142 return Integer.parseInt(serial);
2143 } catch (NumberFormatException e) {
2144 throw new IOException("Bad serial number: " + serial);
2145 }
2146 } catch (ErrnoException e) {
2147 if (e.errno == OsConstants.ENODATA) {
2148 return -1;
2149 } else {
2150 throw e.rethrowAsIOException();
2151 }
2152 }
2153 }
2154
Amith Yamasani920ace02012-09-20 22:15:37 -07002155 @Override
Todd Kennedy60459ab2015-10-30 11:32:16 -07002156 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2157 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
2158 (new Shell()).exec(this, in, out, err, args, resultReceiver);
2159 }
2160
2161 int onShellCommand(Shell shell, String cmd) {
2162 if (cmd == null) {
2163 return shell.handleDefaultCommands(cmd);
2164 }
2165
2166 final PrintWriter pw = shell.getOutPrintWriter();
2167 try {
2168 switch(cmd) {
2169 case "list":
2170 return runList(pw);
2171 }
2172 } catch (RemoteException e) {
2173 pw.println("Remote exception: " + e);
2174 }
2175 return -1;
2176 }
2177
2178 private int runList(PrintWriter pw) throws RemoteException {
2179 final IActivityManager am = ActivityManagerNative.getDefault();
2180 final List<UserInfo> users = getUsers(false);
2181 if (users == null) {
2182 pw.println("Error: couldn't get users");
2183 return 1;
2184 } else {
2185 pw.println("Users:");
2186 for (int i = 0; i < users.size(); i++) {
2187 String running = am.isUserRunning(users.get(i).id, false) ? " running" : "";
2188 pw.println("\t" + users.get(i).toString() + running);
2189 }
2190 return 0;
2191 }
2192 }
2193
2194 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -07002195 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2196 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2197 != PackageManager.PERMISSION_GRANTED) {
2198 pw.println("Permission Denial: can't dump UserManager from from pid="
2199 + Binder.getCallingPid()
2200 + ", uid=" + Binder.getCallingUid()
2201 + " without permission "
2202 + android.Manifest.permission.DUMP);
2203 return;
2204 }
2205
2206 long now = System.currentTimeMillis();
2207 StringBuilder sb = new StringBuilder();
2208 synchronized (mPackagesLock) {
2209 pw.println("Users:");
2210 for (int i = 0; i < mUsers.size(); i++) {
2211 UserInfo user = mUsers.valueAt(i);
2212 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07002213 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08002214 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07002215 if (user.partial) pw.print(" <partial>");
2216 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07002217 pw.print(" Created: ");
2218 if (user.creationTime == 0) {
2219 pw.println("<unknown>");
2220 } else {
2221 sb.setLength(0);
2222 TimeUtils.formatDuration(now - user.creationTime, sb);
2223 sb.append(" ago");
2224 pw.println(sb);
2225 }
2226 pw.print(" Last logged in: ");
2227 if (user.lastLoggedInTime == 0) {
2228 pw.println("<unknown>");
2229 } else {
2230 sb.setLength(0);
2231 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
2232 sb.append(" ago");
2233 pw.println(sb);
2234 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002235 pw.println(" Restrictions:");
2236 UserRestrictionsUtils.dumpRestrictions(
Makoto Onuki068c54a2015-10-13 14:34:03 -07002237 pw, " ", mBaseUserRestrictions.get(user.id));
2238 pw.println(" Effective restrictions:");
2239 UserRestrictionsUtils.dumpRestrictions(
2240 pw, " ", mCachedEffectiveUserRestrictions.get(user.id));
Amith Yamasani920ace02012-09-20 22:15:37 -07002241 }
Makoto Onukia4f11972015-10-01 13:19:58 -07002242 pw.println();
2243 pw.println("Guest restrictions:");
2244 UserRestrictionsUtils.dumpRestrictions(pw, " ", mGuestRestrictions);
Amith Yamasani920ace02012-09-20 22:15:37 -07002245 }
2246 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08002247
2248 final class MainHandler extends Handler {
2249
2250 @Override
2251 public void handleMessage(Message msg) {
2252 switch (msg.what) {
2253 case WRITE_USER_MSG:
2254 removeMessages(WRITE_USER_MSG, msg.obj);
2255 synchronized (mPackagesLock) {
2256 int userId = ((UserInfo) msg.obj).id;
2257 UserInfo userInfo = mUsers.get(userId);
2258 if (userInfo != null) {
2259 writeUserLocked(userInfo);
2260 }
2261 }
2262 }
2263 }
2264 }
Amith Yamasanibb054c92015-07-09 14:16:27 -07002265
2266 /**
2267 * @param userId
2268 * @return whether the user has been initialized yet
2269 */
2270 boolean isInitialized(int userId) {
2271 return (getUserInfo(userId).flags & UserInfo.FLAG_INITIALIZED) != 0;
2272 }
Makoto Onuki068c54a2015-10-13 14:34:03 -07002273
2274 private class LocalService extends UserManagerInternal {
2275
2276 @Override
2277 public Object getUserRestrictionsLock() {
2278 return mRestrictionsLock;
2279 }
2280
2281 @Override
2282 @GuardedBy("mRestrictionsLock")
2283 public void updateEffectiveUserRestrictionsRL(int userId) {
2284 UserManagerService.this.updateEffectiveUserRestrictionsRL(userId);
2285 }
2286
2287 @Override
2288 @GuardedBy("mRestrictionsLock")
2289 public void updateEffectiveUserRestrictionsForAllUsersRL() {
2290 UserManagerService.this.updateEffectiveUserRestrictionsForAllUsersRL();
2291 }
2292
2293 @Override
2294 public Bundle getBaseUserRestrictions(int userId) {
2295 synchronized (mRestrictionsLock) {
2296 return mBaseUserRestrictions.get(userId);
2297 }
2298 }
2299
2300 @Override
2301 public void setBaseUserRestrictionsByDpmsForMigration(
2302 int userId, Bundle baseRestrictions) {
2303 synchronized (mRestrictionsLock) {
2304 mBaseUserRestrictions.put(userId, new Bundle(baseRestrictions));
2305 invalidateEffectiveUserRestrictionsRL(userId);
2306 }
2307
2308 synchronized (mPackagesLock) {
2309 final UserInfo userInfo = mUsers.get(userId);
2310 if (userInfo != null) {
2311 writeUserLocked(userInfo);
2312 } else {
2313 Slog.w(LOG_TAG, "UserInfo not found for " + userId);
2314 }
2315 }
2316 }
2317 }
Todd Kennedy60459ab2015-10-30 11:32:16 -07002318
2319 private class Shell extends ShellCommand {
2320 @Override
2321 public int onCommand(String cmd) {
2322 return onShellCommand(this, cmd);
2323 }
2324
2325 @Override
2326 public void onHelp() {
2327 final PrintWriter pw = getOutPrintWriter();
2328 pw.println("User manager (user) commands:");
2329 pw.println(" help");
2330 pw.println(" Print this help text.");
2331 pw.println("");
2332 pw.println(" list");
2333 pw.println(" Prints all users on the system.");
2334 }
2335 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07002336}