blob: 53d8ed0bd0d3fed8d3a3a50a705a2f55e1b7043f [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 Yamasani4b2e9342011-03-31 12:38:53 -070036import android.os.Environment;
37import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080038import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070041import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040042import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070045import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070046import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Slog;
48import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070050import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.util.Xml;
52
Jason Monk62062992014-05-06 09:55:28 -040053import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080054import com.android.internal.util.ArrayUtils;
55import com.android.internal.util.FastXmlSerializer;
56
57import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59import org.xmlpull.v1.XmlSerializer;
60
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import java.io.BufferedOutputStream;
62import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070063import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070065import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileOutputStream;
67import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070068import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070069import java.security.MessageDigest;
70import java.security.NoSuchAlgorithmException;
71import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import java.util.ArrayList;
73import java.util.List;
74
Amith Yamasani258848d2012-08-10 17:06:33 -070075public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070076
Amith Yamasani2a003292012-08-14 18:25:45 -070077 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani16389312012-10-17 21:20:14 -070079 private static final boolean DBG = false;
80
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070083 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070085 private static final String ATTR_CREATION_TIME = "created";
86 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070087 private static final String ATTR_SALT = "salt";
88 private static final String ATTR_PIN_HASH = "pinHash";
89 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
90 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070091 private static final String ATTR_SERIAL_NO = "serialNumber";
92 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070093 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070094 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070095 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010096 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053097 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800100 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800101 private static final String TAG_ENTRY = "entry";
102 private static final String TAG_VALUE = "value";
103 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700107 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
108 private static final String ATTR_TYPE_STRING = "s";
109 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700110 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700111
Amith Yamasani0b285492011-04-14 17:35:23 -0700112 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700114 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700117 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800118
Amith Yamasani634cf312012-10-04 17:34:21 -0700119 private static final int MIN_USER_ID = 10;
120
Amith Yamasani5e486f52013-08-07 11:06:44 -0700121 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700122
Amith Yamasani920ace02012-09-20 22:15:37 -0700123 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
124
Amith Yamasani655d0e22013-06-12 14:19:10 -0700125 // Number of attempts before jumping to the next BACKOFF_TIMES slot
126 private static final int BACKOFF_INC_INTERVAL = 5;
127
Amith Yamasani95ab7842014-08-11 17:09:26 -0700128 // Maximum number of managed profiles permitted is 1. This cannot be increased
129 // without first making sure that the rest of the framework is prepared for it.
130 private static final int MAX_MANAGED_PROFILES = 1;
131
Amith Yamasani655d0e22013-06-12 14:19:10 -0700132 // Amount of time to force the user to wait before entering the PIN again, after failing
133 // BACKOFF_INC_INTERVAL times.
134 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
135
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530136
Dianne Hackborn4428e172012-08-24 17:43:05 -0700137 private final Context mContext;
138 private final PackageManagerService mPm;
139 private final Object mInstallLock;
140 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800142 private final Handler mHandler;
143
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700144 private final File mUsersDir;
145 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700146 private final File mBaseUserPath;
147
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800148 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800149 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530150 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800151
Amith Yamasani655d0e22013-06-12 14:19:10 -0700152 class RestrictionsPinState {
153 long salt;
154 String pinHash;
155 int failedAttempts;
156 long lastAttemptTime;
157 }
158
159 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
160 new SparseArray<RestrictionsPinState>();
161
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800162 /**
163 * Set of user IDs being actively removed. Removed IDs linger in this set
164 * for several seconds to work around a VFS caching issue.
165 */
166 // @GuardedBy("mPackagesLock")
167 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700168
Amith Yamasani0b285492011-04-14 17:35:23 -0700169 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700170 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700171 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700172
Jason Monk62062992014-05-06 09:55:28 -0400173 private IAppOpsService mAppOpsService;
174
Amith Yamasani258848d2012-08-10 17:06:33 -0700175 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700176
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177 public static UserManagerService getInstance() {
178 synchronized (UserManagerService.class) {
179 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700180 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700182
183 /**
184 * Available for testing purposes.
185 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700186 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700187 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 }
189
Dianne Hackborn4428e172012-08-24 17:43:05 -0700190 /**
191 * Called by package manager to create the service. This is closely
192 * associated with the package manager, and the given lock is the
193 * package manager's own lock.
194 */
195 UserManagerService(Context context, PackageManagerService pm,
196 Object installLock, Object packagesLock) {
197 this(context, pm, installLock, packagesLock,
198 Environment.getDataDirectory(),
199 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700200 }
201
Dianne Hackborn4428e172012-08-24 17:43:05 -0700202 /**
203 * Available for testing purposes.
204 */
205 private UserManagerService(Context context, PackageManagerService pm,
206 Object installLock, Object packagesLock,
207 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700208 mContext = context;
209 mPm = pm;
210 mInstallLock = installLock;
211 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800212 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700213 synchronized (mInstallLock) {
214 synchronized (mPackagesLock) {
215 mUsersDir = new File(dataDir, USER_INFO_DIR);
216 mUsersDir.mkdirs();
217 // Make zeroth user directory, for services to migrate their files to that location
218 File userZeroDir = new File(mUsersDir, "0");
219 userZeroDir.mkdirs();
220 mBaseUserPath = baseUserPath;
221 FileUtils.setPermissions(mUsersDir.toString(),
222 FileUtils.S_IRWXU|FileUtils.S_IRWXG
223 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
224 -1, -1);
225 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
226 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700227 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700228 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
229 for (int i = 0; i < mUsers.size(); i++) {
230 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700231 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700232 partials.add(ui);
233 }
234 }
235 for (int i = 0; i < partials.size(); i++) {
236 UserInfo ui = partials.get(i);
237 Slog.w(LOG_TAG, "Removing partially created user #" + i
238 + " (name=" + ui.name + ")");
239 removeUserStateLocked(ui.id);
240 }
241 sInstance = this;
242 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700243 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700244 }
245
246 void systemReady() {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700247 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400248 mAppOpsService = IAppOpsService.Stub.asInterface(
249 ServiceManager.getService(Context.APP_OPS_SERVICE));
250 for (int i = 0; i < mUserIds.length; ++i) {
251 try {
252 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
253 } catch (RemoteException e) {
254 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
255 }
256 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700257 }
258
259 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700260 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700261 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700262 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700263 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
264 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700265 UserInfo ui = mUsers.valueAt(i);
266 if (ui.partial) {
267 continue;
268 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800269 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700270 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700271 }
Amith Yamasani13593602012-03-22 16:16:17 -0700272 }
273 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700274 }
Amith Yamasani13593602012-03-22 16:16:17 -0700275 }
276
Amith Yamasani258848d2012-08-10 17:06:33 -0700277 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100278 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800279 if (userId != UserHandle.getCallingUserId()) {
280 checkManageUsersPermission("getting profiles related to user " + userId);
281 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700282 final long ident = Binder.clearCallingIdentity();
283 try {
284 synchronized (mPackagesLock) {
285 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100286 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700287 } finally {
288 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000289 }
290 }
291
Amith Yamasanibe465322014-04-24 13:45:17 -0700292 /** Assume permissions already checked and caller's identity cleared */
293 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700294 UserInfo user = getUserInfoLocked(userId);
295 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700296 if (user == null) {
297 // Probably a dying user
298 return users;
299 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700300 for (int i = 0; i < mUsers.size(); i++) {
301 UserInfo profile = mUsers.valueAt(i);
302 if (!isProfileOf(user, profile)) {
303 continue;
304 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100305 if (enabledOnly && !profile.isEnabled()) {
306 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700307 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700308 if (mRemovingUserIds.get(profile.id)) {
309 continue;
310 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700311 users.add(profile);
312 }
313 return users;
314 }
315
Jessica Hummelbe81c802014-04-22 15:49:22 +0100316 @Override
317 public UserInfo getProfileParent(int userHandle) {
318 checkManageUsersPermission("get the profile parent");
319 synchronized (mPackagesLock) {
320 UserInfo profile = getUserInfoLocked(userHandle);
321 int parentUserId = profile.profileGroupId;
322 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
323 return null;
324 } else {
325 return getUserInfoLocked(parentUserId);
326 }
327 }
328 }
329
Kenny Guy2a764942014-04-02 13:29:20 +0100330 private boolean isProfileOf(UserInfo user, UserInfo profile) {
331 return user.id == profile.id ||
332 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
333 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000334 }
335
336 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100337 public void setUserEnabled(int userId) {
338 checkManageUsersPermission("enable user");
339 synchronized (mPackagesLock) {
340 UserInfo info = getUserInfoLocked(userId);
341 if (info != null && !info.isEnabled()) {
342 info.flags ^= UserInfo.FLAG_DISABLED;
343 writeUserLocked(info);
344 }
345 }
346 }
347
348 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700349 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700350 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700351 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700352 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700353 }
354 }
355
Amith Yamasani71e6c692013-03-24 17:39:28 -0700356 @Override
357 public boolean isRestricted() {
358 synchronized (mPackagesLock) {
359 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
360 }
361 }
362
Amith Yamasani195263742012-08-21 15:40:12 -0700363 /*
364 * Should be locked on mUsers before calling this.
365 */
366 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700367 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700368 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800369 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700370 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
371 return null;
372 }
373 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700374 }
375
Amith Yamasani13593602012-03-22 16:16:17 -0700376 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700377 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700378 return ArrayUtils.contains(mUserIds, userId);
379 }
380 }
381
Amith Yamasani258848d2012-08-10 17:06:33 -0700382 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700383 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700384 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700385 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700386 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700387 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700388 if (info == null || info.partial) {
389 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
390 return;
391 }
Amith Yamasani13593602012-03-22 16:16:17 -0700392 if (name != null && !name.equals(info.name)) {
393 info.name = name;
394 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700395 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700396 }
397 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700398 if (changed) {
399 sendUserInfoChangedBroadcast(userId);
400 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700401 }
402
Amith Yamasani258848d2012-08-10 17:06:33 -0700403 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700404 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700405 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400406 long ident = Binder.clearCallingIdentity();
407 try {
408 synchronized (mPackagesLock) {
409 UserInfo info = mUsers.get(userId);
410 if (info == null || info.partial) {
411 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
412 return;
413 }
414 writeBitmapLocked(info, bitmap);
415 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700416 }
Jason Monk9a944532014-07-08 09:31:21 -0400417 sendUserInfoChangedBroadcast(userId);
418 } finally {
419 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700420 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700421 }
422
423 private void sendUserInfoChangedBroadcast(int userId) {
424 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
425 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
426 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700427 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700428 }
429
Amith Yamasani258848d2012-08-10 17:06:33 -0700430 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700431 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700432 synchronized (mPackagesLock) {
433 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700434 if (info == null || info.partial) {
435 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
436 return null;
437 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100438 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
439 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
440 || callingGroupId != info.profileGroupId) {
441 checkManageUsersPermission("get the icon of a user who is not related");
442 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700443 if (info.iconPath == null) {
444 return null;
445 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700446 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700447 }
448 }
449
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700450 public void makeInitialized(int userId) {
451 checkManageUsersPermission("makeInitialized");
452 synchronized (mPackagesLock) {
453 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700454 if (info == null || info.partial) {
455 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
456 }
457 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700458 info.flags |= UserInfo.FLAG_INITIALIZED;
459 writeUserLocked(info);
460 }
461 }
462 }
463
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800464 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530465 public Bundle getDefaultGuestRestrictions() {
466 checkManageUsersPermission("getDefaultGuestRestrictions");
467 synchronized (mPackagesLock) {
468 return new Bundle(mGuestRestrictions);
469 }
470 }
471
472 @Override
473 public void setDefaultGuestRestrictions(Bundle restrictions) {
474 checkManageUsersPermission("setDefaultGuestRestrictions");
475 synchronized (mPackagesLock) {
476 mGuestRestrictions.clear();
477 mGuestRestrictions.putAll(restrictions);
478 writeUserListLocked();
479 }
480 }
481
482 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800483 public Bundle getUserRestrictions(int userId) {
484 // checkManageUsersPermission("getUserRestrictions");
485
486 synchronized (mPackagesLock) {
487 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700488 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800489 }
490 }
491
492 @Override
493 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700494 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700495 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800496
497 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700498 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800499 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400500 long token = Binder.clearCallingIdentity();
501 try {
502 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
503 } catch (RemoteException e) {
504 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
505 } finally {
506 Binder.restoreCallingIdentity(token);
507 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800508 writeUserLocked(mUsers.get(userId));
509 }
510 }
511
Amith Yamasani258848d2012-08-10 17:06:33 -0700512 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700513 * Check if we've hit the limit of how many users can be created.
514 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700515 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700516 int aliveUserCount = 0;
517 final int totalUserCount = mUsers.size();
518 // Skip over users being removed
519 for (int i = 0; i < totalUserCount; i++) {
520 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700521 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700522 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700523 aliveUserCount++;
524 }
525 }
526 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700527 }
528
529 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700530 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700531 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700532 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700533 *
534 * @param message used as message if SecurityException is thrown
535 * @throws SecurityException if the caller is not system or root
536 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700537 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700538 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700539 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400540 && ActivityManager.checkComponentPermission(
541 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700542 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
543 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
544 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400545 }
546
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700547 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700548 try {
549 File dir = new File(mUsersDir, Integer.toString(info.id));
550 File file = new File(dir, USER_PHOTO_FILENAME);
551 if (!dir.exists()) {
552 dir.mkdir();
553 FileUtils.setPermissions(
554 dir.getPath(),
555 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
556 -1, -1);
557 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700558 FileOutputStream os;
559 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700560 info.iconPath = file.getAbsolutePath();
561 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700562 try {
563 os.close();
564 } catch (IOException ioe) {
565 // What the ... !
566 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700567 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700568 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700569 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700570 }
571
Amith Yamasani0b285492011-04-14 17:35:23 -0700572 /**
573 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
574 * cache it elsewhere.
575 * @return the array of user ids.
576 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700577 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700578 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700579 return mUserIds;
580 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700581 }
582
Dianne Hackborn4428e172012-08-24 17:43:05 -0700583 int[] getUserIdsLPr() {
584 return mUserIds;
585 }
586
Amith Yamasani13593602012-03-22 16:16:17 -0700587 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700588 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700589 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700590 return;
591 }
592 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700593 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700594 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700595 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700596 XmlPullParser parser = Xml.newPullParser();
597 parser.setInput(fis, null);
598 int type;
599 while ((type = parser.next()) != XmlPullParser.START_TAG
600 && type != XmlPullParser.END_DOCUMENT) {
601 ;
602 }
603
604 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700605 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700606 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700607 return;
608 }
609
Amith Yamasani2a003292012-08-14 18:25:45 -0700610 mNextSerialNumber = -1;
611 if (parser.getName().equals(TAG_USERS)) {
612 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
613 if (lastSerialNumber != null) {
614 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
615 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700616 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
617 if (versionNumber != null) {
618 mUserVersion = Integer.parseInt(versionNumber);
619 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700620 }
621
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700622 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530623 if (type == XmlPullParser.START_TAG) {
624 final String name = parser.getName();
625 if (name.equals(TAG_USER)) {
626 String id = parser.getAttributeValue(null, ATTR_ID);
627 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700628
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530629 if (user != null) {
630 mUsers.put(user.id, user);
631 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
632 mNextSerialNumber = user.id + 1;
633 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700634 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530635 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
636 mGuestRestrictions.clear();
637 readRestrictionsLocked(parser, mGuestRestrictions);
Amith Yamasani258848d2012-08-10 17:06:33 -0700638 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700639 }
640 }
Amith Yamasani13593602012-03-22 16:16:17 -0700641 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700642 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700643 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700644 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700645 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700646 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800647 } finally {
648 if (fis != null) {
649 try {
650 fis.close();
651 } catch (IOException e) {
652 }
653 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700654 }
655 }
656
Amith Yamasani6f34b412012-10-22 18:19:27 -0700657 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800658 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700659 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700660 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700661 int userVersion = mUserVersion;
662 if (userVersion < 1) {
663 // Assign a proper name for the owner, if not initialized correctly before
664 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
665 if ("Primary".equals(user.name)) {
666 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
667 writeUserLocked(user);
668 }
669 userVersion = 1;
670 }
671
Amith Yamasanibc9625052012-11-15 14:39:18 -0800672 if (userVersion < 2) {
673 // Owner should be marked as initialized
674 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
675 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
676 user.flags |= UserInfo.FLAG_INITIALIZED;
677 writeUserLocked(user);
678 }
679 userVersion = 2;
680 }
681
Amith Yamasani350962c2013-08-06 11:18:53 -0700682
Amith Yamasani5e486f52013-08-07 11:06:44 -0700683 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700684 userVersion = 4;
685 }
686
Amith Yamasani6f34b412012-10-22 18:19:27 -0700687 if (userVersion < USER_VERSION) {
688 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
689 + USER_VERSION);
690 } else {
691 mUserVersion = userVersion;
692 writeUserListLocked();
693 }
694 }
695
Amith Yamasani13593602012-03-22 16:16:17 -0700696 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700697 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800698 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700699 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700700 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700701 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700702 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400703 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800704
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500705 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800706 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
707
Amith Yamasani13593602012-03-22 16:16:17 -0700708 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700709
Amith Yamasani13593602012-03-22 16:16:17 -0700710 writeUserListLocked();
711 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700712 }
713
714 /*
715 * Writes the user file in this format:
716 *
717 * <user flags="20039023" id="0">
718 * <name>Primary</name>
719 * </user>
720 */
Amith Yamasani13593602012-03-22 16:16:17 -0700721 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700722 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700723 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700724 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700725 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700726 final BufferedOutputStream bos = new BufferedOutputStream(fos);
727
728 // XmlSerializer serializer = XmlUtils.serializerInstance();
729 final XmlSerializer serializer = new FastXmlSerializer();
730 serializer.setOutput(bos, "utf-8");
731 serializer.startDocument(null, true);
732 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
733
734 serializer.startTag(null, TAG_USER);
735 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700736 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700737 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700738 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
739 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
740 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700741 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
742 if (pinState != null) {
743 if (pinState.salt != 0) {
744 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
745 }
746 if (pinState.pinHash != null) {
747 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
748 }
749 if (pinState.failedAttempts != 0) {
750 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
751 Integer.toString(pinState.failedAttempts));
752 serializer.attribute(null, ATTR_LAST_RETRY_MS,
753 Long.toString(pinState.lastAttemptTime));
754 }
755 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700756 if (userInfo.iconPath != null) {
757 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
758 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700759 if (userInfo.partial) {
760 serializer.attribute(null, ATTR_PARTIAL, "true");
761 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700762 if (userInfo.guestToRemove) {
763 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
764 }
Kenny Guy2a764942014-04-02 13:29:20 +0100765 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
766 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
767 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000768 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700769
770 serializer.startTag(null, TAG_NAME);
771 serializer.text(userInfo.name);
772 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800773 Bundle restrictions = mUserRestrictions.get(userInfo.id);
774 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530775 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800776 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700777 serializer.endTag(null, TAG_USER);
778
779 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700780 userFile.finishWrite(fos);
781 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700782 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700783 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700784 }
785 }
786
787 /*
788 * Writes the user list file in this format:
789 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700790 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700791 * <user id="0"></user>
792 * <user id="2"></user>
793 * </users>
794 */
Amith Yamasani13593602012-03-22 16:16:17 -0700795 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700796 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700797 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700798 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700799 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700800 final BufferedOutputStream bos = new BufferedOutputStream(fos);
801
802 // XmlSerializer serializer = XmlUtils.serializerInstance();
803 final XmlSerializer serializer = new FastXmlSerializer();
804 serializer.setOutput(bos, "utf-8");
805 serializer.startDocument(null, true);
806 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
807
808 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700809 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700810 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700811
Adam Lesinskieddeb492014-09-08 17:50:03 -0700812 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530813 writeRestrictionsLocked(serializer, mGuestRestrictions);
814 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700815 for (int i = 0; i < mUsers.size(); i++) {
816 UserInfo user = mUsers.valueAt(i);
817 serializer.startTag(null, TAG_USER);
818 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
819 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700820 }
821
822 serializer.endTag(null, TAG_USERS);
823
824 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700825 userListFile.finishWrite(fos);
826 } catch (Exception e) {
827 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700828 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700829 }
830 }
831
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530832 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
833 throws IOException {
834 serializer.startTag(null, TAG_RESTRICTIONS);
835 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
836 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
837 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
838 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
839 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
840 writeBoolean(serializer, restrictions,
841 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
842 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
843 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
844 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
845 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
846 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
847 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
848 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
849 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
850 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
851 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
852 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
853 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
854 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
855 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
856 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
857 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700858 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
859 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400860 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530861 serializer.endTag(null, TAG_RESTRICTIONS);
862 }
863
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800864 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700865 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700866 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700867 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700868 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700869 long creationTime = 0L;
870 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700871 long salt = 0L;
872 String pinHash = null;
873 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100874 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700875 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700876 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700877 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800878 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700879
880 FileInputStream fis = null;
881 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700882 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700883 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700884 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700885 XmlPullParser parser = Xml.newPullParser();
886 parser.setInput(fis, null);
887 int type;
888 while ((type = parser.next()) != XmlPullParser.START_TAG
889 && type != XmlPullParser.END_DOCUMENT) {
890 ;
891 }
892
893 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700894 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700895 return null;
896 }
897
898 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700899 int storedId = readIntAttribute(parser, ATTR_ID, -1);
900 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700901 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700902 return null;
903 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700904 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
905 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700906 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700907 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
908 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700909 salt = readLongAttribute(parser, ATTR_SALT, 0L);
910 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
911 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
912 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100913 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
914 UserInfo.NO_PROFILE_GROUP_ID);
915 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
916 // This attribute was added and renamed during development of L.
917 // TODO Remove upgrade path by 1st May 2014
918 profileGroupId = readIntAttribute(parser, "relatedGroupId",
919 UserInfo.NO_PROFILE_GROUP_ID);
920 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700921 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
922 if ("true".equals(valueString)) {
923 partial = true;
924 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700925 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
926 if ("true".equals(valueString)) {
927 guestToRemove = true;
928 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700929
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800930 int outerDepth = parser.getDepth();
931 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
932 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
933 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
934 continue;
935 }
936 String tag = parser.getName();
937 if (TAG_NAME.equals(tag)) {
938 type = parser.next();
939 if (type == XmlPullParser.TEXT) {
940 name = parser.getText();
941 }
942 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530943 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700944 }
945 }
946 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700948 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700949 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700950 userInfo.creationTime = creationTime;
951 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700952 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700953 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +0100954 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800955 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700956 if (salt != 0L) {
957 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
958 if (pinState == null) {
959 pinState = new RestrictionsPinState();
960 mRestrictionsPinStates.put(id, pinState);
961 }
962 pinState.salt = salt;
963 pinState.pinHash = pinHash;
964 pinState.failedAttempts = failedAttempts;
965 pinState.lastAttemptTime = lastAttemptTime;
966 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700967 return userInfo;
968
969 } catch (IOException ioe) {
970 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800971 } finally {
972 if (fis != null) {
973 try {
974 fis.close();
975 } catch (IOException e) {
976 }
977 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700978 }
979 return null;
980 }
981
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530982 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
983 throws IOException {
984 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
985 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
986 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
987 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
988 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
989 readBoolean(parser, restrictions,
990 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
991 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
992 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
993 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
994 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
995 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
996 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
997 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
998 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
999 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1000 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1001 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1002 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1003 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1004 readBoolean(parser, restrictions,
1005 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1006 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1007 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001008 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1009 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001010 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301011 }
1012
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001013 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1014 String restrictionKey) {
1015 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001016 if (value != null) {
1017 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1018 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001019 }
1020
1021 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1022 throws IOException {
1023 if (restrictions.containsKey(restrictionKey)) {
1024 xml.attribute(null, restrictionKey,
1025 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1026 }
1027 }
1028
Amith Yamasani920ace02012-09-20 22:15:37 -07001029 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1030 String valueString = parser.getAttributeValue(null, attr);
1031 if (valueString == null) return defaultValue;
1032 try {
1033 return Integer.parseInt(valueString);
1034 } catch (NumberFormatException nfe) {
1035 return defaultValue;
1036 }
1037 }
1038
1039 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1040 String valueString = parser.getAttributeValue(null, attr);
1041 if (valueString == null) return defaultValue;
1042 try {
1043 return Long.parseLong(valueString);
1044 } catch (NumberFormatException nfe) {
1045 return defaultValue;
1046 }
1047 }
1048
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001049 private boolean isPackageInstalled(String pkg, int userId) {
1050 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1051 PackageManager.GET_UNINSTALLED_PACKAGES,
1052 userId);
1053 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1054 return false;
1055 }
1056 return true;
1057 }
1058
Amith Yamasanib82add22013-07-09 11:24:44 -07001059 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001060 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001061 * Does not do any permissions checking.
1062 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001063 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001064 synchronized (mPackagesLock) {
1065 File dir = Environment.getUserSystemDirectory(userId);
1066 String[] files = dir.list();
1067 if (files == null) return;
1068 for (String fileName : files) {
1069 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1070 File resFile = new File(dir, fileName);
1071 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001072 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001073 }
1074 }
1075 }
1076 }
1077 }
1078
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001079 /**
1080 * Removes the app restrictions file for a specific package and user id, if it exists.
1081 */
1082 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1083 synchronized (mPackagesLock) {
1084 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001085 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001086 if (resFile.exists()) {
1087 resFile.delete();
1088 }
1089 }
1090 }
1091
Kenny Guya52dc3e2014-02-11 15:33:14 +00001092 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001093 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001094 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001095 if (userId != UserHandle.USER_OWNER) {
1096 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001097 return null;
1098 }
Kenny Guy2a764942014-04-02 13:29:20 +01001099 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001100 }
1101
Amith Yamasani258848d2012-08-10 17:06:33 -07001102 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001103 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001104 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001105 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001106 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001107
Jessica Hummelbe81c802014-04-22 15:49:22 +01001108 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001109 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1110 UserManager.DISALLOW_ADD_USER, false)) {
1111 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1112 return null;
1113 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001114 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001115 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001116 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001117 try {
1118 synchronized (mInstallLock) {
1119 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001120 UserInfo parent = null;
1121 if (parentId != UserHandle.USER_NULL) {
1122 parent = getUserInfoLocked(parentId);
1123 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001124 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001125 // If we're not adding a guest user and the limit has been reached,
1126 // cannot add a user.
1127 if (!isGuest && isUserLimitReachedLocked()) {
1128 return null;
1129 }
1130 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001131 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001132 return null;
1133 }
1134 // Limit number of managed profiles that can be created
1135 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1136 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1137 >= MAX_MANAGED_PROFILES) {
1138 return null;
1139 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001140 int userId = getNextAvailableIdLocked();
1141 userInfo = new UserInfo(userId, name, null, flags);
1142 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1143 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001144 long now = System.currentTimeMillis();
1145 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001146 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001147 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001148 mUsers.put(userId, userInfo);
1149 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001150 if (parent != null) {
1151 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1152 parent.profileGroupId = parent.id;
1153 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001154 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001155 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001156 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001157 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001158 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001159 userInfo.partial = false;
1160 writeUserLocked(userInfo);
1161 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001162 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001163 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001164 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001165 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001166 if (userInfo != null) {
1167 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1168 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1169 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1170 android.Manifest.permission.MANAGE_USERS);
1171 }
1172 } finally {
1173 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001174 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001175 return userInfo;
1176 }
1177
Amith Yamasani95ab7842014-08-11 17:09:26 -07001178 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1179 int count = 0;
1180 for (int i = mUsers.size() - 1; i >= 0; i--) {
1181 UserInfo user = mUsers.valueAt(i);
1182 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1183 if ((user.flags & flags) != 0) {
1184 count++;
1185 }
1186 }
1187 }
1188 return count;
1189 }
1190
Amith Yamasani0b285492011-04-14 17:35:23 -07001191 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001192 * Find the current guest user. If the Guest user is partial,
1193 * then do not include it in the results as it is about to die.
1194 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1195 * the special handling of Guests being removed.
1196 */
1197 private UserInfo findCurrentGuestUserLocked() {
1198 final int size = mUsers.size();
1199 for (int i = 0; i < size; i++) {
1200 final UserInfo user = mUsers.valueAt(i);
1201 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1202 return user;
1203 }
1204 }
1205 return null;
1206 }
1207
1208 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001209 * Mark this guest user for deletion to allow us to create another guest
1210 * and switch to that user before actually removing this guest.
1211 * @param userHandle the userid of the current guest
1212 * @return whether the user could be marked for deletion
1213 */
1214 public boolean markGuestForDeletion(int userHandle) {
1215 checkManageUsersPermission("Only the system can remove users");
1216 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1217 UserManager.DISALLOW_REMOVE_USER, false)) {
1218 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1219 return false;
1220 }
1221
1222 long ident = Binder.clearCallingIdentity();
1223 try {
1224 final UserInfo user;
1225 synchronized (mPackagesLock) {
1226 user = mUsers.get(userHandle);
1227 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1228 return false;
1229 }
1230 if (!user.isGuest()) {
1231 return false;
1232 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001233 // We set this to a guest user that is to be removed. This is a temporary state
1234 // where we are allowed to add new Guest users, even if this one is still not
1235 // removed. This user will still show up in getUserInfo() calls.
1236 // If we don't get around to removing this Guest user, it will be purged on next
1237 // startup.
1238 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001239 // Mark it as disabled, so that it isn't returned any more when
1240 // profiles are queried.
1241 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001242 writeUserLocked(user);
1243 }
1244 } finally {
1245 Binder.restoreCallingIdentity(ident);
1246 }
1247 return true;
1248 }
1249
1250 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001251 * Removes a user and all data directories created for that user. This method should be called
1252 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001253 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001254 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001255 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001256 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001257 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1258 UserManager.DISALLOW_REMOVE_USER, false)) {
1259 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1260 return false;
1261 }
1262
Kenny Guyee58b4f2014-05-23 15:19:53 +01001263 long ident = Binder.clearCallingIdentity();
1264 try {
1265 final UserInfo user;
1266 synchronized (mPackagesLock) {
1267 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001268 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001269 return false;
1270 }
1271 mRemovingUserIds.put(userHandle, true);
1272 try {
1273 mAppOpsService.removeUser(userHandle);
1274 } catch (RemoteException e) {
1275 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1276 }
1277 // Set this to a partially created user, so that the user will be purged
1278 // on next startup, in case the runtime stops now before stopping and
1279 // removing the user completely.
1280 user.partial = true;
1281 // Mark it as disabled, so that it isn't returned any more when
1282 // profiles are queried.
1283 user.flags |= UserInfo.FLAG_DISABLED;
1284 writeUserLocked(user);
1285 }
1286
1287 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1288 && user.isManagedProfile()) {
1289 // Send broadcast to notify system that the user removed was a
1290 // managed user.
1291 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1292 }
1293
1294 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1295 int res;
1296 try {
1297 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1298 new IStopUserCallback.Stub() {
1299 @Override
1300 public void userStopped(int userId) {
1301 finishRemoveUser(userId);
1302 }
1303 @Override
1304 public void userStopAborted(int userId) {
1305 }
1306 });
1307 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001308 return false;
1309 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001310 return res == ActivityManager.USER_OP_SUCCESS;
1311 } finally {
1312 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001313 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001314 }
1315
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001316 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001317 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001318 // Let other services shutdown any activity and clean up their state before completely
1319 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001320 long ident = Binder.clearCallingIdentity();
1321 try {
1322 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1323 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001324 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1325 android.Manifest.permission.MANAGE_USERS,
1326
1327 new BroadcastReceiver() {
1328 @Override
1329 public void onReceive(Context context, Intent intent) {
1330 if (DBG) {
1331 Slog.i(LOG_TAG,
1332 "USER_REMOVED broadcast sent, cleaning up user data "
1333 + userHandle);
1334 }
1335 new Thread() {
1336 public void run() {
1337 synchronized (mInstallLock) {
1338 synchronized (mPackagesLock) {
1339 removeUserStateLocked(userHandle);
1340 }
1341 }
1342 }
1343 }.start();
1344 }
1345 },
1346
1347 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001348 } finally {
1349 Binder.restoreCallingIdentity(ident);
1350 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001351 }
1352
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001353 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001354 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001355 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001356
1357 // Remove this user from the list
1358 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001359
1360 // Have user ID linger for several seconds to let external storage VFS
1361 // cache entries expire. This must be greater than the 'entry_valid'
1362 // timeout used by the FUSE daemon.
1363 mHandler.postDelayed(new Runnable() {
1364 @Override
1365 public void run() {
1366 synchronized (mPackagesLock) {
1367 mRemovingUserIds.delete(userHandle);
1368 }
1369 }
1370 }, MINUTE_IN_MILLIS);
1371
Amith Yamasani655d0e22013-06-12 14:19:10 -07001372 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001373 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001374 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001375 userFile.delete();
1376 // Update the user list
1377 writeUserListLocked();
1378 updateUserIdsLocked();
1379 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1380 }
1381
Amith Yamasani61f57372012-08-31 12:12:28 -07001382 private void removeDirectoryRecursive(File parent) {
1383 if (parent.isDirectory()) {
1384 String[] files = parent.list();
1385 for (String filename : files) {
1386 File child = new File(parent, filename);
1387 removeDirectoryRecursive(child);
1388 }
1389 }
1390 parent.delete();
1391 }
1392
Kenny Guyf8d3a232014-05-15 16:09:52 +01001393 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001394 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001395 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1396 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001397 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1398 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001399 }
1400
Amith Yamasani2a003292012-08-14 18:25:45 -07001401 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001402 public Bundle getApplicationRestrictions(String packageName) {
1403 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1404 }
1405
1406 @Override
1407 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001408 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001409 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001410 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001411 }
1412 synchronized (mPackagesLock) {
1413 // Read the restrictions from XML
1414 return readApplicationRestrictionsLocked(packageName, userId);
1415 }
1416 }
1417
1418 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001419 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001420 int userId) {
1421 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001422 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001423 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001424 }
1425 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001426 if (restrictions == null || restrictions.isEmpty()) {
1427 cleanAppRestrictionsForPackage(packageName, userId);
1428 } else {
1429 // Write the restrictions to XML
1430 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1431 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001432 }
Robin Lee66e5d962014-04-09 16:44:21 +01001433
Kenny Guyd21b2182014-07-17 16:38:55 +01001434 if (isPackageInstalled(packageName, userId)) {
1435 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1436 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1437 changeIntent.setPackage(packageName);
1438 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1439 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1440 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001441 }
1442
Amith Yamasani655d0e22013-06-12 14:19:10 -07001443 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001444 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001445 checkManageUsersPermission("Only system can modify the restrictions pin");
1446 int userId = UserHandle.getCallingUserId();
1447 synchronized (mPackagesLock) {
1448 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1449 if (pinState == null) {
1450 pinState = new RestrictionsPinState();
1451 }
1452 if (newPin == null) {
1453 pinState.salt = 0;
1454 pinState.pinHash = null;
1455 } else {
1456 try {
1457 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1458 } catch (NoSuchAlgorithmException e) {
1459 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1460 }
1461 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1462 pinState.failedAttempts = 0;
1463 }
1464 mRestrictionsPinStates.put(userId, pinState);
1465 writeUserLocked(mUsers.get(userId));
1466 }
1467 return true;
1468 }
1469
1470 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001471 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001472 checkManageUsersPermission("Only system can verify the restrictions pin");
1473 int userId = UserHandle.getCallingUserId();
1474 synchronized (mPackagesLock) {
1475 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1476 // If there's no pin set, return error code
1477 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1478 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1479 } else if (pin == null) {
1480 // If just checking if user can be prompted, return remaining time
1481 int waitTime = getRemainingTimeForPinAttempt(pinState);
1482 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1483 return waitTime;
1484 } else {
1485 int waitTime = getRemainingTimeForPinAttempt(pinState);
1486 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1487 if (waitTime > 0) {
1488 return waitTime;
1489 }
1490 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1491 pinState.failedAttempts = 0;
1492 writeUserLocked(mUsers.get(userId));
1493 return UserManager.PIN_VERIFICATION_SUCCESS;
1494 } else {
1495 pinState.failedAttempts++;
1496 pinState.lastAttemptTime = System.currentTimeMillis();
1497 writeUserLocked(mUsers.get(userId));
1498 return waitTime;
1499 }
1500 }
1501 }
1502 }
1503
1504 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1505 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1506 BACKOFF_TIMES.length - 1);
1507 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1508 BACKOFF_TIMES[backoffIndex] : 0;
1509 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1510 0);
1511 }
1512
1513 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001514 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001515 int userId = UserHandle.getCallingUserId();
1516 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001517 return hasRestrictionsPinLocked(userId);
1518 }
1519 }
1520
1521 private boolean hasRestrictionsPinLocked(int userId) {
1522 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1523 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1524 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001525 }
1526 return true;
1527 }
1528
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001529 @Override
1530 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001531 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001532 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001533 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001534 }
1535
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001536 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001537 synchronized (mPackagesLock) {
1538 // Remove all user restrictions
1539 setUserRestrictions(new Bundle(), userHandle);
1540 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001541 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001542 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001543 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001544 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001545 if (unhideApps) {
1546 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001547 }
1548 }
1549
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001550 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001551 mHandler.post(new Runnable() {
1552 @Override
1553 public void run() {
1554 List<ApplicationInfo> apps =
1555 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1556 userHandle).getList();
1557 final long ident = Binder.clearCallingIdentity();
1558 try {
1559 for (ApplicationInfo appInfo : apps) {
1560 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001561 && (appInfo.flags & ApplicationInfo.FLAG_HIDDEN) != 0) {
1562 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001563 userHandle);
1564 }
1565 }
1566 } finally {
1567 Binder.restoreCallingIdentity(ident);
1568 }
1569 }
1570 });
1571 }
1572
Amith Yamasani655d0e22013-06-12 14:19:10 -07001573 /*
1574 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1575 * Not the most secure, but it is at least a second level of protection. First level is that
1576 * the file is in a location only readable by the system process.
1577 * @param password the password.
1578 * @param salt the randomly generated salt
1579 * @return the hash of the pattern in a String.
1580 */
1581 private String passwordToHash(String password, long salt) {
1582 if (password == null) {
1583 return null;
1584 }
1585 String algo = null;
1586 String hashed = salt + password;
1587 try {
1588 byte[] saltedPassword = (password + salt).getBytes();
1589 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1590 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1591 hashed = toHex(sha1) + toHex(md5);
1592 } catch (NoSuchAlgorithmException e) {
1593 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1594 }
1595 return hashed;
1596 }
1597
1598 private static String toHex(byte[] ary) {
1599 final String hex = "0123456789ABCDEF";
1600 String ret = "";
1601 for (int i = 0; i < ary.length; i++) {
1602 ret += hex.charAt((ary[i] >> 4) & 0xf);
1603 ret += hex.charAt(ary[i] & 0xf);
1604 }
1605 return ret;
1606 }
1607
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001608 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001609 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001610 try {
1611 return mContext.getPackageManager().getApplicationInfo(packageName,
1612 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1613 } catch (NameNotFoundException nnfe) {
1614 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001615 } finally {
1616 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001617 }
1618 }
1619
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001620 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001621 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001622 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001623 final ArrayList<String> values = new ArrayList<String>();
1624
1625 FileInputStream fis = null;
1626 try {
1627 AtomicFile restrictionsFile =
1628 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001629 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001630 fis = restrictionsFile.openRead();
1631 XmlPullParser parser = Xml.newPullParser();
1632 parser.setInput(fis, null);
1633 int type;
1634 while ((type = parser.next()) != XmlPullParser.START_TAG
1635 && type != XmlPullParser.END_DOCUMENT) {
1636 ;
1637 }
1638
1639 if (type != XmlPullParser.START_TAG) {
1640 Slog.e(LOG_TAG, "Unable to read restrictions file "
1641 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001642 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001643 }
1644
1645 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1646 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1647 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001648 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001649 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1650 if (multiple != null) {
Amith Yamasanie0840392014-08-27 10:33:17 -07001651 values.clear();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001652 int count = Integer.parseInt(multiple);
1653 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1654 if (type == XmlPullParser.START_TAG
1655 && parser.getName().equals(TAG_VALUE)) {
1656 values.add(parser.nextText().trim());
1657 count--;
1658 }
1659 }
1660 String [] valueStrings = new String[values.size()];
1661 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001662 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001663 } else {
1664 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001665 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1666 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1667 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1668 restrictions.putInt(key, Integer.parseInt(value));
1669 } else {
1670 restrictions.putString(key, value);
1671 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001672 }
1673 }
1674 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001675 } catch (IOException ioe) {
1676 } catch (XmlPullParserException pe) {
1677 } finally {
1678 if (fis != null) {
1679 try {
1680 fis.close();
1681 } catch (IOException e) {
1682 }
1683 }
1684 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001685 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001686 }
1687
1688 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001689 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001690 FileOutputStream fos = null;
1691 AtomicFile restrictionsFile = new AtomicFile(
1692 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001693 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001694 try {
1695 fos = restrictionsFile.startWrite();
1696 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1697
1698 // XmlSerializer serializer = XmlUtils.serializerInstance();
1699 final XmlSerializer serializer = new FastXmlSerializer();
1700 serializer.setOutput(bos, "utf-8");
1701 serializer.startDocument(null, true);
1702 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1703
1704 serializer.startTag(null, TAG_RESTRICTIONS);
1705
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001706 for (String key : restrictions.keySet()) {
1707 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001708 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001709 serializer.attribute(null, ATTR_KEY, key);
1710
1711 if (value instanceof Boolean) {
1712 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1713 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001714 } else if (value instanceof Integer) {
1715 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1716 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001717 } else if (value == null || value instanceof String) {
1718 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1719 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001720 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001721 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1722 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001723 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001724 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001725 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001726 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001727 serializer.endTag(null, TAG_VALUE);
1728 }
1729 }
1730 serializer.endTag(null, TAG_ENTRY);
1731 }
1732
1733 serializer.endTag(null, TAG_RESTRICTIONS);
1734
1735 serializer.endDocument();
1736 restrictionsFile.finishWrite(fos);
1737 } catch (Exception e) {
1738 restrictionsFile.failWrite(fos);
1739 Slog.e(LOG_TAG, "Error writing application restrictions list");
1740 }
1741 }
1742
1743 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001744 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001745 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001746 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001747 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001748 }
1749 }
1750
1751 @Override
1752 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001753 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001754 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001755 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001756 }
1757 // Not found
1758 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001759 }
1760 }
1761
Amith Yamasani0b285492011-04-14 17:35:23 -07001762 /**
1763 * Caches the list of user ids in an array, adjusting the array size when necessary.
1764 */
Amith Yamasani13593602012-03-22 16:16:17 -07001765 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001766 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001767 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001768 if (!mUsers.valueAt(i).partial) {
1769 num++;
1770 }
1771 }
Amith Yamasani16389312012-10-17 21:20:14 -07001772 final int[] newUsers = new int[num];
1773 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001774 for (int i = 0; i < mUsers.size(); i++) {
1775 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001776 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001777 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001778 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001779 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001780 }
1781
1782 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001783 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001784 * @param userId the user that was just foregrounded
1785 */
1786 public void userForeground(int userId) {
1787 synchronized (mPackagesLock) {
1788 UserInfo user = mUsers.get(userId);
1789 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001790 if (user == null || user.partial) {
1791 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1792 return;
1793 }
1794 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001795 user.lastLoggedInTime = now;
1796 writeUserLocked(user);
1797 }
1798 }
1799 }
1800
1801 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001802 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001803 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1804 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001805 * @return
1806 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001807 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001808 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001809 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001810 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001811 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001812 break;
1813 }
1814 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001815 }
Amith Yamasani195263742012-08-21 15:40:12 -07001816 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001817 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001818 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001819
Amith Yamasanifc95e702013-09-26 13:20:17 -07001820 private String packageToRestrictionsFileName(String packageName) {
1821 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1822 }
1823
1824 private String restrictionsFileNameToPackage(String fileName) {
1825 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1826 (int) (fileName.length() - XML_SUFFIX.length()));
1827 }
1828
Amith Yamasani920ace02012-09-20 22:15:37 -07001829 @Override
1830 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1831 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1832 != PackageManager.PERMISSION_GRANTED) {
1833 pw.println("Permission Denial: can't dump UserManager from from pid="
1834 + Binder.getCallingPid()
1835 + ", uid=" + Binder.getCallingUid()
1836 + " without permission "
1837 + android.Manifest.permission.DUMP);
1838 return;
1839 }
1840
1841 long now = System.currentTimeMillis();
1842 StringBuilder sb = new StringBuilder();
1843 synchronized (mPackagesLock) {
1844 pw.println("Users:");
1845 for (int i = 0; i < mUsers.size(); i++) {
1846 UserInfo user = mUsers.valueAt(i);
1847 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001848 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001849 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001850 if (user.partial) pw.print(" <partial>");
1851 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001852 pw.print(" Created: ");
1853 if (user.creationTime == 0) {
1854 pw.println("<unknown>");
1855 } else {
1856 sb.setLength(0);
1857 TimeUtils.formatDuration(now - user.creationTime, sb);
1858 sb.append(" ago");
1859 pw.println(sb);
1860 }
1861 pw.print(" Last logged in: ");
1862 if (user.lastLoggedInTime == 0) {
1863 pw.println("<unknown>");
1864 } else {
1865 sb.setLength(0);
1866 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1867 sb.append(" ago");
1868 pw.println(sb);
1869 }
1870 }
1871 }
1872 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001873}