blob: ad879933e81727f755bce1b26d346fe006a9298b [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;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070024import android.app.ActivityThread;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040043import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070044import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070045import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070046import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070047import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.util.Slog;
49import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070051import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Xml;
53
Jason Monk62062992014-05-06 09:55:28 -040054import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import com.android.internal.util.ArrayUtils;
56import com.android.internal.util.FastXmlSerializer;
57
58import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60import org.xmlpull.v1.XmlSerializer;
61
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import java.io.BufferedOutputStream;
63import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070064import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070066import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import java.io.FileOutputStream;
68import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070069import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070070import java.security.MessageDigest;
71import java.security.NoSuchAlgorithmException;
72import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.util.ArrayList;
74import java.util.List;
75
Amith Yamasani258848d2012-08-10 17:06:33 -070076public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077
Amith Yamasani2a003292012-08-14 18:25:45 -070078 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070079
Amith Yamasani16389312012-10-17 21:20:14 -070080 private static final boolean DBG = false;
81
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070086 private static final String ATTR_CREATION_TIME = "created";
87 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070088 private static final String ATTR_SALT = "salt";
89 private static final String ATTR_PIN_HASH = "pinHash";
90 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
91 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070092 private static final String ATTR_SERIAL_NO = "serialNumber";
93 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070094 private static final String ATTR_PARTIAL = "partial";
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);
231 if (ui.partial && i != 0) {
232 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());
296 for (int i = 0; i < mUsers.size(); i++) {
297 UserInfo profile = mUsers.valueAt(i);
298 if (!isProfileOf(user, profile)) {
299 continue;
300 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100301 if (enabledOnly && !profile.isEnabled()) {
302 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700303 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700304 if (mRemovingUserIds.get(profile.id)) {
305 continue;
306 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700307 users.add(profile);
308 }
309 return users;
310 }
311
Jessica Hummelbe81c802014-04-22 15:49:22 +0100312 @Override
313 public UserInfo getProfileParent(int userHandle) {
314 checkManageUsersPermission("get the profile parent");
315 synchronized (mPackagesLock) {
316 UserInfo profile = getUserInfoLocked(userHandle);
317 int parentUserId = profile.profileGroupId;
318 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
319 return null;
320 } else {
321 return getUserInfoLocked(parentUserId);
322 }
323 }
324 }
325
Kenny Guy2a764942014-04-02 13:29:20 +0100326 private boolean isProfileOf(UserInfo user, UserInfo profile) {
327 return user.id == profile.id ||
328 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
329 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000330 }
331
332 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100333 public void setUserEnabled(int userId) {
334 checkManageUsersPermission("enable user");
335 synchronized (mPackagesLock) {
336 UserInfo info = getUserInfoLocked(userId);
337 if (info != null && !info.isEnabled()) {
338 info.flags ^= UserInfo.FLAG_DISABLED;
339 writeUserLocked(info);
340 }
341 }
342 }
343
344 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700345 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700346 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700347 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700348 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700349 }
350 }
351
Amith Yamasani71e6c692013-03-24 17:39:28 -0700352 @Override
353 public boolean isRestricted() {
354 synchronized (mPackagesLock) {
355 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
356 }
357 }
358
Amith Yamasani195263742012-08-21 15:40:12 -0700359 /*
360 * Should be locked on mUsers before calling this.
361 */
362 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700363 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700364 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800365 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700366 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
367 return null;
368 }
369 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700370 }
371
Amith Yamasani13593602012-03-22 16:16:17 -0700372 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700373 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700374 return ArrayUtils.contains(mUserIds, userId);
375 }
376 }
377
Amith Yamasani258848d2012-08-10 17:06:33 -0700378 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700379 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700380 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700381 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700382 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700383 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700384 if (info == null || info.partial) {
385 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
386 return;
387 }
Amith Yamasani13593602012-03-22 16:16:17 -0700388 if (name != null && !name.equals(info.name)) {
389 info.name = name;
390 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700391 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700392 }
393 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700394 if (changed) {
395 sendUserInfoChangedBroadcast(userId);
396 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700397 }
398
Amith Yamasani258848d2012-08-10 17:06:33 -0700399 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700400 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700401 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400402 long ident = Binder.clearCallingIdentity();
403 try {
404 synchronized (mPackagesLock) {
405 UserInfo info = mUsers.get(userId);
406 if (info == null || info.partial) {
407 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
408 return;
409 }
410 writeBitmapLocked(info, bitmap);
411 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700412 }
Jason Monk9a944532014-07-08 09:31:21 -0400413 sendUserInfoChangedBroadcast(userId);
414 } finally {
415 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700416 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700417 }
418
419 private void sendUserInfoChangedBroadcast(int userId) {
420 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
421 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
422 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700423 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700424 }
425
Amith Yamasani258848d2012-08-10 17:06:33 -0700426 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700427 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700428 synchronized (mPackagesLock) {
429 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700430 if (info == null || info.partial) {
431 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
432 return null;
433 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100434 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
435 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
436 || callingGroupId != info.profileGroupId) {
437 checkManageUsersPermission("get the icon of a user who is not related");
438 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700439 if (info.iconPath == null) {
440 return null;
441 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700442 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700443 }
444 }
445
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700446 public void makeInitialized(int userId) {
447 checkManageUsersPermission("makeInitialized");
448 synchronized (mPackagesLock) {
449 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700450 if (info == null || info.partial) {
451 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
452 }
453 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700454 info.flags |= UserInfo.FLAG_INITIALIZED;
455 writeUserLocked(info);
456 }
457 }
458 }
459
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800460 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530461 public Bundle getDefaultGuestRestrictions() {
462 checkManageUsersPermission("getDefaultGuestRestrictions");
463 synchronized (mPackagesLock) {
464 return new Bundle(mGuestRestrictions);
465 }
466 }
467
468 @Override
469 public void setDefaultGuestRestrictions(Bundle restrictions) {
470 checkManageUsersPermission("setDefaultGuestRestrictions");
471 synchronized (mPackagesLock) {
472 mGuestRestrictions.clear();
473 mGuestRestrictions.putAll(restrictions);
474 writeUserListLocked();
475 }
476 }
477
478 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800479 public Bundle getUserRestrictions(int userId) {
480 // checkManageUsersPermission("getUserRestrictions");
481
482 synchronized (mPackagesLock) {
483 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700484 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800485 }
486 }
487
488 @Override
489 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700490 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700491 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800492
493 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700494 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800495 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400496 long token = Binder.clearCallingIdentity();
497 try {
498 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
499 } catch (RemoteException e) {
500 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
501 } finally {
502 Binder.restoreCallingIdentity(token);
503 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800504 writeUserLocked(mUsers.get(userId));
505 }
506 }
507
Amith Yamasani258848d2012-08-10 17:06:33 -0700508 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700509 * Check if we've hit the limit of how many users can be created.
510 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700511 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700512 int aliveUserCount = 0;
513 final int totalUserCount = mUsers.size();
514 // Skip over users being removed
515 for (int i = 0; i < totalUserCount; i++) {
516 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700517 if (!mRemovingUserIds.get(user.id)
518 && !user.isGuest()) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700519 aliveUserCount++;
520 }
521 }
522 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700523 }
524
525 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700526 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700527 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700528 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700529 *
530 * @param message used as message if SecurityException is thrown
531 * @throws SecurityException if the caller is not system or root
532 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700533 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700534 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700535 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400536 && ActivityManager.checkComponentPermission(
537 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700538 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
539 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
540 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400541 }
542
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700543 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700544 try {
545 File dir = new File(mUsersDir, Integer.toString(info.id));
546 File file = new File(dir, USER_PHOTO_FILENAME);
547 if (!dir.exists()) {
548 dir.mkdir();
549 FileUtils.setPermissions(
550 dir.getPath(),
551 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
552 -1, -1);
553 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700554 FileOutputStream os;
555 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700556 info.iconPath = file.getAbsolutePath();
557 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700558 try {
559 os.close();
560 } catch (IOException ioe) {
561 // What the ... !
562 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700563 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700564 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700565 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700566 }
567
Amith Yamasani0b285492011-04-14 17:35:23 -0700568 /**
569 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
570 * cache it elsewhere.
571 * @return the array of user ids.
572 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700573 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700574 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700575 return mUserIds;
576 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700577 }
578
Dianne Hackborn4428e172012-08-24 17:43:05 -0700579 int[] getUserIdsLPr() {
580 return mUserIds;
581 }
582
Amith Yamasani13593602012-03-22 16:16:17 -0700583 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700584 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700585 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700586 return;
587 }
588 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700589 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700590 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700591 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700592 XmlPullParser parser = Xml.newPullParser();
593 parser.setInput(fis, null);
594 int type;
595 while ((type = parser.next()) != XmlPullParser.START_TAG
596 && type != XmlPullParser.END_DOCUMENT) {
597 ;
598 }
599
600 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700601 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700602 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700603 return;
604 }
605
Amith Yamasani2a003292012-08-14 18:25:45 -0700606 mNextSerialNumber = -1;
607 if (parser.getName().equals(TAG_USERS)) {
608 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
609 if (lastSerialNumber != null) {
610 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
611 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700612 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
613 if (versionNumber != null) {
614 mUserVersion = Integer.parseInt(versionNumber);
615 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700616 }
617
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700618 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530619 if (type == XmlPullParser.START_TAG) {
620 final String name = parser.getName();
621 if (name.equals(TAG_USER)) {
622 String id = parser.getAttributeValue(null, ATTR_ID);
623 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700624
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530625 if (user != null) {
626 mUsers.put(user.id, user);
627 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
628 mNextSerialNumber = user.id + 1;
629 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700630 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530631 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
632 mGuestRestrictions.clear();
633 readRestrictionsLocked(parser, mGuestRestrictions);
Amith Yamasani258848d2012-08-10 17:06:33 -0700634 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700635 }
636 }
Amith Yamasani13593602012-03-22 16:16:17 -0700637 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700638 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700639 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700640 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700641 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700642 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800643 } finally {
644 if (fis != null) {
645 try {
646 fis.close();
647 } catch (IOException e) {
648 }
649 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700650 }
651 }
652
Amith Yamasani6f34b412012-10-22 18:19:27 -0700653 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800654 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700655 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700656 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700657 int userVersion = mUserVersion;
658 if (userVersion < 1) {
659 // Assign a proper name for the owner, if not initialized correctly before
660 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
661 if ("Primary".equals(user.name)) {
662 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
663 writeUserLocked(user);
664 }
665 userVersion = 1;
666 }
667
Amith Yamasanibc9625052012-11-15 14:39:18 -0800668 if (userVersion < 2) {
669 // Owner should be marked as initialized
670 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
671 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
672 user.flags |= UserInfo.FLAG_INITIALIZED;
673 writeUserLocked(user);
674 }
675 userVersion = 2;
676 }
677
Amith Yamasani350962c2013-08-06 11:18:53 -0700678
Amith Yamasani5e486f52013-08-07 11:06:44 -0700679 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700680 userVersion = 4;
681 }
682
Amith Yamasani6f34b412012-10-22 18:19:27 -0700683 if (userVersion < USER_VERSION) {
684 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
685 + USER_VERSION);
686 } else {
687 mUserVersion = userVersion;
688 writeUserListLocked();
689 }
690 }
691
Amith Yamasani13593602012-03-22 16:16:17 -0700692 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700693 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800694 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700695 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700696 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700697 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700698 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400699 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800700
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500701 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800702 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
703
Amith Yamasani13593602012-03-22 16:16:17 -0700704 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700705
Amith Yamasani13593602012-03-22 16:16:17 -0700706 writeUserListLocked();
707 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700708 }
709
710 /*
711 * Writes the user file in this format:
712 *
713 * <user flags="20039023" id="0">
714 * <name>Primary</name>
715 * </user>
716 */
Amith Yamasani13593602012-03-22 16:16:17 -0700717 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700718 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700719 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700720 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700721 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700722 final BufferedOutputStream bos = new BufferedOutputStream(fos);
723
724 // XmlSerializer serializer = XmlUtils.serializerInstance();
725 final XmlSerializer serializer = new FastXmlSerializer();
726 serializer.setOutput(bos, "utf-8");
727 serializer.startDocument(null, true);
728 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
729
730 serializer.startTag(null, TAG_USER);
731 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700732 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700733 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700734 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
735 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
736 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700737 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
738 if (pinState != null) {
739 if (pinState.salt != 0) {
740 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
741 }
742 if (pinState.pinHash != null) {
743 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
744 }
745 if (pinState.failedAttempts != 0) {
746 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
747 Integer.toString(pinState.failedAttempts));
748 serializer.attribute(null, ATTR_LAST_RETRY_MS,
749 Long.toString(pinState.lastAttemptTime));
750 }
751 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700752 if (userInfo.iconPath != null) {
753 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
754 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700755 if (userInfo.partial) {
756 serializer.attribute(null, ATTR_PARTIAL, "true");
757 }
Kenny Guy2a764942014-04-02 13:29:20 +0100758 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
759 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
760 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000761 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700762
763 serializer.startTag(null, TAG_NAME);
764 serializer.text(userInfo.name);
765 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800766 Bundle restrictions = mUserRestrictions.get(userInfo.id);
767 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530768 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800769 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700770 serializer.endTag(null, TAG_USER);
771
772 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700773 userFile.finishWrite(fos);
774 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700775 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700776 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700777 }
778 }
779
780 /*
781 * Writes the user list file in this format:
782 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700783 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700784 * <user id="0"></user>
785 * <user id="2"></user>
786 * </users>
787 */
Amith Yamasani13593602012-03-22 16:16:17 -0700788 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700789 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700790 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700791 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700792 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700793 final BufferedOutputStream bos = new BufferedOutputStream(fos);
794
795 // XmlSerializer serializer = XmlUtils.serializerInstance();
796 final XmlSerializer serializer = new FastXmlSerializer();
797 serializer.setOutput(bos, "utf-8");
798 serializer.startDocument(null, true);
799 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
800
801 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700802 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700803 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700804
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530805 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
806 writeRestrictionsLocked(serializer, mGuestRestrictions);
807 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700808 for (int i = 0; i < mUsers.size(); i++) {
809 UserInfo user = mUsers.valueAt(i);
810 serializer.startTag(null, TAG_USER);
811 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
812 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700813 }
814
815 serializer.endTag(null, TAG_USERS);
816
817 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700818 userListFile.finishWrite(fos);
819 } catch (Exception e) {
820 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700821 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700822 }
823 }
824
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530825 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
826 throws IOException {
827 serializer.startTag(null, TAG_RESTRICTIONS);
828 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
829 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
830 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
831 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
832 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
833 writeBoolean(serializer, restrictions,
834 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
835 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
836 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
837 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
838 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
839 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
840 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
841 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
842 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
843 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
844 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
845 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
846 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
847 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
848 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
849 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
850 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700851 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
852 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400853 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530854 serializer.endTag(null, TAG_RESTRICTIONS);
855 }
856
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800857 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700858 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700859 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700860 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700861 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700862 long creationTime = 0L;
863 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700864 long salt = 0L;
865 String pinHash = null;
866 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100867 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700868 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700869 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800870 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700871
872 FileInputStream fis = null;
873 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700874 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700875 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700876 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700877 XmlPullParser parser = Xml.newPullParser();
878 parser.setInput(fis, null);
879 int type;
880 while ((type = parser.next()) != XmlPullParser.START_TAG
881 && type != XmlPullParser.END_DOCUMENT) {
882 ;
883 }
884
885 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700886 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700887 return null;
888 }
889
890 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700891 int storedId = readIntAttribute(parser, ATTR_ID, -1);
892 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700893 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700894 return null;
895 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700896 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
897 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700898 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700899 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
900 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700901 salt = readLongAttribute(parser, ATTR_SALT, 0L);
902 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
903 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
904 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100905 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
906 UserInfo.NO_PROFILE_GROUP_ID);
907 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
908 // This attribute was added and renamed during development of L.
909 // TODO Remove upgrade path by 1st May 2014
910 profileGroupId = readIntAttribute(parser, "relatedGroupId",
911 UserInfo.NO_PROFILE_GROUP_ID);
912 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700913 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
914 if ("true".equals(valueString)) {
915 partial = true;
916 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700917
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800918 int outerDepth = parser.getDepth();
919 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
920 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
921 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
922 continue;
923 }
924 String tag = parser.getName();
925 if (TAG_NAME.equals(tag)) {
926 type = parser.next();
927 if (type == XmlPullParser.TEXT) {
928 name = parser.getText();
929 }
930 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530931 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700932 }
933 }
934 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700935
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700936 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700937 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700938 userInfo.creationTime = creationTime;
939 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700940 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100941 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800942 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700943 if (salt != 0L) {
944 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
945 if (pinState == null) {
946 pinState = new RestrictionsPinState();
947 mRestrictionsPinStates.put(id, pinState);
948 }
949 pinState.salt = salt;
950 pinState.pinHash = pinHash;
951 pinState.failedAttempts = failedAttempts;
952 pinState.lastAttemptTime = lastAttemptTime;
953 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700954 return userInfo;
955
956 } catch (IOException ioe) {
957 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800958 } finally {
959 if (fis != null) {
960 try {
961 fis.close();
962 } catch (IOException e) {
963 }
964 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700965 }
966 return null;
967 }
968
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530969 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
970 throws IOException {
971 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
972 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
973 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
974 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
975 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
976 readBoolean(parser, restrictions,
977 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
978 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
979 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
980 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
981 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
982 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
983 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
984 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
985 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
986 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
987 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
988 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
989 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
990 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
991 readBoolean(parser, restrictions,
992 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
993 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
994 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700995 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
996 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400997 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530998 }
999
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001000 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1001 String restrictionKey) {
1002 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001003 if (value != null) {
1004 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1005 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001006 }
1007
1008 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1009 throws IOException {
1010 if (restrictions.containsKey(restrictionKey)) {
1011 xml.attribute(null, restrictionKey,
1012 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1013 }
1014 }
1015
Amith Yamasani920ace02012-09-20 22:15:37 -07001016 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1017 String valueString = parser.getAttributeValue(null, attr);
1018 if (valueString == null) return defaultValue;
1019 try {
1020 return Integer.parseInt(valueString);
1021 } catch (NumberFormatException nfe) {
1022 return defaultValue;
1023 }
1024 }
1025
1026 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1027 String valueString = parser.getAttributeValue(null, attr);
1028 if (valueString == null) return defaultValue;
1029 try {
1030 return Long.parseLong(valueString);
1031 } catch (NumberFormatException nfe) {
1032 return defaultValue;
1033 }
1034 }
1035
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001036 private boolean isPackageInstalled(String pkg, int userId) {
1037 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1038 PackageManager.GET_UNINSTALLED_PACKAGES,
1039 userId);
1040 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1041 return false;
1042 }
1043 return true;
1044 }
1045
Amith Yamasanib82add22013-07-09 11:24:44 -07001046 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001047 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001048 * Does not do any permissions checking.
1049 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001050 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001051 synchronized (mPackagesLock) {
1052 File dir = Environment.getUserSystemDirectory(userId);
1053 String[] files = dir.list();
1054 if (files == null) return;
1055 for (String fileName : files) {
1056 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1057 File resFile = new File(dir, fileName);
1058 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001059 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001060 }
1061 }
1062 }
1063 }
1064 }
1065
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001066 /**
1067 * Removes the app restrictions file for a specific package and user id, if it exists.
1068 */
1069 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1070 synchronized (mPackagesLock) {
1071 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001072 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001073 if (resFile.exists()) {
1074 resFile.delete();
1075 }
1076 }
1077 }
1078
Kenny Guya52dc3e2014-02-11 15:33:14 +00001079 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001080 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001081 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001082 if (userId != UserHandle.USER_OWNER) {
1083 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001084 return null;
1085 }
Kenny Guy2a764942014-04-02 13:29:20 +01001086 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001087 }
1088
Amith Yamasani258848d2012-08-10 17:06:33 -07001089 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001090 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001091 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001092 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001093 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001094
Jessica Hummelbe81c802014-04-22 15:49:22 +01001095 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001096 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1097 UserManager.DISALLOW_ADD_USER, false)) {
1098 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1099 return null;
1100 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001101 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001102 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001103 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001104 try {
1105 synchronized (mInstallLock) {
1106 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001107 UserInfo parent = null;
1108 if (parentId != UserHandle.USER_NULL) {
1109 parent = getUserInfoLocked(parentId);
1110 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001111 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001112 // If we're not adding a guest user and the limit has been reached,
1113 // cannot add a user.
1114 if (!isGuest && isUserLimitReachedLocked()) {
1115 return null;
1116 }
1117 // If we're adding a guest and there already exists one, bail.
1118 if (isGuest && numberOfUsersOfTypeLocked(UserInfo.FLAG_GUEST, true) > 0) {
1119 return null;
1120 }
1121 // Limit number of managed profiles that can be created
1122 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1123 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1124 >= MAX_MANAGED_PROFILES) {
1125 return null;
1126 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001127 int userId = getNextAvailableIdLocked();
1128 userInfo = new UserInfo(userId, name, null, flags);
1129 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1130 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001131 long now = System.currentTimeMillis();
1132 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001133 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001134 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001135 mUsers.put(userId, userInfo);
1136 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001137 if (parent != null) {
1138 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1139 parent.profileGroupId = parent.id;
1140 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001141 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001142 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001143 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001144 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001145 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001146 userInfo.partial = false;
1147 writeUserLocked(userInfo);
1148 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001149 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001150 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001151 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001152 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001153 if (userInfo != null) {
1154 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1155 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1156 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1157 android.Manifest.permission.MANAGE_USERS);
1158 }
1159 } finally {
1160 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001161 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001162 return userInfo;
1163 }
1164
Amith Yamasani95ab7842014-08-11 17:09:26 -07001165 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1166 int count = 0;
1167 for (int i = mUsers.size() - 1; i >= 0; i--) {
1168 UserInfo user = mUsers.valueAt(i);
1169 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1170 if ((user.flags & flags) != 0) {
1171 count++;
1172 }
1173 }
1174 }
1175 return count;
1176 }
1177
Amith Yamasani0b285492011-04-14 17:35:23 -07001178 /**
1179 * Removes a user and all data directories created for that user. This method should be called
1180 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001181 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001182 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001183 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001184 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001185 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1186 UserManager.DISALLOW_REMOVE_USER, false)) {
1187 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1188 return false;
1189 }
1190
Kenny Guyee58b4f2014-05-23 15:19:53 +01001191 long ident = Binder.clearCallingIdentity();
1192 try {
1193 final UserInfo user;
1194 synchronized (mPackagesLock) {
1195 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001196 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001197 return false;
1198 }
1199 mRemovingUserIds.put(userHandle, true);
1200 try {
1201 mAppOpsService.removeUser(userHandle);
1202 } catch (RemoteException e) {
1203 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1204 }
1205 // Set this to a partially created user, so that the user will be purged
1206 // on next startup, in case the runtime stops now before stopping and
1207 // removing the user completely.
1208 user.partial = true;
1209 // Mark it as disabled, so that it isn't returned any more when
1210 // profiles are queried.
1211 user.flags |= UserInfo.FLAG_DISABLED;
1212 writeUserLocked(user);
1213 }
1214
1215 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1216 && user.isManagedProfile()) {
1217 // Send broadcast to notify system that the user removed was a
1218 // managed user.
1219 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1220 }
1221
1222 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1223 int res;
1224 try {
1225 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1226 new IStopUserCallback.Stub() {
1227 @Override
1228 public void userStopped(int userId) {
1229 finishRemoveUser(userId);
1230 }
1231 @Override
1232 public void userStopAborted(int userId) {
1233 }
1234 });
1235 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001236 return false;
1237 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001238 return res == ActivityManager.USER_OP_SUCCESS;
1239 } finally {
1240 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001241 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001242 }
1243
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001244 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001245 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001246 // Let other services shutdown any activity and clean up their state before completely
1247 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001248 long ident = Binder.clearCallingIdentity();
1249 try {
1250 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1251 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001252 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1253 android.Manifest.permission.MANAGE_USERS,
1254
1255 new BroadcastReceiver() {
1256 @Override
1257 public void onReceive(Context context, Intent intent) {
1258 if (DBG) {
1259 Slog.i(LOG_TAG,
1260 "USER_REMOVED broadcast sent, cleaning up user data "
1261 + userHandle);
1262 }
1263 new Thread() {
1264 public void run() {
1265 synchronized (mInstallLock) {
1266 synchronized (mPackagesLock) {
1267 removeUserStateLocked(userHandle);
1268 }
1269 }
1270 }
1271 }.start();
1272 }
1273 },
1274
1275 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001276 } finally {
1277 Binder.restoreCallingIdentity(ident);
1278 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001279 }
1280
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001281 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001282 // Cleanup package manager settings
1283 mPm.cleanUpUserLILPw(userHandle);
1284
1285 // Remove this user from the list
1286 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001287
1288 // Have user ID linger for several seconds to let external storage VFS
1289 // cache entries expire. This must be greater than the 'entry_valid'
1290 // timeout used by the FUSE daemon.
1291 mHandler.postDelayed(new Runnable() {
1292 @Override
1293 public void run() {
1294 synchronized (mPackagesLock) {
1295 mRemovingUserIds.delete(userHandle);
1296 }
1297 }
1298 }, MINUTE_IN_MILLIS);
1299
Amith Yamasani655d0e22013-06-12 14:19:10 -07001300 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001301 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001302 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001303 userFile.delete();
1304 // Update the user list
1305 writeUserListLocked();
1306 updateUserIdsLocked();
1307 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1308 }
1309
Amith Yamasani61f57372012-08-31 12:12:28 -07001310 private void removeDirectoryRecursive(File parent) {
1311 if (parent.isDirectory()) {
1312 String[] files = parent.list();
1313 for (String filename : files) {
1314 File child = new File(parent, filename);
1315 removeDirectoryRecursive(child);
1316 }
1317 }
1318 parent.delete();
1319 }
1320
Kenny Guyf8d3a232014-05-15 16:09:52 +01001321 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001322 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001323 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1324 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001325 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1326 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001327 }
1328
Amith Yamasani2a003292012-08-14 18:25:45 -07001329 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001330 public Bundle getApplicationRestrictions(String packageName) {
1331 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1332 }
1333
1334 @Override
1335 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001336 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001337 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001338 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001339 }
1340 synchronized (mPackagesLock) {
1341 // Read the restrictions from XML
1342 return readApplicationRestrictionsLocked(packageName, userId);
1343 }
1344 }
1345
1346 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001347 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001348 int userId) {
1349 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001350 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001351 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001352 }
1353 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001354 if (restrictions == null || restrictions.isEmpty()) {
1355 cleanAppRestrictionsForPackage(packageName, userId);
1356 } else {
1357 // Write the restrictions to XML
1358 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1359 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001360 }
Robin Lee66e5d962014-04-09 16:44:21 +01001361
Kenny Guyd21b2182014-07-17 16:38:55 +01001362 if (isPackageInstalled(packageName, userId)) {
1363 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1364 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1365 changeIntent.setPackage(packageName);
1366 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1367 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1368 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001369 }
1370
Amith Yamasani655d0e22013-06-12 14:19:10 -07001371 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001372 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001373 checkManageUsersPermission("Only system can modify the restrictions pin");
1374 int userId = UserHandle.getCallingUserId();
1375 synchronized (mPackagesLock) {
1376 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1377 if (pinState == null) {
1378 pinState = new RestrictionsPinState();
1379 }
1380 if (newPin == null) {
1381 pinState.salt = 0;
1382 pinState.pinHash = null;
1383 } else {
1384 try {
1385 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1386 } catch (NoSuchAlgorithmException e) {
1387 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1388 }
1389 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1390 pinState.failedAttempts = 0;
1391 }
1392 mRestrictionsPinStates.put(userId, pinState);
1393 writeUserLocked(mUsers.get(userId));
1394 }
1395 return true;
1396 }
1397
1398 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001399 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001400 checkManageUsersPermission("Only system can verify the restrictions pin");
1401 int userId = UserHandle.getCallingUserId();
1402 synchronized (mPackagesLock) {
1403 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1404 // If there's no pin set, return error code
1405 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1406 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1407 } else if (pin == null) {
1408 // If just checking if user can be prompted, return remaining time
1409 int waitTime = getRemainingTimeForPinAttempt(pinState);
1410 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1411 return waitTime;
1412 } else {
1413 int waitTime = getRemainingTimeForPinAttempt(pinState);
1414 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1415 if (waitTime > 0) {
1416 return waitTime;
1417 }
1418 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1419 pinState.failedAttempts = 0;
1420 writeUserLocked(mUsers.get(userId));
1421 return UserManager.PIN_VERIFICATION_SUCCESS;
1422 } else {
1423 pinState.failedAttempts++;
1424 pinState.lastAttemptTime = System.currentTimeMillis();
1425 writeUserLocked(mUsers.get(userId));
1426 return waitTime;
1427 }
1428 }
1429 }
1430 }
1431
1432 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1433 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1434 BACKOFF_TIMES.length - 1);
1435 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1436 BACKOFF_TIMES[backoffIndex] : 0;
1437 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1438 0);
1439 }
1440
1441 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001442 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001443 int userId = UserHandle.getCallingUserId();
1444 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001445 return hasRestrictionsPinLocked(userId);
1446 }
1447 }
1448
1449 private boolean hasRestrictionsPinLocked(int userId) {
1450 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1451 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1452 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001453 }
1454 return true;
1455 }
1456
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001457 @Override
1458 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001459 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001460 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001461 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001462 }
1463
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001464 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001465 synchronized (mPackagesLock) {
1466 // Remove all user restrictions
1467 setUserRestrictions(new Bundle(), userHandle);
1468 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001469 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001470 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001471 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001472 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001473 if (unhideApps) {
1474 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001475 }
1476 }
1477
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001478 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001479 mHandler.post(new Runnable() {
1480 @Override
1481 public void run() {
1482 List<ApplicationInfo> apps =
1483 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1484 userHandle).getList();
1485 final long ident = Binder.clearCallingIdentity();
1486 try {
1487 for (ApplicationInfo appInfo : apps) {
1488 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001489 && (appInfo.flags & ApplicationInfo.FLAG_HIDDEN) != 0) {
1490 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001491 userHandle);
1492 }
1493 }
1494 } finally {
1495 Binder.restoreCallingIdentity(ident);
1496 }
1497 }
1498 });
1499 }
1500
Amith Yamasani655d0e22013-06-12 14:19:10 -07001501 /*
1502 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1503 * Not the most secure, but it is at least a second level of protection. First level is that
1504 * the file is in a location only readable by the system process.
1505 * @param password the password.
1506 * @param salt the randomly generated salt
1507 * @return the hash of the pattern in a String.
1508 */
1509 private String passwordToHash(String password, long salt) {
1510 if (password == null) {
1511 return null;
1512 }
1513 String algo = null;
1514 String hashed = salt + password;
1515 try {
1516 byte[] saltedPassword = (password + salt).getBytes();
1517 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1518 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1519 hashed = toHex(sha1) + toHex(md5);
1520 } catch (NoSuchAlgorithmException e) {
1521 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1522 }
1523 return hashed;
1524 }
1525
1526 private static String toHex(byte[] ary) {
1527 final String hex = "0123456789ABCDEF";
1528 String ret = "";
1529 for (int i = 0; i < ary.length; i++) {
1530 ret += hex.charAt((ary[i] >> 4) & 0xf);
1531 ret += hex.charAt(ary[i] & 0xf);
1532 }
1533 return ret;
1534 }
1535
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001536 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001537 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001538 try {
1539 return mContext.getPackageManager().getApplicationInfo(packageName,
1540 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1541 } catch (NameNotFoundException nnfe) {
1542 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001543 } finally {
1544 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001545 }
1546 }
1547
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001548 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001549 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001550 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001551 final ArrayList<String> values = new ArrayList<String>();
1552
1553 FileInputStream fis = null;
1554 try {
1555 AtomicFile restrictionsFile =
1556 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001557 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001558 fis = restrictionsFile.openRead();
1559 XmlPullParser parser = Xml.newPullParser();
1560 parser.setInput(fis, null);
1561 int type;
1562 while ((type = parser.next()) != XmlPullParser.START_TAG
1563 && type != XmlPullParser.END_DOCUMENT) {
1564 ;
1565 }
1566
1567 if (type != XmlPullParser.START_TAG) {
1568 Slog.e(LOG_TAG, "Unable to read restrictions file "
1569 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001570 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001571 }
1572
1573 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1574 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1575 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001576 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001577 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1578 if (multiple != null) {
1579 int count = Integer.parseInt(multiple);
1580 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1581 if (type == XmlPullParser.START_TAG
1582 && parser.getName().equals(TAG_VALUE)) {
1583 values.add(parser.nextText().trim());
1584 count--;
1585 }
1586 }
1587 String [] valueStrings = new String[values.size()];
1588 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001589 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001590 } else {
1591 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001592 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1593 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1594 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1595 restrictions.putInt(key, Integer.parseInt(value));
1596 } else {
1597 restrictions.putString(key, value);
1598 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001599 }
1600 }
1601 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001602 } catch (IOException ioe) {
1603 } catch (XmlPullParserException pe) {
1604 } finally {
1605 if (fis != null) {
1606 try {
1607 fis.close();
1608 } catch (IOException e) {
1609 }
1610 }
1611 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001612 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001613 }
1614
1615 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001616 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001617 FileOutputStream fos = null;
1618 AtomicFile restrictionsFile = new AtomicFile(
1619 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001620 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001621 try {
1622 fos = restrictionsFile.startWrite();
1623 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1624
1625 // XmlSerializer serializer = XmlUtils.serializerInstance();
1626 final XmlSerializer serializer = new FastXmlSerializer();
1627 serializer.setOutput(bos, "utf-8");
1628 serializer.startDocument(null, true);
1629 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1630
1631 serializer.startTag(null, TAG_RESTRICTIONS);
1632
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001633 for (String key : restrictions.keySet()) {
1634 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001635 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001636 serializer.attribute(null, ATTR_KEY, key);
1637
1638 if (value instanceof Boolean) {
1639 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1640 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001641 } else if (value instanceof Integer) {
1642 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1643 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001644 } else if (value == null || value instanceof String) {
1645 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1646 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001647 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001648 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1649 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001650 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001651 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001652 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001653 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001654 serializer.endTag(null, TAG_VALUE);
1655 }
1656 }
1657 serializer.endTag(null, TAG_ENTRY);
1658 }
1659
1660 serializer.endTag(null, TAG_RESTRICTIONS);
1661
1662 serializer.endDocument();
1663 restrictionsFile.finishWrite(fos);
1664 } catch (Exception e) {
1665 restrictionsFile.failWrite(fos);
1666 Slog.e(LOG_TAG, "Error writing application restrictions list");
1667 }
1668 }
1669
1670 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001671 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001672 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001673 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001674 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001675 }
1676 }
1677
1678 @Override
1679 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001680 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001681 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001682 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001683 }
1684 // Not found
1685 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001686 }
1687 }
1688
Amith Yamasani0b285492011-04-14 17:35:23 -07001689 /**
1690 * Caches the list of user ids in an array, adjusting the array size when necessary.
1691 */
Amith Yamasani13593602012-03-22 16:16:17 -07001692 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001693 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001694 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001695 if (!mUsers.valueAt(i).partial) {
1696 num++;
1697 }
1698 }
Amith Yamasani16389312012-10-17 21:20:14 -07001699 final int[] newUsers = new int[num];
1700 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001701 for (int i = 0; i < mUsers.size(); i++) {
1702 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001703 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001704 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001705 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001706 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001707 }
1708
1709 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001710 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001711 * @param userId the user that was just foregrounded
1712 */
1713 public void userForeground(int userId) {
1714 synchronized (mPackagesLock) {
1715 UserInfo user = mUsers.get(userId);
1716 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001717 if (user == null || user.partial) {
1718 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1719 return;
1720 }
1721 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001722 user.lastLoggedInTime = now;
1723 writeUserLocked(user);
1724 }
1725 }
1726 }
1727
1728 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001729 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001730 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1731 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001732 * @return
1733 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001734 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001735 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001736 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001737 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001738 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001739 break;
1740 }
1741 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001742 }
Amith Yamasani195263742012-08-21 15:40:12 -07001743 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001744 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001745 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001746
Amith Yamasanifc95e702013-09-26 13:20:17 -07001747 private String packageToRestrictionsFileName(String packageName) {
1748 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1749 }
1750
1751 private String restrictionsFileNameToPackage(String fileName) {
1752 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1753 (int) (fileName.length() - XML_SUFFIX.length()));
1754 }
1755
Amith Yamasani920ace02012-09-20 22:15:37 -07001756 @Override
1757 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1758 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1759 != PackageManager.PERMISSION_GRANTED) {
1760 pw.println("Permission Denial: can't dump UserManager from from pid="
1761 + Binder.getCallingPid()
1762 + ", uid=" + Binder.getCallingUid()
1763 + " without permission "
1764 + android.Manifest.permission.DUMP);
1765 return;
1766 }
1767
1768 long now = System.currentTimeMillis();
1769 StringBuilder sb = new StringBuilder();
1770 synchronized (mPackagesLock) {
1771 pw.println("Users:");
1772 for (int i = 0; i < mUsers.size(); i++) {
1773 UserInfo user = mUsers.valueAt(i);
1774 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001775 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001776 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001777 if (user.partial) pw.print(" <partial>");
1778 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001779 pw.print(" Created: ");
1780 if (user.creationTime == 0) {
1781 pw.println("<unknown>");
1782 } else {
1783 sb.setLength(0);
1784 TimeUtils.formatDuration(now - user.creationTime, sb);
1785 sb.append(" ago");
1786 pw.println(sb);
1787 }
1788 pw.print(" Last logged in: ");
1789 if (user.lastLoggedInTime == 0) {
1790 pw.println("<unknown>");
1791 } else {
1792 sb.setLength(0);
1793 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1794 sb.append(" ago");
1795 pw.println(sb);
1796 }
1797 }
1798 }
1799 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001800}