blob: c5588452b8e23cd6dfb7f85c41321eb1c75d8b63 [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);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800227 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700228 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700229 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700230 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
231 for (int i = 0; i < mUsers.size(); i++) {
232 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700233 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700234 partials.add(ui);
235 }
236 }
237 for (int i = 0; i < partials.size(); i++) {
238 UserInfo ui = partials.get(i);
239 Slog.w(LOG_TAG, "Removing partially created user #" + i
240 + " (name=" + ui.name + ")");
241 removeUserStateLocked(ui.id);
242 }
243 sInstance = this;
244 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700245 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700246 }
247
248 void systemReady() {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700249 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400250 mAppOpsService = IAppOpsService.Stub.asInterface(
251 ServiceManager.getService(Context.APP_OPS_SERVICE));
252 for (int i = 0; i < mUserIds.length; ++i) {
253 try {
254 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
255 } catch (RemoteException e) {
256 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
257 }
258 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700259 }
260
261 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700262 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700263 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700264 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700265 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
266 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700267 UserInfo ui = mUsers.valueAt(i);
268 if (ui.partial) {
269 continue;
270 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800271 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700272 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700273 }
Amith Yamasani13593602012-03-22 16:16:17 -0700274 }
275 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700276 }
Amith Yamasani13593602012-03-22 16:16:17 -0700277 }
278
Amith Yamasani258848d2012-08-10 17:06:33 -0700279 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100280 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800281 if (userId != UserHandle.getCallingUserId()) {
282 checkManageUsersPermission("getting profiles related to user " + userId);
283 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700284 final long ident = Binder.clearCallingIdentity();
285 try {
286 synchronized (mPackagesLock) {
287 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100288 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700289 } finally {
290 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000291 }
292 }
293
Amith Yamasanibe465322014-04-24 13:45:17 -0700294 /** Assume permissions already checked and caller's identity cleared */
295 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700296 UserInfo user = getUserInfoLocked(userId);
297 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700298 if (user == null) {
299 // Probably a dying user
300 return users;
301 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700302 for (int i = 0; i < mUsers.size(); i++) {
303 UserInfo profile = mUsers.valueAt(i);
304 if (!isProfileOf(user, profile)) {
305 continue;
306 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100307 if (enabledOnly && !profile.isEnabled()) {
308 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700309 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700310 if (mRemovingUserIds.get(profile.id)) {
311 continue;
312 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700313 users.add(profile);
314 }
315 return users;
316 }
317
Jessica Hummelbe81c802014-04-22 15:49:22 +0100318 @Override
319 public UserInfo getProfileParent(int userHandle) {
320 checkManageUsersPermission("get the profile parent");
321 synchronized (mPackagesLock) {
322 UserInfo profile = getUserInfoLocked(userHandle);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -0800323 if (profile == null) {
324 return null;
325 }
Jessica Hummelbe81c802014-04-22 15:49:22 +0100326 int parentUserId = profile.profileGroupId;
327 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
328 return null;
329 } else {
330 return getUserInfoLocked(parentUserId);
331 }
332 }
333 }
334
Kenny Guy2a764942014-04-02 13:29:20 +0100335 private boolean isProfileOf(UserInfo user, UserInfo profile) {
336 return user.id == profile.id ||
337 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
338 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000339 }
340
341 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100342 public void setUserEnabled(int userId) {
343 checkManageUsersPermission("enable user");
344 synchronized (mPackagesLock) {
345 UserInfo info = getUserInfoLocked(userId);
346 if (info != null && !info.isEnabled()) {
347 info.flags ^= UserInfo.FLAG_DISABLED;
348 writeUserLocked(info);
349 }
350 }
351 }
352
353 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700354 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700355 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700356 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700357 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700358 }
359 }
360
Amith Yamasani71e6c692013-03-24 17:39:28 -0700361 @Override
362 public boolean isRestricted() {
363 synchronized (mPackagesLock) {
364 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
365 }
366 }
367
Amith Yamasani195263742012-08-21 15:40:12 -0700368 /*
369 * Should be locked on mUsers before calling this.
370 */
371 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700372 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700373 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800374 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700375 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
376 return null;
377 }
378 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700379 }
380
Amith Yamasani13593602012-03-22 16:16:17 -0700381 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700382 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700383 return ArrayUtils.contains(mUserIds, userId);
384 }
385 }
386
Amith Yamasani258848d2012-08-10 17:06:33 -0700387 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700388 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700389 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700390 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700391 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700392 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700393 if (info == null || info.partial) {
394 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
395 return;
396 }
Amith Yamasani13593602012-03-22 16:16:17 -0700397 if (name != null && !name.equals(info.name)) {
398 info.name = name;
399 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700400 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700401 }
402 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700403 if (changed) {
404 sendUserInfoChangedBroadcast(userId);
405 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700406 }
407
Amith Yamasani258848d2012-08-10 17:06:33 -0700408 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700409 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700410 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400411 long ident = Binder.clearCallingIdentity();
412 try {
413 synchronized (mPackagesLock) {
414 UserInfo info = mUsers.get(userId);
415 if (info == null || info.partial) {
416 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
417 return;
418 }
419 writeBitmapLocked(info, bitmap);
420 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700421 }
Jason Monk9a944532014-07-08 09:31:21 -0400422 sendUserInfoChangedBroadcast(userId);
423 } finally {
424 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700425 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700426 }
427
428 private void sendUserInfoChangedBroadcast(int userId) {
429 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
430 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
431 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700432 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700433 }
434
Amith Yamasani258848d2012-08-10 17:06:33 -0700435 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700436 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700437 synchronized (mPackagesLock) {
438 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 if (info == null || info.partial) {
440 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
441 return null;
442 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100443 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
444 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
445 || callingGroupId != info.profileGroupId) {
446 checkManageUsersPermission("get the icon of a user who is not related");
447 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700448 if (info.iconPath == null) {
449 return null;
450 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700451 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700452 }
453 }
454
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700455 public void makeInitialized(int userId) {
456 checkManageUsersPermission("makeInitialized");
457 synchronized (mPackagesLock) {
458 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700459 if (info == null || info.partial) {
460 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
461 }
462 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700463 info.flags |= UserInfo.FLAG_INITIALIZED;
464 writeUserLocked(info);
465 }
466 }
467 }
468
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700469 /**
470 * If default guest restrictions haven't been initialized yet, add the basic
471 * restrictions.
472 */
473 private void initDefaultGuestRestrictions() {
474 if (mGuestRestrictions.isEmpty()) {
475 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800476 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700477 }
478 }
479
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800480 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530481 public Bundle getDefaultGuestRestrictions() {
482 checkManageUsersPermission("getDefaultGuestRestrictions");
483 synchronized (mPackagesLock) {
484 return new Bundle(mGuestRestrictions);
485 }
486 }
487
488 @Override
489 public void setDefaultGuestRestrictions(Bundle restrictions) {
490 checkManageUsersPermission("setDefaultGuestRestrictions");
491 synchronized (mPackagesLock) {
492 mGuestRestrictions.clear();
493 mGuestRestrictions.putAll(restrictions);
494 writeUserListLocked();
495 }
496 }
497
498 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700499 public boolean hasUserRestriction(String restrictionKey, int userId) {
500 synchronized (mPackagesLock) {
501 Bundle restrictions = mUserRestrictions.get(userId);
502 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
503 }
504 }
505
506 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800507 public Bundle getUserRestrictions(int userId) {
508 // checkManageUsersPermission("getUserRestrictions");
509
510 synchronized (mPackagesLock) {
511 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700512 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800513 }
514 }
515
516 @Override
517 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700518 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700519 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800520
521 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700522 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800523 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400524 long token = Binder.clearCallingIdentity();
525 try {
526 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
527 } catch (RemoteException e) {
528 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
529 } finally {
530 Binder.restoreCallingIdentity(token);
531 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800532 writeUserLocked(mUsers.get(userId));
533 }
534 }
535
Amith Yamasani258848d2012-08-10 17:06:33 -0700536 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700537 * Check if we've hit the limit of how many users can be created.
538 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700539 private boolean isUserLimitReachedLocked() {
Nicolas Prevot12678a92015-05-13 12:15:03 -0700540 return getAliveUsersExcludingGuestsCountLocked() >= UserManager.getMaxSupportedUsers();
541 }
542
543 @Override
544 public boolean canAddMoreManagedProfiles() {
545 checkManageUsersPermission("check if more managed profiles can be added.");
546 if (ActivityManager.isLowRamDeviceStatic()) {
547 return false;
548 }
549 synchronized(mPackagesLock) {
550 // Limit number of managed profiles that can be created
551 if (numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
552 >= MAX_MANAGED_PROFILES) {
553 return false;
554 }
555 int usersCount = getAliveUsersExcludingGuestsCountLocked();
556 // We allow creating a managed profile in the special case where there is only one user.
557 return usersCount == 1 || usersCount < UserManager.getMaxSupportedUsers();
558 }
559 }
560
561 private int getAliveUsersExcludingGuestsCountLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700562 int aliveUserCount = 0;
563 final int totalUserCount = mUsers.size();
564 // Skip over users being removed
565 for (int i = 0; i < totalUserCount; i++) {
566 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700567 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700568 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700569 aliveUserCount++;
570 }
571 }
Nicolas Prevot12678a92015-05-13 12:15:03 -0700572 return aliveUserCount;
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700573 }
574
575 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700576 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700577 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700578 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700579 *
580 * @param message used as message if SecurityException is thrown
581 * @throws SecurityException if the caller is not system or root
582 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700583 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700584 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700585 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400586 && ActivityManager.checkComponentPermission(
587 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700588 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
589 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
590 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400591 }
592
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700593 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700594 try {
595 File dir = new File(mUsersDir, Integer.toString(info.id));
596 File file = new File(dir, USER_PHOTO_FILENAME);
597 if (!dir.exists()) {
598 dir.mkdir();
599 FileUtils.setPermissions(
600 dir.getPath(),
601 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
602 -1, -1);
603 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700604 FileOutputStream os;
605 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700606 info.iconPath = file.getAbsolutePath();
607 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700608 try {
609 os.close();
610 } catch (IOException ioe) {
611 // What the ... !
612 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700613 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700614 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700615 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700616 }
617
Amith Yamasani0b285492011-04-14 17:35:23 -0700618 /**
619 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
620 * cache it elsewhere.
621 * @return the array of user ids.
622 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700623 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700624 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700625 return mUserIds;
626 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700627 }
628
Dianne Hackborn4428e172012-08-24 17:43:05 -0700629 int[] getUserIdsLPr() {
630 return mUserIds;
631 }
632
Amith Yamasani13593602012-03-22 16:16:17 -0700633 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700634 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700635 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700636 return;
637 }
638 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700639 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700640 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700641 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700642 XmlPullParser parser = Xml.newPullParser();
643 parser.setInput(fis, null);
644 int type;
645 while ((type = parser.next()) != XmlPullParser.START_TAG
646 && type != XmlPullParser.END_DOCUMENT) {
647 ;
648 }
649
650 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700651 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700652 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700653 return;
654 }
655
Amith Yamasani2a003292012-08-14 18:25:45 -0700656 mNextSerialNumber = -1;
657 if (parser.getName().equals(TAG_USERS)) {
658 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
659 if (lastSerialNumber != null) {
660 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
661 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700662 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
663 if (versionNumber != null) {
664 mUserVersion = Integer.parseInt(versionNumber);
665 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700666 }
667
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700668 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530669 if (type == XmlPullParser.START_TAG) {
670 final String name = parser.getName();
671 if (name.equals(TAG_USER)) {
672 String id = parser.getAttributeValue(null, ATTR_ID);
673 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700674
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530675 if (user != null) {
676 mUsers.put(user.id, user);
677 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
678 mNextSerialNumber = user.id + 1;
679 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700680 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530681 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800682 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
683 && type != XmlPullParser.END_TAG) {
684 if (type == XmlPullParser.START_TAG) {
685 if (parser.getName().equals(TAG_RESTRICTIONS)) {
686 readRestrictionsLocked(parser, mGuestRestrictions);
687 }
688 break;
689 }
690 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700691 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700692 }
693 }
Amith Yamasani13593602012-03-22 16:16:17 -0700694 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700695 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700696 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700697 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700698 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700699 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800700 } finally {
701 if (fis != null) {
702 try {
703 fis.close();
704 } catch (IOException e) {
705 }
706 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700707 }
708 }
709
Amith Yamasani6f34b412012-10-22 18:19:27 -0700710 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800711 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700712 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700713 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700714 int userVersion = mUserVersion;
715 if (userVersion < 1) {
716 // Assign a proper name for the owner, if not initialized correctly before
717 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
718 if ("Primary".equals(user.name)) {
719 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
720 writeUserLocked(user);
721 }
722 userVersion = 1;
723 }
724
Amith Yamasanibc9625052012-11-15 14:39:18 -0800725 if (userVersion < 2) {
726 // Owner should be marked as initialized
727 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
728 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
729 user.flags |= UserInfo.FLAG_INITIALIZED;
730 writeUserLocked(user);
731 }
732 userVersion = 2;
733 }
734
Amith Yamasani350962c2013-08-06 11:18:53 -0700735
Amith Yamasani5e486f52013-08-07 11:06:44 -0700736 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700737 userVersion = 4;
738 }
739
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700740 if (userVersion < 5) {
741 initDefaultGuestRestrictions();
742 userVersion = 5;
743 }
744
Amith Yamasani6f34b412012-10-22 18:19:27 -0700745 if (userVersion < USER_VERSION) {
746 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
747 + USER_VERSION);
748 } else {
749 mUserVersion = userVersion;
750 writeUserListLocked();
751 }
752 }
753
Amith Yamasani13593602012-03-22 16:16:17 -0700754 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700755 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800756 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700757 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700758 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700759 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700760 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400761 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800762
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500763 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800764 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
765
Amith Yamasani13593602012-03-22 16:16:17 -0700766 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700767 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700768
Amith Yamasani13593602012-03-22 16:16:17 -0700769 writeUserListLocked();
770 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700771 }
772
773 /*
774 * Writes the user file in this format:
775 *
776 * <user flags="20039023" id="0">
777 * <name>Primary</name>
778 * </user>
779 */
Amith Yamasani13593602012-03-22 16:16:17 -0700780 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700781 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700782 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700783 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700784 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700785 final BufferedOutputStream bos = new BufferedOutputStream(fos);
786
787 // XmlSerializer serializer = XmlUtils.serializerInstance();
788 final XmlSerializer serializer = new FastXmlSerializer();
789 serializer.setOutput(bos, "utf-8");
790 serializer.startDocument(null, true);
791 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
792
793 serializer.startTag(null, TAG_USER);
794 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700795 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700796 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700797 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
798 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
799 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700800 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
801 if (pinState != null) {
802 if (pinState.salt != 0) {
803 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
804 }
805 if (pinState.pinHash != null) {
806 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
807 }
808 if (pinState.failedAttempts != 0) {
809 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
810 Integer.toString(pinState.failedAttempts));
811 serializer.attribute(null, ATTR_LAST_RETRY_MS,
812 Long.toString(pinState.lastAttemptTime));
813 }
814 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700815 if (userInfo.iconPath != null) {
816 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
817 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700818 if (userInfo.partial) {
819 serializer.attribute(null, ATTR_PARTIAL, "true");
820 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700821 if (userInfo.guestToRemove) {
822 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
823 }
Kenny Guy2a764942014-04-02 13:29:20 +0100824 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
825 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
826 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000827 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700828
829 serializer.startTag(null, TAG_NAME);
830 serializer.text(userInfo.name);
831 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800832 Bundle restrictions = mUserRestrictions.get(userInfo.id);
833 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530834 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800835 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700836 serializer.endTag(null, TAG_USER);
837
838 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700839 userFile.finishWrite(fos);
840 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700841 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700842 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700843 }
844 }
845
846 /*
847 * Writes the user list file in this format:
848 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700849 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700850 * <user id="0"></user>
851 * <user id="2"></user>
852 * </users>
853 */
Amith Yamasani13593602012-03-22 16:16:17 -0700854 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700855 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700856 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700857 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700858 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700859 final BufferedOutputStream bos = new BufferedOutputStream(fos);
860
861 // XmlSerializer serializer = XmlUtils.serializerInstance();
862 final XmlSerializer serializer = new FastXmlSerializer();
863 serializer.setOutput(bos, "utf-8");
864 serializer.startDocument(null, true);
865 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
866
867 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700868 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700869 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700870
Adam Lesinskieddeb492014-09-08 17:50:03 -0700871 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530872 writeRestrictionsLocked(serializer, mGuestRestrictions);
873 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700874 for (int i = 0; i < mUsers.size(); i++) {
875 UserInfo user = mUsers.valueAt(i);
876 serializer.startTag(null, TAG_USER);
877 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
878 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700879 }
880
881 serializer.endTag(null, TAG_USERS);
882
883 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700884 userListFile.finishWrite(fos);
885 } catch (Exception e) {
886 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700887 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700888 }
889 }
890
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530891 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
892 throws IOException {
893 serializer.startTag(null, TAG_RESTRICTIONS);
894 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
895 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
896 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
897 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
898 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
899 writeBoolean(serializer, restrictions,
900 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
901 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
902 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
903 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
904 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
905 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
906 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
907 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
908 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
909 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
910 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
911 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
912 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
913 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
914 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
915 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
916 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700917 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
918 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400919 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700920 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
921 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530922 serializer.endTag(null, TAG_RESTRICTIONS);
923 }
924
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800925 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700926 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700927 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700929 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700930 long creationTime = 0L;
931 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700932 long salt = 0L;
933 String pinHash = null;
934 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100935 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700936 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700937 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700938 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800939 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700940
941 FileInputStream fis = null;
942 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700943 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700944 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700945 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700946 XmlPullParser parser = Xml.newPullParser();
947 parser.setInput(fis, null);
948 int type;
949 while ((type = parser.next()) != XmlPullParser.START_TAG
950 && type != XmlPullParser.END_DOCUMENT) {
951 ;
952 }
953
954 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700955 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700956 return null;
957 }
958
959 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700960 int storedId = readIntAttribute(parser, ATTR_ID, -1);
961 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700962 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700963 return null;
964 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700965 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
966 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700967 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700968 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
969 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700970 salt = readLongAttribute(parser, ATTR_SALT, 0L);
971 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
972 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
973 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100974 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
975 UserInfo.NO_PROFILE_GROUP_ID);
976 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
977 // This attribute was added and renamed during development of L.
978 // TODO Remove upgrade path by 1st May 2014
979 profileGroupId = readIntAttribute(parser, "relatedGroupId",
980 UserInfo.NO_PROFILE_GROUP_ID);
981 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700982 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
983 if ("true".equals(valueString)) {
984 partial = true;
985 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700986 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
987 if ("true".equals(valueString)) {
988 guestToRemove = true;
989 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700990
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800991 int outerDepth = parser.getDepth();
992 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
993 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
994 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
995 continue;
996 }
997 String tag = parser.getName();
998 if (TAG_NAME.equals(tag)) {
999 type = parser.next();
1000 if (type == XmlPullParser.TEXT) {
1001 name = parser.getText();
1002 }
1003 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301004 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001005 }
1006 }
1007 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001008
Amith Yamasanib8151ec2012-04-18 18:02:48 -07001009 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -07001010 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -07001011 userInfo.creationTime = creationTime;
1012 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001013 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -07001014 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +01001015 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001016 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -07001017 if (salt != 0L) {
1018 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
1019 if (pinState == null) {
1020 pinState = new RestrictionsPinState();
1021 mRestrictionsPinStates.put(id, pinState);
1022 }
1023 pinState.salt = salt;
1024 pinState.pinHash = pinHash;
1025 pinState.failedAttempts = failedAttempts;
1026 pinState.lastAttemptTime = lastAttemptTime;
1027 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001028 return userInfo;
1029
1030 } catch (IOException ioe) {
1031 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001032 } finally {
1033 if (fis != null) {
1034 try {
1035 fis.close();
1036 } catch (IOException e) {
1037 }
1038 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001039 }
1040 return null;
1041 }
1042
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301043 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1044 throws IOException {
1045 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1046 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1047 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1048 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1049 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1050 readBoolean(parser, restrictions,
1051 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1052 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1053 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1054 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1055 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1056 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1057 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1058 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1059 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1060 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1061 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1062 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1063 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1064 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1065 readBoolean(parser, restrictions,
1066 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1067 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1068 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001069 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1070 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001071 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001072 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1073 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301074 }
1075
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001076 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1077 String restrictionKey) {
1078 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001079 if (value != null) {
1080 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1081 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001082 }
1083
1084 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1085 throws IOException {
1086 if (restrictions.containsKey(restrictionKey)) {
1087 xml.attribute(null, restrictionKey,
1088 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1089 }
1090 }
1091
Amith Yamasani920ace02012-09-20 22:15:37 -07001092 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1093 String valueString = parser.getAttributeValue(null, attr);
1094 if (valueString == null) return defaultValue;
1095 try {
1096 return Integer.parseInt(valueString);
1097 } catch (NumberFormatException nfe) {
1098 return defaultValue;
1099 }
1100 }
1101
1102 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1103 String valueString = parser.getAttributeValue(null, attr);
1104 if (valueString == null) return defaultValue;
1105 try {
1106 return Long.parseLong(valueString);
1107 } catch (NumberFormatException nfe) {
1108 return defaultValue;
1109 }
1110 }
1111
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001112 private boolean isPackageInstalled(String pkg, int userId) {
1113 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1114 PackageManager.GET_UNINSTALLED_PACKAGES,
1115 userId);
1116 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1117 return false;
1118 }
1119 return true;
1120 }
1121
Amith Yamasanib82add22013-07-09 11:24:44 -07001122 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001123 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001124 * Does not do any permissions checking.
1125 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001126 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001127 synchronized (mPackagesLock) {
1128 File dir = Environment.getUserSystemDirectory(userId);
1129 String[] files = dir.list();
1130 if (files == null) return;
1131 for (String fileName : files) {
1132 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1133 File resFile = new File(dir, fileName);
1134 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001135 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001136 }
1137 }
1138 }
1139 }
1140 }
1141
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001142 /**
1143 * Removes the app restrictions file for a specific package and user id, if it exists.
1144 */
1145 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1146 synchronized (mPackagesLock) {
1147 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001148 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001149 if (resFile.exists()) {
1150 resFile.delete();
1151 }
1152 }
1153 }
1154
Kenny Guya52dc3e2014-02-11 15:33:14 +00001155 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001156 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001157 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001158 if (userId != UserHandle.USER_OWNER) {
1159 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001160 return null;
1161 }
Kenny Guy2a764942014-04-02 13:29:20 +01001162 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001163 }
1164
Amith Yamasani258848d2012-08-10 17:06:33 -07001165 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001166 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001167 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001168 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001169 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001170
Jessica Hummelbe81c802014-04-22 15:49:22 +01001171 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001172 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1173 UserManager.DISALLOW_ADD_USER, false)) {
1174 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1175 return null;
1176 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001177 if (ActivityManager.isLowRamDeviceStatic()) {
1178 return null;
1179 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001180 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Nicolas Prevot12678a92015-05-13 12:15:03 -07001181 final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001182 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001183 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001184 try {
1185 synchronized (mInstallLock) {
1186 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001187 UserInfo parent = null;
1188 if (parentId != UserHandle.USER_NULL) {
1189 parent = getUserInfoLocked(parentId);
1190 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001191 }
Nicolas Prevot12678a92015-05-13 12:15:03 -07001192 if (isManagedProfile && !canAddMoreManagedProfiles()) {
1193 return null;
1194 }
1195 if (!isGuest && !isManagedProfile && isUserLimitReachedLocked()) {
1196 // If we're not adding a guest user or a managed profile and the limit has
1197 // been reached, cannot add a user.
Amith Yamasani95ab7842014-08-11 17:09:26 -07001198 return null;
1199 }
1200 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001201 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001202 return null;
1203 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001204 int userId = getNextAvailableIdLocked();
1205 userInfo = new UserInfo(userId, name, null, flags);
1206 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1207 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001208 long now = System.currentTimeMillis();
1209 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001210 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001211 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001212 mUsers.put(userId, userInfo);
1213 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001214 if (parent != null) {
1215 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1216 parent.profileGroupId = parent.id;
1217 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001218 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001219 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001220 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001221 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001222 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001223 userInfo.partial = false;
1224 writeUserLocked(userInfo);
1225 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001226 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001227 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001228 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001229 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001230 if (userInfo != null) {
1231 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1232 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1233 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1234 android.Manifest.permission.MANAGE_USERS);
1235 }
1236 } finally {
1237 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001238 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001239 return userInfo;
1240 }
1241
Amith Yamasani95ab7842014-08-11 17:09:26 -07001242 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1243 int count = 0;
1244 for (int i = mUsers.size() - 1; i >= 0; i--) {
1245 UserInfo user = mUsers.valueAt(i);
1246 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1247 if ((user.flags & flags) != 0) {
1248 count++;
1249 }
1250 }
1251 }
1252 return count;
1253 }
1254
Amith Yamasani0b285492011-04-14 17:35:23 -07001255 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001256 * Find the current guest user. If the Guest user is partial,
1257 * then do not include it in the results as it is about to die.
1258 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1259 * the special handling of Guests being removed.
1260 */
1261 private UserInfo findCurrentGuestUserLocked() {
1262 final int size = mUsers.size();
1263 for (int i = 0; i < size; i++) {
1264 final UserInfo user = mUsers.valueAt(i);
1265 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1266 return user;
1267 }
1268 }
1269 return null;
1270 }
1271
1272 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001273 * Mark this guest user for deletion to allow us to create another guest
1274 * and switch to that user before actually removing this guest.
1275 * @param userHandle the userid of the current guest
1276 * @return whether the user could be marked for deletion
1277 */
1278 public boolean markGuestForDeletion(int userHandle) {
1279 checkManageUsersPermission("Only the system can remove users");
1280 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1281 UserManager.DISALLOW_REMOVE_USER, false)) {
1282 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1283 return false;
1284 }
1285
1286 long ident = Binder.clearCallingIdentity();
1287 try {
1288 final UserInfo user;
1289 synchronized (mPackagesLock) {
1290 user = mUsers.get(userHandle);
1291 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1292 return false;
1293 }
1294 if (!user.isGuest()) {
1295 return false;
1296 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001297 // We set this to a guest user that is to be removed. This is a temporary state
1298 // where we are allowed to add new Guest users, even if this one is still not
1299 // removed. This user will still show up in getUserInfo() calls.
1300 // If we don't get around to removing this Guest user, it will be purged on next
1301 // startup.
1302 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001303 // Mark it as disabled, so that it isn't returned any more when
1304 // profiles are queried.
1305 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001306 writeUserLocked(user);
1307 }
1308 } finally {
1309 Binder.restoreCallingIdentity(ident);
1310 }
1311 return true;
1312 }
1313
1314 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001315 * Removes a user and all data directories created for that user. This method should be called
1316 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001317 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001318 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001319 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001320 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001321 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1322 UserManager.DISALLOW_REMOVE_USER, false)) {
1323 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1324 return false;
1325 }
1326
Kenny Guyee58b4f2014-05-23 15:19:53 +01001327 long ident = Binder.clearCallingIdentity();
1328 try {
1329 final UserInfo user;
1330 synchronized (mPackagesLock) {
1331 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001332 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001333 return false;
1334 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001335
1336 // We remember deleted user IDs to prevent them from being
1337 // reused during the current boot; they can still be reused
1338 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001339 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001340
Kenny Guyee58b4f2014-05-23 15:19:53 +01001341 try {
1342 mAppOpsService.removeUser(userHandle);
1343 } catch (RemoteException e) {
1344 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1345 }
1346 // Set this to a partially created user, so that the user will be purged
1347 // on next startup, in case the runtime stops now before stopping and
1348 // removing the user completely.
1349 user.partial = true;
1350 // Mark it as disabled, so that it isn't returned any more when
1351 // profiles are queried.
1352 user.flags |= UserInfo.FLAG_DISABLED;
1353 writeUserLocked(user);
1354 }
1355
1356 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1357 && user.isManagedProfile()) {
1358 // Send broadcast to notify system that the user removed was a
1359 // managed user.
1360 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1361 }
1362
1363 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1364 int res;
1365 try {
1366 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1367 new IStopUserCallback.Stub() {
1368 @Override
1369 public void userStopped(int userId) {
1370 finishRemoveUser(userId);
1371 }
1372 @Override
1373 public void userStopAborted(int userId) {
1374 }
1375 });
1376 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001377 return false;
1378 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001379 return res == ActivityManager.USER_OP_SUCCESS;
1380 } finally {
1381 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001382 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001383 }
1384
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001385 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001386 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001387 // Let other services shutdown any activity and clean up their state before completely
1388 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001389 long ident = Binder.clearCallingIdentity();
1390 try {
1391 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1392 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001393 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1394 android.Manifest.permission.MANAGE_USERS,
1395
1396 new BroadcastReceiver() {
1397 @Override
1398 public void onReceive(Context context, Intent intent) {
1399 if (DBG) {
1400 Slog.i(LOG_TAG,
1401 "USER_REMOVED broadcast sent, cleaning up user data "
1402 + userHandle);
1403 }
1404 new Thread() {
1405 public void run() {
1406 synchronized (mInstallLock) {
1407 synchronized (mPackagesLock) {
1408 removeUserStateLocked(userHandle);
1409 }
1410 }
1411 }
1412 }.start();
1413 }
1414 },
1415
1416 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001417 } finally {
1418 Binder.restoreCallingIdentity(ident);
1419 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001420 }
1421
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001422 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001423 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001424 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001425
1426 // Remove this user from the list
1427 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001428
Amith Yamasani655d0e22013-06-12 14:19:10 -07001429 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001430 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001431 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001432 userFile.delete();
1433 // Update the user list
1434 writeUserListLocked();
1435 updateUserIdsLocked();
1436 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1437 }
1438
Amith Yamasani61f57372012-08-31 12:12:28 -07001439 private void removeDirectoryRecursive(File parent) {
1440 if (parent.isDirectory()) {
1441 String[] files = parent.list();
1442 for (String filename : files) {
1443 File child = new File(parent, filename);
1444 removeDirectoryRecursive(child);
1445 }
1446 }
1447 parent.delete();
1448 }
1449
Kenny Guyf8d3a232014-05-15 16:09:52 +01001450 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001451 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001452 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1453 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001454 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1455 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001456 }
1457
Amith Yamasani2a003292012-08-14 18:25:45 -07001458 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001459 public Bundle getApplicationRestrictions(String packageName) {
1460 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1461 }
1462
1463 @Override
1464 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001465 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001466 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001467 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001468 }
1469 synchronized (mPackagesLock) {
1470 // Read the restrictions from XML
1471 return readApplicationRestrictionsLocked(packageName, userId);
1472 }
1473 }
1474
1475 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001476 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001477 int userId) {
1478 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001479 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001480 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001481 }
1482 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001483 if (restrictions == null || restrictions.isEmpty()) {
1484 cleanAppRestrictionsForPackage(packageName, userId);
1485 } else {
1486 // Write the restrictions to XML
1487 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1488 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001489 }
Robin Lee66e5d962014-04-09 16:44:21 +01001490
Kenny Guyd21b2182014-07-17 16:38:55 +01001491 if (isPackageInstalled(packageName, userId)) {
1492 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1493 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1494 changeIntent.setPackage(packageName);
1495 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1496 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1497 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001498 }
1499
Amith Yamasani655d0e22013-06-12 14:19:10 -07001500 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001501 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001502 checkManageUsersPermission("Only system can modify the restrictions pin");
1503 int userId = UserHandle.getCallingUserId();
1504 synchronized (mPackagesLock) {
1505 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1506 if (pinState == null) {
1507 pinState = new RestrictionsPinState();
1508 }
1509 if (newPin == null) {
1510 pinState.salt = 0;
1511 pinState.pinHash = null;
1512 } else {
1513 try {
1514 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1515 } catch (NoSuchAlgorithmException e) {
1516 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1517 }
1518 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1519 pinState.failedAttempts = 0;
1520 }
1521 mRestrictionsPinStates.put(userId, pinState);
1522 writeUserLocked(mUsers.get(userId));
1523 }
1524 return true;
1525 }
1526
1527 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001528 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001529 checkManageUsersPermission("Only system can verify the restrictions pin");
1530 int userId = UserHandle.getCallingUserId();
1531 synchronized (mPackagesLock) {
1532 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1533 // If there's no pin set, return error code
1534 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1535 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1536 } else if (pin == null) {
1537 // If just checking if user can be prompted, return remaining time
1538 int waitTime = getRemainingTimeForPinAttempt(pinState);
1539 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1540 return waitTime;
1541 } else {
1542 int waitTime = getRemainingTimeForPinAttempt(pinState);
1543 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1544 if (waitTime > 0) {
1545 return waitTime;
1546 }
1547 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1548 pinState.failedAttempts = 0;
1549 writeUserLocked(mUsers.get(userId));
1550 return UserManager.PIN_VERIFICATION_SUCCESS;
1551 } else {
1552 pinState.failedAttempts++;
1553 pinState.lastAttemptTime = System.currentTimeMillis();
1554 writeUserLocked(mUsers.get(userId));
1555 return waitTime;
1556 }
1557 }
1558 }
1559 }
1560
1561 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1562 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1563 BACKOFF_TIMES.length - 1);
1564 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1565 BACKOFF_TIMES[backoffIndex] : 0;
1566 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1567 0);
1568 }
1569
1570 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001571 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001572 int userId = UserHandle.getCallingUserId();
1573 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001574 return hasRestrictionsPinLocked(userId);
1575 }
1576 }
1577
1578 private boolean hasRestrictionsPinLocked(int userId) {
1579 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1580 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1581 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001582 }
1583 return true;
1584 }
1585
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001586 @Override
1587 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001588 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001589 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001590 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001591 }
1592
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001593 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001594 synchronized (mPackagesLock) {
1595 // Remove all user restrictions
1596 setUserRestrictions(new Bundle(), userHandle);
1597 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001598 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001599 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001600 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001601 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001602 if (unhideApps) {
1603 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001604 }
1605 }
1606
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001607 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001608 mHandler.post(new Runnable() {
1609 @Override
1610 public void run() {
1611 List<ApplicationInfo> apps =
1612 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1613 userHandle).getList();
1614 final long ident = Binder.clearCallingIdentity();
1615 try {
1616 for (ApplicationInfo appInfo : apps) {
1617 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001618 && (appInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HIDDEN)
1619 != 0) {
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001620 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001621 userHandle);
1622 }
1623 }
1624 } finally {
1625 Binder.restoreCallingIdentity(ident);
1626 }
1627 }
1628 });
1629 }
1630
Amith Yamasani655d0e22013-06-12 14:19:10 -07001631 /*
1632 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1633 * Not the most secure, but it is at least a second level of protection. First level is that
1634 * the file is in a location only readable by the system process.
1635 * @param password the password.
1636 * @param salt the randomly generated salt
1637 * @return the hash of the pattern in a String.
1638 */
1639 private String passwordToHash(String password, long salt) {
1640 if (password == null) {
1641 return null;
1642 }
1643 String algo = null;
1644 String hashed = salt + password;
1645 try {
1646 byte[] saltedPassword = (password + salt).getBytes();
1647 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1648 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1649 hashed = toHex(sha1) + toHex(md5);
1650 } catch (NoSuchAlgorithmException e) {
1651 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1652 }
1653 return hashed;
1654 }
1655
1656 private static String toHex(byte[] ary) {
1657 final String hex = "0123456789ABCDEF";
1658 String ret = "";
1659 for (int i = 0; i < ary.length; i++) {
1660 ret += hex.charAt((ary[i] >> 4) & 0xf);
1661 ret += hex.charAt(ary[i] & 0xf);
1662 }
1663 return ret;
1664 }
1665
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001666 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001667 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001668 try {
1669 return mContext.getPackageManager().getApplicationInfo(packageName,
1670 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1671 } catch (NameNotFoundException nnfe) {
1672 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001673 } finally {
1674 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 }
1676 }
1677
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001678 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001679 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001680 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001681 final ArrayList<String> values = new ArrayList<String>();
1682
1683 FileInputStream fis = null;
1684 try {
1685 AtomicFile restrictionsFile =
1686 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001687 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001688 fis = restrictionsFile.openRead();
1689 XmlPullParser parser = Xml.newPullParser();
1690 parser.setInput(fis, null);
1691 int type;
1692 while ((type = parser.next()) != XmlPullParser.START_TAG
1693 && type != XmlPullParser.END_DOCUMENT) {
1694 ;
1695 }
1696
1697 if (type != XmlPullParser.START_TAG) {
1698 Slog.e(LOG_TAG, "Unable to read restrictions file "
1699 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001700 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001701 }
1702
1703 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1704 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1705 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001706 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001707 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1708 if (multiple != null) {
Amith Yamasanie0840392014-08-27 10:33:17 -07001709 values.clear();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001710 int count = Integer.parseInt(multiple);
1711 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1712 if (type == XmlPullParser.START_TAG
1713 && parser.getName().equals(TAG_VALUE)) {
1714 values.add(parser.nextText().trim());
1715 count--;
1716 }
1717 }
1718 String [] valueStrings = new String[values.size()];
1719 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001720 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001721 } else {
1722 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001723 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1724 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1725 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1726 restrictions.putInt(key, Integer.parseInt(value));
1727 } else {
1728 restrictions.putString(key, value);
1729 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001730 }
1731 }
1732 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001733 } catch (IOException ioe) {
1734 } catch (XmlPullParserException pe) {
1735 } finally {
1736 if (fis != null) {
1737 try {
1738 fis.close();
1739 } catch (IOException e) {
1740 }
1741 }
1742 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001743 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001744 }
1745
1746 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001747 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001748 FileOutputStream fos = null;
1749 AtomicFile restrictionsFile = new AtomicFile(
1750 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001751 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001752 try {
1753 fos = restrictionsFile.startWrite();
1754 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1755
1756 // XmlSerializer serializer = XmlUtils.serializerInstance();
1757 final XmlSerializer serializer = new FastXmlSerializer();
1758 serializer.setOutput(bos, "utf-8");
1759 serializer.startDocument(null, true);
1760 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1761
1762 serializer.startTag(null, TAG_RESTRICTIONS);
1763
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001764 for (String key : restrictions.keySet()) {
1765 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001766 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001767 serializer.attribute(null, ATTR_KEY, key);
1768
1769 if (value instanceof Boolean) {
1770 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1771 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001772 } else if (value instanceof Integer) {
1773 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1774 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001775 } else if (value == null || value instanceof String) {
1776 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1777 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001778 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001779 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1780 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001781 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001782 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001783 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001784 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001785 serializer.endTag(null, TAG_VALUE);
1786 }
1787 }
1788 serializer.endTag(null, TAG_ENTRY);
1789 }
1790
1791 serializer.endTag(null, TAG_RESTRICTIONS);
1792
1793 serializer.endDocument();
1794 restrictionsFile.finishWrite(fos);
1795 } catch (Exception e) {
1796 restrictionsFile.failWrite(fos);
1797 Slog.e(LOG_TAG, "Error writing application restrictions list");
1798 }
1799 }
1800
1801 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001802 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001803 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001804 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001805 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001806 }
1807 }
1808
1809 @Override
1810 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001811 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001812 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001813 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001814 }
1815 // Not found
1816 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001817 }
1818 }
1819
Amith Yamasani0b285492011-04-14 17:35:23 -07001820 /**
1821 * Caches the list of user ids in an array, adjusting the array size when necessary.
1822 */
Amith Yamasani13593602012-03-22 16:16:17 -07001823 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001824 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001825 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001826 if (!mUsers.valueAt(i).partial) {
1827 num++;
1828 }
1829 }
Amith Yamasani16389312012-10-17 21:20:14 -07001830 final int[] newUsers = new int[num];
1831 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001832 for (int i = 0; i < mUsers.size(); i++) {
1833 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001834 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001835 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001836 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001837 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001838 }
1839
1840 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001841 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001842 * @param userId the user that was just foregrounded
1843 */
1844 public void userForeground(int userId) {
1845 synchronized (mPackagesLock) {
1846 UserInfo user = mUsers.get(userId);
1847 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001848 if (user == null || user.partial) {
1849 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1850 return;
1851 }
1852 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001853 user.lastLoggedInTime = now;
1854 writeUserLocked(user);
1855 }
1856 }
1857 }
1858
1859 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001860 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001861 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1862 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001863 * @return
1864 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001865 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001866 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001867 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001868 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001869 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001870 break;
1871 }
1872 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001873 }
Amith Yamasani195263742012-08-21 15:40:12 -07001874 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001875 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001876 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001877
Amith Yamasanifc95e702013-09-26 13:20:17 -07001878 private String packageToRestrictionsFileName(String packageName) {
1879 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1880 }
1881
1882 private String restrictionsFileNameToPackage(String fileName) {
1883 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1884 (int) (fileName.length() - XML_SUFFIX.length()));
1885 }
1886
Amith Yamasani920ace02012-09-20 22:15:37 -07001887 @Override
1888 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1889 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1890 != PackageManager.PERMISSION_GRANTED) {
1891 pw.println("Permission Denial: can't dump UserManager from from pid="
1892 + Binder.getCallingPid()
1893 + ", uid=" + Binder.getCallingUid()
1894 + " without permission "
1895 + android.Manifest.permission.DUMP);
1896 return;
1897 }
1898
1899 long now = System.currentTimeMillis();
1900 StringBuilder sb = new StringBuilder();
1901 synchronized (mPackagesLock) {
1902 pw.println("Users:");
1903 for (int i = 0; i < mUsers.size(); i++) {
1904 UserInfo user = mUsers.valueAt(i);
1905 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001906 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001907 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001908 if (user.partial) pw.print(" <partial>");
1909 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001910 pw.print(" Created: ");
1911 if (user.creationTime == 0) {
1912 pw.println("<unknown>");
1913 } else {
1914 sb.setLength(0);
1915 TimeUtils.formatDuration(now - user.creationTime, sb);
1916 sb.append(" ago");
1917 pw.println(sb);
1918 }
1919 pw.print(" Last logged in: ");
1920 if (user.lastLoggedInTime == 0) {
1921 pw.println("<unknown>");
1922 } else {
1923 sb.setLength(0);
1924 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1925 sb.append(" ago");
1926 pw.println(sb);
1927 }
1928 }
1929 }
1930 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001931}