blob: db0f53bf2f680e52eff0301f2d131d675431a438 [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
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080019import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070020
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
24import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070025import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070026import android.content.Context;
27import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070028import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070029import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080030import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070031import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070032import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070034import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080035import android.os.Bundle;
Amith Yamasani8cd28b52014-06-08 17:54:27 -070036import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040043import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070044import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070045import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070046import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070047import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.util.Slog;
49import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070051import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Xml;
53
Jason Monk62062992014-05-06 09:55:28 -040054import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import com.android.internal.util.ArrayUtils;
56import com.android.internal.util.FastXmlSerializer;
57
58import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60import org.xmlpull.v1.XmlSerializer;
61
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import java.io.BufferedOutputStream;
63import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070064import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070066import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import java.io.FileOutputStream;
68import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070069import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070070import java.security.MessageDigest;
71import java.security.NoSuchAlgorithmException;
72import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.util.ArrayList;
74import java.util.List;
75
Amith Yamasani258848d2012-08-10 17:06:33 -070076public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077
Amith Yamasani2a003292012-08-14 18:25:45 -070078 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070079
Amith Yamasani16389312012-10-17 21:20:14 -070080 private static final boolean DBG = false;
81
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070086 private static final String ATTR_CREATION_TIME = "created";
87 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070088 private static final String ATTR_SALT = "salt";
89 private static final String ATTR_PIN_HASH = "pinHash";
90 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
91 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070092 private static final String ATTR_SERIAL_NO = "serialNumber";
93 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070094 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070095 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070096 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010097 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053098 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700100 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800101 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800102 private static final String TAG_ENTRY = "entry";
103 private static final String TAG_VALUE = "value";
104 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700105 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800106 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700108 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
109 private static final String ATTR_TYPE_STRING = "s";
110 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700111 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700112
Amith Yamasani0b285492011-04-14 17:35:23 -0700113 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700115 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800117 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700118 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800119
Amith Yamasani634cf312012-10-04 17:34:21 -0700120 private static final int MIN_USER_ID = 10;
121
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700122 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700123
Amith Yamasani920ace02012-09-20 22:15:37 -0700124 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
125
Amith Yamasani655d0e22013-06-12 14:19:10 -0700126 // Number of attempts before jumping to the next BACKOFF_TIMES slot
127 private static final int BACKOFF_INC_INTERVAL = 5;
128
Amith Yamasani95ab7842014-08-11 17:09:26 -0700129 // Maximum number of managed profiles permitted is 1. This cannot be increased
130 // without first making sure that the rest of the framework is prepared for it.
131 private static final int MAX_MANAGED_PROFILES = 1;
132
Amith Yamasani655d0e22013-06-12 14:19:10 -0700133 // Amount of time to force the user to wait before entering the PIN again, after failing
134 // BACKOFF_INC_INTERVAL times.
135 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
136
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530137
Dianne Hackborn4428e172012-08-24 17:43:05 -0700138 private final Context mContext;
139 private final PackageManagerService mPm;
140 private final Object mInstallLock;
141 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143 private final Handler mHandler;
144
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private final File mUsersDir;
146 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700147 private final File mBaseUserPath;
148
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800149 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800150 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530151 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800152
Amith Yamasani655d0e22013-06-12 14:19:10 -0700153 class RestrictionsPinState {
154 long salt;
155 String pinHash;
156 int failedAttempts;
157 long lastAttemptTime;
158 }
159
160 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
161 new SparseArray<RestrictionsPinState>();
162
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800163 /**
164 * Set of user IDs being actively removed. Removed IDs linger in this set
165 * for several seconds to work around a VFS caching issue.
166 */
167 // @GuardedBy("mPackagesLock")
168 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700169
Amith Yamasani0b285492011-04-14 17:35:23 -0700170 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700171 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700172 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700173
Jason Monk62062992014-05-06 09:55:28 -0400174 private IAppOpsService mAppOpsService;
175
Amith Yamasani258848d2012-08-10 17:06:33 -0700176 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700177
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 public static UserManagerService getInstance() {
179 synchronized (UserManagerService.class) {
180 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700182 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183
184 /**
185 * Available for testing purposes.
186 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700187 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700188 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700189 }
190
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 /**
192 * Called by package manager to create the service. This is closely
193 * associated with the package manager, and the given lock is the
194 * package manager's own lock.
195 */
196 UserManagerService(Context context, PackageManagerService pm,
197 Object installLock, Object packagesLock) {
198 this(context, pm, installLock, packagesLock,
199 Environment.getDataDirectory(),
200 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700201 }
202
Dianne Hackborn4428e172012-08-24 17:43:05 -0700203 /**
204 * Available for testing purposes.
205 */
206 private UserManagerService(Context context, PackageManagerService pm,
207 Object installLock, Object packagesLock,
208 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700209 mContext = context;
210 mPm = pm;
211 mInstallLock = installLock;
212 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800213 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700214 synchronized (mInstallLock) {
215 synchronized (mPackagesLock) {
216 mUsersDir = new File(dataDir, USER_INFO_DIR);
217 mUsersDir.mkdirs();
218 // Make zeroth user directory, for services to migrate their files to that location
219 File userZeroDir = new File(mUsersDir, "0");
220 userZeroDir.mkdirs();
221 mBaseUserPath = baseUserPath;
222 FileUtils.setPermissions(mUsersDir.toString(),
223 FileUtils.S_IRWXU|FileUtils.S_IRWXG
224 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
225 -1, -1);
226 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
227 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700228 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700229 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
230 for (int i = 0; i < mUsers.size(); i++) {
231 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700232 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700233 partials.add(ui);
234 }
235 }
236 for (int i = 0; i < partials.size(); i++) {
237 UserInfo ui = partials.get(i);
238 Slog.w(LOG_TAG, "Removing partially created user #" + i
239 + " (name=" + ui.name + ")");
240 removeUserStateLocked(ui.id);
241 }
242 sInstance = this;
243 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700244 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700245 }
246
247 void systemReady() {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700248 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400249 mAppOpsService = IAppOpsService.Stub.asInterface(
250 ServiceManager.getService(Context.APP_OPS_SERVICE));
251 for (int i = 0; i < mUserIds.length; ++i) {
252 try {
253 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
254 } catch (RemoteException e) {
255 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
256 }
257 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700258 }
259
260 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700261 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700262 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700263 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700264 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
265 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700266 UserInfo ui = mUsers.valueAt(i);
267 if (ui.partial) {
268 continue;
269 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800270 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700271 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700272 }
Amith Yamasani13593602012-03-22 16:16:17 -0700273 }
274 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700275 }
Amith Yamasani13593602012-03-22 16:16:17 -0700276 }
277
Amith Yamasani258848d2012-08-10 17:06:33 -0700278 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100279 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800280 if (userId != UserHandle.getCallingUserId()) {
281 checkManageUsersPermission("getting profiles related to user " + userId);
282 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700283 final long ident = Binder.clearCallingIdentity();
284 try {
285 synchronized (mPackagesLock) {
286 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100287 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700288 } finally {
289 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000290 }
291 }
292
Amith Yamasanibe465322014-04-24 13:45:17 -0700293 /** Assume permissions already checked and caller's identity cleared */
294 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700295 UserInfo user = getUserInfoLocked(userId);
296 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700297 if (user == null) {
298 // Probably a dying user
299 return users;
300 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700301 for (int i = 0; i < mUsers.size(); i++) {
302 UserInfo profile = mUsers.valueAt(i);
303 if (!isProfileOf(user, profile)) {
304 continue;
305 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100306 if (enabledOnly && !profile.isEnabled()) {
307 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700308 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700309 if (mRemovingUserIds.get(profile.id)) {
310 continue;
311 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700312 users.add(profile);
313 }
314 return users;
315 }
316
Jessica Hummelbe81c802014-04-22 15:49:22 +0100317 @Override
318 public UserInfo getProfileParent(int userHandle) {
319 checkManageUsersPermission("get the profile parent");
320 synchronized (mPackagesLock) {
321 UserInfo profile = getUserInfoLocked(userHandle);
322 int parentUserId = profile.profileGroupId;
323 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
324 return null;
325 } else {
326 return getUserInfoLocked(parentUserId);
327 }
328 }
329 }
330
Kenny Guy2a764942014-04-02 13:29:20 +0100331 private boolean isProfileOf(UserInfo user, UserInfo profile) {
332 return user.id == profile.id ||
333 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
334 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000335 }
336
337 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100338 public void setUserEnabled(int userId) {
339 checkManageUsersPermission("enable user");
340 synchronized (mPackagesLock) {
341 UserInfo info = getUserInfoLocked(userId);
342 if (info != null && !info.isEnabled()) {
343 info.flags ^= UserInfo.FLAG_DISABLED;
344 writeUserLocked(info);
345 }
346 }
347 }
348
349 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700350 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700351 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700352 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700353 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700354 }
355 }
356
Amith Yamasani71e6c692013-03-24 17:39:28 -0700357 @Override
358 public boolean isRestricted() {
359 synchronized (mPackagesLock) {
360 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
361 }
362 }
363
Amith Yamasani195263742012-08-21 15:40:12 -0700364 /*
365 * Should be locked on mUsers before calling this.
366 */
367 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700368 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700369 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800370 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700371 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
372 return null;
373 }
374 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700375 }
376
Amith Yamasani13593602012-03-22 16:16:17 -0700377 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700378 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700379 return ArrayUtils.contains(mUserIds, userId);
380 }
381 }
382
Amith Yamasani258848d2012-08-10 17:06:33 -0700383 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700384 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700385 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700386 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700387 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700388 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700389 if (info == null || info.partial) {
390 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
391 return;
392 }
Amith Yamasani13593602012-03-22 16:16:17 -0700393 if (name != null && !name.equals(info.name)) {
394 info.name = name;
395 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700396 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700397 }
398 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700399 if (changed) {
400 sendUserInfoChangedBroadcast(userId);
401 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700402 }
403
Amith Yamasani258848d2012-08-10 17:06:33 -0700404 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700405 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700406 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400407 long ident = Binder.clearCallingIdentity();
408 try {
409 synchronized (mPackagesLock) {
410 UserInfo info = mUsers.get(userId);
411 if (info == null || info.partial) {
412 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
413 return;
414 }
415 writeBitmapLocked(info, bitmap);
416 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700417 }
Jason Monk9a944532014-07-08 09:31:21 -0400418 sendUserInfoChangedBroadcast(userId);
419 } finally {
420 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700421 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700422 }
423
424 private void sendUserInfoChangedBroadcast(int userId) {
425 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
426 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
427 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700428 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700429 }
430
Amith Yamasani258848d2012-08-10 17:06:33 -0700431 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700432 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700433 synchronized (mPackagesLock) {
434 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700435 if (info == null || info.partial) {
436 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
437 return null;
438 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100439 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
440 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
441 || callingGroupId != info.profileGroupId) {
442 checkManageUsersPermission("get the icon of a user who is not related");
443 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700444 if (info.iconPath == null) {
445 return null;
446 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700447 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700448 }
449 }
450
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700451 public void makeInitialized(int userId) {
452 checkManageUsersPermission("makeInitialized");
453 synchronized (mPackagesLock) {
454 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700455 if (info == null || info.partial) {
456 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
457 }
458 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700459 info.flags |= UserInfo.FLAG_INITIALIZED;
460 writeUserLocked(info);
461 }
462 }
463 }
464
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700465 /**
466 * If default guest restrictions haven't been initialized yet, add the basic
467 * restrictions.
468 */
469 private void initDefaultGuestRestrictions() {
470 if (mGuestRestrictions.isEmpty()) {
471 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
472 writeUserListLocked();
473 }
474 }
475
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800476 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530477 public Bundle getDefaultGuestRestrictions() {
478 checkManageUsersPermission("getDefaultGuestRestrictions");
479 synchronized (mPackagesLock) {
480 return new Bundle(mGuestRestrictions);
481 }
482 }
483
484 @Override
485 public void setDefaultGuestRestrictions(Bundle restrictions) {
486 checkManageUsersPermission("setDefaultGuestRestrictions");
487 synchronized (mPackagesLock) {
488 mGuestRestrictions.clear();
489 mGuestRestrictions.putAll(restrictions);
490 writeUserListLocked();
491 }
492 }
493
494 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700495 public boolean hasUserRestriction(String restrictionKey, int userId) {
496 synchronized (mPackagesLock) {
497 Bundle restrictions = mUserRestrictions.get(userId);
498 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
499 }
500 }
501
502 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800503 public Bundle getUserRestrictions(int userId) {
504 // checkManageUsersPermission("getUserRestrictions");
505
506 synchronized (mPackagesLock) {
507 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700508 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800509 }
510 }
511
512 @Override
513 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700514 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700515 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800516
517 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700518 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800519 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400520 long token = Binder.clearCallingIdentity();
521 try {
522 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
523 } catch (RemoteException e) {
524 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
525 } finally {
526 Binder.restoreCallingIdentity(token);
527 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800528 writeUserLocked(mUsers.get(userId));
529 }
530 }
531
Amith Yamasani258848d2012-08-10 17:06:33 -0700532 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700533 * Check if we've hit the limit of how many users can be created.
534 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700535 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700536 int aliveUserCount = 0;
537 final int totalUserCount = mUsers.size();
538 // Skip over users being removed
539 for (int i = 0; i < totalUserCount; i++) {
540 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700541 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700542 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700543 aliveUserCount++;
544 }
545 }
546 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700547 }
548
549 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700550 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700551 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700552 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700553 *
554 * @param message used as message if SecurityException is thrown
555 * @throws SecurityException if the caller is not system or root
556 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700557 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700558 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700559 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400560 && ActivityManager.checkComponentPermission(
561 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700562 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
563 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
564 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400565 }
566
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700567 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700568 try {
569 File dir = new File(mUsersDir, Integer.toString(info.id));
570 File file = new File(dir, USER_PHOTO_FILENAME);
571 if (!dir.exists()) {
572 dir.mkdir();
573 FileUtils.setPermissions(
574 dir.getPath(),
575 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
576 -1, -1);
577 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700578 FileOutputStream os;
579 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700580 info.iconPath = file.getAbsolutePath();
581 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700582 try {
583 os.close();
584 } catch (IOException ioe) {
585 // What the ... !
586 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700587 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700588 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700589 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700590 }
591
Amith Yamasani0b285492011-04-14 17:35:23 -0700592 /**
593 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
594 * cache it elsewhere.
595 * @return the array of user ids.
596 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700597 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700598 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700599 return mUserIds;
600 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700601 }
602
Dianne Hackborn4428e172012-08-24 17:43:05 -0700603 int[] getUserIdsLPr() {
604 return mUserIds;
605 }
606
Amith Yamasani13593602012-03-22 16:16:17 -0700607 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700608 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700609 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700610 return;
611 }
612 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700613 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700614 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700615 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700616 XmlPullParser parser = Xml.newPullParser();
617 parser.setInput(fis, null);
618 int type;
619 while ((type = parser.next()) != XmlPullParser.START_TAG
620 && type != XmlPullParser.END_DOCUMENT) {
621 ;
622 }
623
624 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700625 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700626 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700627 return;
628 }
629
Amith Yamasani2a003292012-08-14 18:25:45 -0700630 mNextSerialNumber = -1;
631 if (parser.getName().equals(TAG_USERS)) {
632 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
633 if (lastSerialNumber != null) {
634 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
635 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700636 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
637 if (versionNumber != null) {
638 mUserVersion = Integer.parseInt(versionNumber);
639 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700640 }
641
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700642 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530643 if (type == XmlPullParser.START_TAG) {
644 final String name = parser.getName();
645 if (name.equals(TAG_USER)) {
646 String id = parser.getAttributeValue(null, ATTR_ID);
647 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700648
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530649 if (user != null) {
650 mUsers.put(user.id, user);
651 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
652 mNextSerialNumber = user.id + 1;
653 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700654 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530655 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
656 mGuestRestrictions.clear();
657 readRestrictionsLocked(parser, mGuestRestrictions);
Amith Yamasani258848d2012-08-10 17:06:33 -0700658 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700659 }
660 }
Amith Yamasani13593602012-03-22 16:16:17 -0700661 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700662 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700663 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700664 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700665 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700666 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800667 } finally {
668 if (fis != null) {
669 try {
670 fis.close();
671 } catch (IOException e) {
672 }
673 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700674 }
675 }
676
Amith Yamasani6f34b412012-10-22 18:19:27 -0700677 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800678 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700679 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700680 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700681 int userVersion = mUserVersion;
682 if (userVersion < 1) {
683 // Assign a proper name for the owner, if not initialized correctly before
684 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
685 if ("Primary".equals(user.name)) {
686 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
687 writeUserLocked(user);
688 }
689 userVersion = 1;
690 }
691
Amith Yamasanibc9625052012-11-15 14:39:18 -0800692 if (userVersion < 2) {
693 // Owner should be marked as initialized
694 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
695 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
696 user.flags |= UserInfo.FLAG_INITIALIZED;
697 writeUserLocked(user);
698 }
699 userVersion = 2;
700 }
701
Amith Yamasani350962c2013-08-06 11:18:53 -0700702
Amith Yamasani5e486f52013-08-07 11:06:44 -0700703 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700704 userVersion = 4;
705 }
706
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700707 if (userVersion < 5) {
708 initDefaultGuestRestrictions();
709 userVersion = 5;
710 }
711
Amith Yamasani6f34b412012-10-22 18:19:27 -0700712 if (userVersion < USER_VERSION) {
713 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
714 + USER_VERSION);
715 } else {
716 mUserVersion = userVersion;
717 writeUserListLocked();
718 }
719 }
720
Amith Yamasani13593602012-03-22 16:16:17 -0700721 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700722 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800723 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700724 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700725 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700726 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700727 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400728 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800729
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500730 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800731 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
732
Amith Yamasani13593602012-03-22 16:16:17 -0700733 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700734 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700735
Amith Yamasani13593602012-03-22 16:16:17 -0700736 writeUserListLocked();
737 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700738 }
739
740 /*
741 * Writes the user file in this format:
742 *
743 * <user flags="20039023" id="0">
744 * <name>Primary</name>
745 * </user>
746 */
Amith Yamasani13593602012-03-22 16:16:17 -0700747 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700748 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700749 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700750 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700751 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700752 final BufferedOutputStream bos = new BufferedOutputStream(fos);
753
754 // XmlSerializer serializer = XmlUtils.serializerInstance();
755 final XmlSerializer serializer = new FastXmlSerializer();
756 serializer.setOutput(bos, "utf-8");
757 serializer.startDocument(null, true);
758 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
759
760 serializer.startTag(null, TAG_USER);
761 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700762 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700763 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700764 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
765 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
766 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700767 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
768 if (pinState != null) {
769 if (pinState.salt != 0) {
770 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
771 }
772 if (pinState.pinHash != null) {
773 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
774 }
775 if (pinState.failedAttempts != 0) {
776 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
777 Integer.toString(pinState.failedAttempts));
778 serializer.attribute(null, ATTR_LAST_RETRY_MS,
779 Long.toString(pinState.lastAttemptTime));
780 }
781 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700782 if (userInfo.iconPath != null) {
783 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
784 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700785 if (userInfo.partial) {
786 serializer.attribute(null, ATTR_PARTIAL, "true");
787 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700788 if (userInfo.guestToRemove) {
789 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
790 }
Kenny Guy2a764942014-04-02 13:29:20 +0100791 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
792 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
793 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000794 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700795
796 serializer.startTag(null, TAG_NAME);
797 serializer.text(userInfo.name);
798 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800799 Bundle restrictions = mUserRestrictions.get(userInfo.id);
800 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530801 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800802 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700803 serializer.endTag(null, TAG_USER);
804
805 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700806 userFile.finishWrite(fos);
807 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700808 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700809 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700810 }
811 }
812
813 /*
814 * Writes the user list file in this format:
815 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700816 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817 * <user id="0"></user>
818 * <user id="2"></user>
819 * </users>
820 */
Amith Yamasani13593602012-03-22 16:16:17 -0700821 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700822 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700823 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700824 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700825 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700826 final BufferedOutputStream bos = new BufferedOutputStream(fos);
827
828 // XmlSerializer serializer = XmlUtils.serializerInstance();
829 final XmlSerializer serializer = new FastXmlSerializer();
830 serializer.setOutput(bos, "utf-8");
831 serializer.startDocument(null, true);
832 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
833
834 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700835 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700836 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700837
Adam Lesinskieddeb492014-09-08 17:50:03 -0700838 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530839 writeRestrictionsLocked(serializer, mGuestRestrictions);
840 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700841 for (int i = 0; i < mUsers.size(); i++) {
842 UserInfo user = mUsers.valueAt(i);
843 serializer.startTag(null, TAG_USER);
844 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
845 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700846 }
847
848 serializer.endTag(null, TAG_USERS);
849
850 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700851 userListFile.finishWrite(fos);
852 } catch (Exception e) {
853 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700854 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700855 }
856 }
857
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530858 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
859 throws IOException {
860 serializer.startTag(null, TAG_RESTRICTIONS);
861 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
862 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
863 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
864 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
865 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
866 writeBoolean(serializer, restrictions,
867 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
868 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
869 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
870 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
871 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
872 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
873 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
874 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
875 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
876 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
877 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
878 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
879 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
880 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
881 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
882 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
883 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700884 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
885 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400886 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700887 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
888 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530889 serializer.endTag(null, TAG_RESTRICTIONS);
890 }
891
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800892 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700893 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700894 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700895 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700896 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700897 long creationTime = 0L;
898 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700899 long salt = 0L;
900 String pinHash = null;
901 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100902 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700903 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700904 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700905 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800906 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700907
908 FileInputStream fis = null;
909 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700910 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700911 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700912 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700913 XmlPullParser parser = Xml.newPullParser();
914 parser.setInput(fis, null);
915 int type;
916 while ((type = parser.next()) != XmlPullParser.START_TAG
917 && type != XmlPullParser.END_DOCUMENT) {
918 ;
919 }
920
921 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700922 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700923 return null;
924 }
925
926 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700927 int storedId = readIntAttribute(parser, ATTR_ID, -1);
928 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700929 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700930 return null;
931 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700932 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
933 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700934 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700935 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
936 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700937 salt = readLongAttribute(parser, ATTR_SALT, 0L);
938 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
939 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
940 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100941 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
942 UserInfo.NO_PROFILE_GROUP_ID);
943 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
944 // This attribute was added and renamed during development of L.
945 // TODO Remove upgrade path by 1st May 2014
946 profileGroupId = readIntAttribute(parser, "relatedGroupId",
947 UserInfo.NO_PROFILE_GROUP_ID);
948 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700949 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
950 if ("true".equals(valueString)) {
951 partial = true;
952 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700953 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
954 if ("true".equals(valueString)) {
955 guestToRemove = true;
956 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700957
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800958 int outerDepth = parser.getDepth();
959 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
960 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
961 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
962 continue;
963 }
964 String tag = parser.getName();
965 if (TAG_NAME.equals(tag)) {
966 type = parser.next();
967 if (type == XmlPullParser.TEXT) {
968 name = parser.getText();
969 }
970 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530971 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700972 }
973 }
974 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700975
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700976 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700977 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700978 userInfo.creationTime = creationTime;
979 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700980 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700981 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +0100982 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800983 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700984 if (salt != 0L) {
985 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
986 if (pinState == null) {
987 pinState = new RestrictionsPinState();
988 mRestrictionsPinStates.put(id, pinState);
989 }
990 pinState.salt = salt;
991 pinState.pinHash = pinHash;
992 pinState.failedAttempts = failedAttempts;
993 pinState.lastAttemptTime = lastAttemptTime;
994 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700995 return userInfo;
996
997 } catch (IOException ioe) {
998 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800999 } finally {
1000 if (fis != null) {
1001 try {
1002 fis.close();
1003 } catch (IOException e) {
1004 }
1005 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001006 }
1007 return null;
1008 }
1009
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301010 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1011 throws IOException {
1012 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1013 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1014 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1015 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1016 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1017 readBoolean(parser, restrictions,
1018 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1019 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1020 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1021 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1022 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1023 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1024 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1025 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1026 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1027 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1028 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1029 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1030 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1031 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1032 readBoolean(parser, restrictions,
1033 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1034 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1035 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001036 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1037 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001038 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001039 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1040 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301041 }
1042
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001043 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1044 String restrictionKey) {
1045 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001046 if (value != null) {
1047 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1048 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001049 }
1050
1051 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1052 throws IOException {
1053 if (restrictions.containsKey(restrictionKey)) {
1054 xml.attribute(null, restrictionKey,
1055 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1056 }
1057 }
1058
Amith Yamasani920ace02012-09-20 22:15:37 -07001059 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1060 String valueString = parser.getAttributeValue(null, attr);
1061 if (valueString == null) return defaultValue;
1062 try {
1063 return Integer.parseInt(valueString);
1064 } catch (NumberFormatException nfe) {
1065 return defaultValue;
1066 }
1067 }
1068
1069 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1070 String valueString = parser.getAttributeValue(null, attr);
1071 if (valueString == null) return defaultValue;
1072 try {
1073 return Long.parseLong(valueString);
1074 } catch (NumberFormatException nfe) {
1075 return defaultValue;
1076 }
1077 }
1078
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001079 private boolean isPackageInstalled(String pkg, int userId) {
1080 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1081 PackageManager.GET_UNINSTALLED_PACKAGES,
1082 userId);
1083 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1084 return false;
1085 }
1086 return true;
1087 }
1088
Amith Yamasanib82add22013-07-09 11:24:44 -07001089 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001090 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001091 * Does not do any permissions checking.
1092 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001093 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001094 synchronized (mPackagesLock) {
1095 File dir = Environment.getUserSystemDirectory(userId);
1096 String[] files = dir.list();
1097 if (files == null) return;
1098 for (String fileName : files) {
1099 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1100 File resFile = new File(dir, fileName);
1101 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001102 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001103 }
1104 }
1105 }
1106 }
1107 }
1108
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001109 /**
1110 * Removes the app restrictions file for a specific package and user id, if it exists.
1111 */
1112 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1113 synchronized (mPackagesLock) {
1114 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001115 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001116 if (resFile.exists()) {
1117 resFile.delete();
1118 }
1119 }
1120 }
1121
Kenny Guya52dc3e2014-02-11 15:33:14 +00001122 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001123 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001124 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001125 if (userId != UserHandle.USER_OWNER) {
1126 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001127 return null;
1128 }
Kenny Guy2a764942014-04-02 13:29:20 +01001129 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001130 }
1131
Amith Yamasani258848d2012-08-10 17:06:33 -07001132 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001133 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001134 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001135 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001136 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001137
Jessica Hummelbe81c802014-04-22 15:49:22 +01001138 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001139 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1140 UserManager.DISALLOW_ADD_USER, false)) {
1141 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1142 return null;
1143 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001144 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001145 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001146 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001147 try {
1148 synchronized (mInstallLock) {
1149 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001150 UserInfo parent = null;
1151 if (parentId != UserHandle.USER_NULL) {
1152 parent = getUserInfoLocked(parentId);
1153 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001154 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001155 // If we're not adding a guest user and the limit has been reached,
1156 // cannot add a user.
1157 if (!isGuest && isUserLimitReachedLocked()) {
1158 return null;
1159 }
1160 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001161 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001162 return null;
1163 }
1164 // Limit number of managed profiles that can be created
1165 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1166 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1167 >= MAX_MANAGED_PROFILES) {
1168 return null;
1169 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001170 int userId = getNextAvailableIdLocked();
1171 userInfo = new UserInfo(userId, name, null, flags);
1172 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1173 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001174 long now = System.currentTimeMillis();
1175 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001176 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001177 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001178 mUsers.put(userId, userInfo);
1179 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001180 if (parent != null) {
1181 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1182 parent.profileGroupId = parent.id;
1183 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001184 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001185 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001186 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001187 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001188 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001189 userInfo.partial = false;
1190 writeUserLocked(userInfo);
1191 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001192 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001193 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001194 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001195 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001196 if (userInfo != null) {
1197 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1198 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1199 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1200 android.Manifest.permission.MANAGE_USERS);
1201 }
1202 } finally {
1203 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001204 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001205 return userInfo;
1206 }
1207
Amith Yamasani95ab7842014-08-11 17:09:26 -07001208 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1209 int count = 0;
1210 for (int i = mUsers.size() - 1; i >= 0; i--) {
1211 UserInfo user = mUsers.valueAt(i);
1212 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1213 if ((user.flags & flags) != 0) {
1214 count++;
1215 }
1216 }
1217 }
1218 return count;
1219 }
1220
Amith Yamasani0b285492011-04-14 17:35:23 -07001221 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001222 * Find the current guest user. If the Guest user is partial,
1223 * then do not include it in the results as it is about to die.
1224 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1225 * the special handling of Guests being removed.
1226 */
1227 private UserInfo findCurrentGuestUserLocked() {
1228 final int size = mUsers.size();
1229 for (int i = 0; i < size; i++) {
1230 final UserInfo user = mUsers.valueAt(i);
1231 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1232 return user;
1233 }
1234 }
1235 return null;
1236 }
1237
1238 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001239 * Mark this guest user for deletion to allow us to create another guest
1240 * and switch to that user before actually removing this guest.
1241 * @param userHandle the userid of the current guest
1242 * @return whether the user could be marked for deletion
1243 */
1244 public boolean markGuestForDeletion(int userHandle) {
1245 checkManageUsersPermission("Only the system can remove users");
1246 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1247 UserManager.DISALLOW_REMOVE_USER, false)) {
1248 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1249 return false;
1250 }
1251
1252 long ident = Binder.clearCallingIdentity();
1253 try {
1254 final UserInfo user;
1255 synchronized (mPackagesLock) {
1256 user = mUsers.get(userHandle);
1257 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1258 return false;
1259 }
1260 if (!user.isGuest()) {
1261 return false;
1262 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001263 // We set this to a guest user that is to be removed. This is a temporary state
1264 // where we are allowed to add new Guest users, even if this one is still not
1265 // removed. This user will still show up in getUserInfo() calls.
1266 // If we don't get around to removing this Guest user, it will be purged on next
1267 // startup.
1268 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001269 // Mark it as disabled, so that it isn't returned any more when
1270 // profiles are queried.
1271 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001272 writeUserLocked(user);
1273 }
1274 } finally {
1275 Binder.restoreCallingIdentity(ident);
1276 }
1277 return true;
1278 }
1279
1280 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001281 * Removes a user and all data directories created for that user. This method should be called
1282 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001283 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001284 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001285 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001286 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001287 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1288 UserManager.DISALLOW_REMOVE_USER, false)) {
1289 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1290 return false;
1291 }
1292
Kenny Guyee58b4f2014-05-23 15:19:53 +01001293 long ident = Binder.clearCallingIdentity();
1294 try {
1295 final UserInfo user;
1296 synchronized (mPackagesLock) {
1297 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001298 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001299 return false;
1300 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001301
1302 // We remember deleted user IDs to prevent them from being
1303 // reused during the current boot; they can still be reused
1304 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001305 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001306
Kenny Guyee58b4f2014-05-23 15:19:53 +01001307 try {
1308 mAppOpsService.removeUser(userHandle);
1309 } catch (RemoteException e) {
1310 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1311 }
1312 // Set this to a partially created user, so that the user will be purged
1313 // on next startup, in case the runtime stops now before stopping and
1314 // removing the user completely.
1315 user.partial = true;
1316 // Mark it as disabled, so that it isn't returned any more when
1317 // profiles are queried.
1318 user.flags |= UserInfo.FLAG_DISABLED;
1319 writeUserLocked(user);
1320 }
1321
1322 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1323 && user.isManagedProfile()) {
1324 // Send broadcast to notify system that the user removed was a
1325 // managed user.
1326 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1327 }
1328
1329 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1330 int res;
1331 try {
1332 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1333 new IStopUserCallback.Stub() {
1334 @Override
1335 public void userStopped(int userId) {
1336 finishRemoveUser(userId);
1337 }
1338 @Override
1339 public void userStopAborted(int userId) {
1340 }
1341 });
1342 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001343 return false;
1344 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001345 return res == ActivityManager.USER_OP_SUCCESS;
1346 } finally {
1347 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001348 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001349 }
1350
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001351 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001352 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001353 // Let other services shutdown any activity and clean up their state before completely
1354 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001355 long ident = Binder.clearCallingIdentity();
1356 try {
1357 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1358 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001359 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1360 android.Manifest.permission.MANAGE_USERS,
1361
1362 new BroadcastReceiver() {
1363 @Override
1364 public void onReceive(Context context, Intent intent) {
1365 if (DBG) {
1366 Slog.i(LOG_TAG,
1367 "USER_REMOVED broadcast sent, cleaning up user data "
1368 + userHandle);
1369 }
1370 new Thread() {
1371 public void run() {
1372 synchronized (mInstallLock) {
1373 synchronized (mPackagesLock) {
1374 removeUserStateLocked(userHandle);
1375 }
1376 }
1377 }
1378 }.start();
1379 }
1380 },
1381
1382 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001383 } finally {
1384 Binder.restoreCallingIdentity(ident);
1385 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001386 }
1387
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001388 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001389 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001390 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001391
1392 // Remove this user from the list
1393 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001394
Amith Yamasani655d0e22013-06-12 14:19:10 -07001395 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001396 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001397 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001398 userFile.delete();
1399 // Update the user list
1400 writeUserListLocked();
1401 updateUserIdsLocked();
1402 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1403 }
1404
Amith Yamasani61f57372012-08-31 12:12:28 -07001405 private void removeDirectoryRecursive(File parent) {
1406 if (parent.isDirectory()) {
1407 String[] files = parent.list();
1408 for (String filename : files) {
1409 File child = new File(parent, filename);
1410 removeDirectoryRecursive(child);
1411 }
1412 }
1413 parent.delete();
1414 }
1415
Kenny Guyf8d3a232014-05-15 16:09:52 +01001416 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001417 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001418 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1419 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001420 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1421 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001422 }
1423
Amith Yamasani2a003292012-08-14 18:25:45 -07001424 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001425 public Bundle getApplicationRestrictions(String packageName) {
1426 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1427 }
1428
1429 @Override
1430 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001431 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001432 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001433 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001434 }
1435 synchronized (mPackagesLock) {
1436 // Read the restrictions from XML
1437 return readApplicationRestrictionsLocked(packageName, userId);
1438 }
1439 }
1440
1441 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001442 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001443 int userId) {
1444 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001445 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001446 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001447 }
1448 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001449 if (restrictions == null || restrictions.isEmpty()) {
1450 cleanAppRestrictionsForPackage(packageName, userId);
1451 } else {
1452 // Write the restrictions to XML
1453 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1454 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001455 }
Robin Lee66e5d962014-04-09 16:44:21 +01001456
Kenny Guyd21b2182014-07-17 16:38:55 +01001457 if (isPackageInstalled(packageName, userId)) {
1458 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1459 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1460 changeIntent.setPackage(packageName);
1461 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1462 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1463 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001464 }
1465
Amith Yamasani655d0e22013-06-12 14:19:10 -07001466 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001467 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001468 checkManageUsersPermission("Only system can modify the restrictions pin");
1469 int userId = UserHandle.getCallingUserId();
1470 synchronized (mPackagesLock) {
1471 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1472 if (pinState == null) {
1473 pinState = new RestrictionsPinState();
1474 }
1475 if (newPin == null) {
1476 pinState.salt = 0;
1477 pinState.pinHash = null;
1478 } else {
1479 try {
1480 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1481 } catch (NoSuchAlgorithmException e) {
1482 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1483 }
1484 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1485 pinState.failedAttempts = 0;
1486 }
1487 mRestrictionsPinStates.put(userId, pinState);
1488 writeUserLocked(mUsers.get(userId));
1489 }
1490 return true;
1491 }
1492
1493 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001494 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001495 checkManageUsersPermission("Only system can verify the restrictions pin");
1496 int userId = UserHandle.getCallingUserId();
1497 synchronized (mPackagesLock) {
1498 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1499 // If there's no pin set, return error code
1500 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1501 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1502 } else if (pin == null) {
1503 // If just checking if user can be prompted, return remaining time
1504 int waitTime = getRemainingTimeForPinAttempt(pinState);
1505 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1506 return waitTime;
1507 } else {
1508 int waitTime = getRemainingTimeForPinAttempt(pinState);
1509 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1510 if (waitTime > 0) {
1511 return waitTime;
1512 }
1513 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1514 pinState.failedAttempts = 0;
1515 writeUserLocked(mUsers.get(userId));
1516 return UserManager.PIN_VERIFICATION_SUCCESS;
1517 } else {
1518 pinState.failedAttempts++;
1519 pinState.lastAttemptTime = System.currentTimeMillis();
1520 writeUserLocked(mUsers.get(userId));
1521 return waitTime;
1522 }
1523 }
1524 }
1525 }
1526
1527 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1528 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1529 BACKOFF_TIMES.length - 1);
1530 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1531 BACKOFF_TIMES[backoffIndex] : 0;
1532 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1533 0);
1534 }
1535
1536 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001537 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001538 int userId = UserHandle.getCallingUserId();
1539 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001540 return hasRestrictionsPinLocked(userId);
1541 }
1542 }
1543
1544 private boolean hasRestrictionsPinLocked(int userId) {
1545 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1546 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1547 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001548 }
1549 return true;
1550 }
1551
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001552 @Override
1553 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001554 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001555 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001556 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001557 }
1558
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001559 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001560 synchronized (mPackagesLock) {
1561 // Remove all user restrictions
1562 setUserRestrictions(new Bundle(), userHandle);
1563 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001564 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001565 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001566 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001567 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001568 if (unhideApps) {
1569 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001570 }
1571 }
1572
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001573 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001574 mHandler.post(new Runnable() {
1575 @Override
1576 public void run() {
1577 List<ApplicationInfo> apps =
1578 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1579 userHandle).getList();
1580 final long ident = Binder.clearCallingIdentity();
1581 try {
1582 for (ApplicationInfo appInfo : apps) {
1583 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001584 && (appInfo.flags & ApplicationInfo.FLAG_HIDDEN) != 0) {
1585 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001586 userHandle);
1587 }
1588 }
1589 } finally {
1590 Binder.restoreCallingIdentity(ident);
1591 }
1592 }
1593 });
1594 }
1595
Amith Yamasani655d0e22013-06-12 14:19:10 -07001596 /*
1597 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1598 * Not the most secure, but it is at least a second level of protection. First level is that
1599 * the file is in a location only readable by the system process.
1600 * @param password the password.
1601 * @param salt the randomly generated salt
1602 * @return the hash of the pattern in a String.
1603 */
1604 private String passwordToHash(String password, long salt) {
1605 if (password == null) {
1606 return null;
1607 }
1608 String algo = null;
1609 String hashed = salt + password;
1610 try {
1611 byte[] saltedPassword = (password + salt).getBytes();
1612 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1613 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1614 hashed = toHex(sha1) + toHex(md5);
1615 } catch (NoSuchAlgorithmException e) {
1616 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1617 }
1618 return hashed;
1619 }
1620
1621 private static String toHex(byte[] ary) {
1622 final String hex = "0123456789ABCDEF";
1623 String ret = "";
1624 for (int i = 0; i < ary.length; i++) {
1625 ret += hex.charAt((ary[i] >> 4) & 0xf);
1626 ret += hex.charAt(ary[i] & 0xf);
1627 }
1628 return ret;
1629 }
1630
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001631 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001632 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001633 try {
1634 return mContext.getPackageManager().getApplicationInfo(packageName,
1635 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1636 } catch (NameNotFoundException nnfe) {
1637 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001638 } finally {
1639 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001640 }
1641 }
1642
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001643 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001644 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001645 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001646 final ArrayList<String> values = new ArrayList<String>();
1647
1648 FileInputStream fis = null;
1649 try {
1650 AtomicFile restrictionsFile =
1651 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001652 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001653 fis = restrictionsFile.openRead();
1654 XmlPullParser parser = Xml.newPullParser();
1655 parser.setInput(fis, null);
1656 int type;
1657 while ((type = parser.next()) != XmlPullParser.START_TAG
1658 && type != XmlPullParser.END_DOCUMENT) {
1659 ;
1660 }
1661
1662 if (type != XmlPullParser.START_TAG) {
1663 Slog.e(LOG_TAG, "Unable to read restrictions file "
1664 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001665 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001666 }
1667
1668 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1669 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1670 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001671 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001672 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1673 if (multiple != null) {
Amith Yamasanie0840392014-08-27 10:33:17 -07001674 values.clear();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 int count = Integer.parseInt(multiple);
1676 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1677 if (type == XmlPullParser.START_TAG
1678 && parser.getName().equals(TAG_VALUE)) {
1679 values.add(parser.nextText().trim());
1680 count--;
1681 }
1682 }
1683 String [] valueStrings = new String[values.size()];
1684 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001685 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001686 } else {
1687 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001688 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1689 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1690 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1691 restrictions.putInt(key, Integer.parseInt(value));
1692 } else {
1693 restrictions.putString(key, value);
1694 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001695 }
1696 }
1697 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001698 } catch (IOException ioe) {
1699 } catch (XmlPullParserException pe) {
1700 } finally {
1701 if (fis != null) {
1702 try {
1703 fis.close();
1704 } catch (IOException e) {
1705 }
1706 }
1707 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001708 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001709 }
1710
1711 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001712 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001713 FileOutputStream fos = null;
1714 AtomicFile restrictionsFile = new AtomicFile(
1715 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001716 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001717 try {
1718 fos = restrictionsFile.startWrite();
1719 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1720
1721 // XmlSerializer serializer = XmlUtils.serializerInstance();
1722 final XmlSerializer serializer = new FastXmlSerializer();
1723 serializer.setOutput(bos, "utf-8");
1724 serializer.startDocument(null, true);
1725 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1726
1727 serializer.startTag(null, TAG_RESTRICTIONS);
1728
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001729 for (String key : restrictions.keySet()) {
1730 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001731 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001732 serializer.attribute(null, ATTR_KEY, key);
1733
1734 if (value instanceof Boolean) {
1735 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1736 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001737 } else if (value instanceof Integer) {
1738 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1739 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001740 } else if (value == null || value instanceof String) {
1741 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1742 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001743 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001744 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1745 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001746 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001747 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001748 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001749 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001750 serializer.endTag(null, TAG_VALUE);
1751 }
1752 }
1753 serializer.endTag(null, TAG_ENTRY);
1754 }
1755
1756 serializer.endTag(null, TAG_RESTRICTIONS);
1757
1758 serializer.endDocument();
1759 restrictionsFile.finishWrite(fos);
1760 } catch (Exception e) {
1761 restrictionsFile.failWrite(fos);
1762 Slog.e(LOG_TAG, "Error writing application restrictions list");
1763 }
1764 }
1765
1766 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001767 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001768 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001769 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001770 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001771 }
1772 }
1773
1774 @Override
1775 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001776 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001777 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001778 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001779 }
1780 // Not found
1781 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001782 }
1783 }
1784
Amith Yamasani0b285492011-04-14 17:35:23 -07001785 /**
1786 * Caches the list of user ids in an array, adjusting the array size when necessary.
1787 */
Amith Yamasani13593602012-03-22 16:16:17 -07001788 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001789 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001790 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001791 if (!mUsers.valueAt(i).partial) {
1792 num++;
1793 }
1794 }
Amith Yamasani16389312012-10-17 21:20:14 -07001795 final int[] newUsers = new int[num];
1796 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001797 for (int i = 0; i < mUsers.size(); i++) {
1798 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001799 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001800 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001801 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001802 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001803 }
1804
1805 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001806 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001807 * @param userId the user that was just foregrounded
1808 */
1809 public void userForeground(int userId) {
1810 synchronized (mPackagesLock) {
1811 UserInfo user = mUsers.get(userId);
1812 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001813 if (user == null || user.partial) {
1814 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1815 return;
1816 }
1817 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001818 user.lastLoggedInTime = now;
1819 writeUserLocked(user);
1820 }
1821 }
1822 }
1823
1824 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001825 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001826 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1827 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001828 * @return
1829 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001830 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001831 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001832 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001833 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001834 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001835 break;
1836 }
1837 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001838 }
Amith Yamasani195263742012-08-21 15:40:12 -07001839 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001840 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001841 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001842
Amith Yamasanifc95e702013-09-26 13:20:17 -07001843 private String packageToRestrictionsFileName(String packageName) {
1844 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1845 }
1846
1847 private String restrictionsFileNameToPackage(String fileName) {
1848 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1849 (int) (fileName.length() - XML_SUFFIX.length()));
1850 }
1851
Amith Yamasani920ace02012-09-20 22:15:37 -07001852 @Override
1853 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1854 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1855 != PackageManager.PERMISSION_GRANTED) {
1856 pw.println("Permission Denial: can't dump UserManager from from pid="
1857 + Binder.getCallingPid()
1858 + ", uid=" + Binder.getCallingUid()
1859 + " without permission "
1860 + android.Manifest.permission.DUMP);
1861 return;
1862 }
1863
1864 long now = System.currentTimeMillis();
1865 StringBuilder sb = new StringBuilder();
1866 synchronized (mPackagesLock) {
1867 pw.println("Users:");
1868 for (int i = 0; i < mUsers.size(); i++) {
1869 UserInfo user = mUsers.valueAt(i);
1870 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001871 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001872 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001873 if (user.partial) pw.print(" <partial>");
1874 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001875 pw.print(" Created: ");
1876 if (user.creationTime == 0) {
1877 pw.println("<unknown>");
1878 } else {
1879 sb.setLength(0);
1880 TimeUtils.formatDuration(now - user.creationTime, sb);
1881 sb.append(" ago");
1882 pw.println(sb);
1883 }
1884 pw.print(" Last logged in: ");
1885 if (user.lastLoggedInTime == 0) {
1886 pw.println("<unknown>");
1887 } else {
1888 sb.setLength(0);
1889 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1890 sb.append(" ago");
1891 pw.println(sb);
1892 }
1893 }
1894 }
1895 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001896}