blob: 95e8834344bb3c5c0d408b3fee419b6c3bf41cb6 [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
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070019import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070020import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070021import android.app.ActivityManagerNative;
22import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070023import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070024import android.content.Context;
25import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070026import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070027import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080028import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070029import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070030import android.graphics.Bitmap;
31import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070032import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080033import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.os.Environment;
35import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080036import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.IUserManager;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -080038import android.os.Message;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070040import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040041import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070042import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070043import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070044import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070045import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070046import android.util.Slog;
47import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080048import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070049import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.util.Xml;
51
Jason Monk62062992014-05-06 09:55:28 -040052import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080053import com.android.internal.util.ArrayUtils;
54import com.android.internal.util.FastXmlSerializer;
55
56import org.xmlpull.v1.XmlPullParser;
57import org.xmlpull.v1.XmlPullParserException;
58import org.xmlpull.v1.XmlSerializer;
59
Amith Yamasani4b2e9342011-03-31 12:38:53 -070060import java.io.BufferedOutputStream;
61import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070062import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070064import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import java.io.FileOutputStream;
66import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070067import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070068import java.security.MessageDigest;
69import java.security.NoSuchAlgorithmException;
70import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070071import java.util.ArrayList;
72import java.util.List;
73
Amith Yamasani258848d2012-08-10 17:06:33 -070074public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070075
Amith Yamasani2a003292012-08-14 18:25:45 -070076 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077
Amith Yamasani16389312012-10-17 21:20:14 -070078 private static final boolean DBG = false;
79
Amith Yamasani4b2e9342011-03-31 12:38:53 -070080 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070082 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070084 private static final String ATTR_CREATION_TIME = "created";
85 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070086 private static final String ATTR_SALT = "salt";
87 private static final String ATTR_PIN_HASH = "pinHash";
88 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
89 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070090 private static final String ATTR_SERIAL_NO = "serialNumber";
91 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070092 private static final String ATTR_PARTIAL = "partial";
Adam Lesinskieddeb492014-09-08 17:50:03 -070093 private static final String ATTR_GUEST_TO_REMOVE = "guestToRemove";
Amith Yamasani6f34b412012-10-22 18:19:27 -070094 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010095 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053096 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080099 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800100 private static final String TAG_ENTRY = "entry";
101 private static final String TAG_VALUE = "value";
102 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700103 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800104 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700106 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
107 private static final String ATTR_TYPE_STRING = "s";
108 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700109 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700110
Amith Yamasani0b285492011-04-14 17:35:23 -0700111 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700116 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800117
Amith Yamasani634cf312012-10-04 17:34:21 -0700118 private static final int MIN_USER_ID = 10;
119
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700120 private static final int USER_VERSION = 5;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700121
Amith Yamasani920ace02012-09-20 22:15:37 -0700122 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
123
Amith Yamasani655d0e22013-06-12 14:19:10 -0700124 // Number of attempts before jumping to the next BACKOFF_TIMES slot
125 private static final int BACKOFF_INC_INTERVAL = 5;
126
Amith Yamasani95ab7842014-08-11 17:09:26 -0700127 // Maximum number of managed profiles permitted is 1. This cannot be increased
128 // without first making sure that the rest of the framework is prepared for it.
129 private static final int MAX_MANAGED_PROFILES = 1;
130
Amith Yamasani655d0e22013-06-12 14:19:10 -0700131 // Amount of time to force the user to wait before entering the PIN again, after failing
132 // BACKOFF_INC_INTERVAL times.
133 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
134
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800135 static final int WRITE_USER_MSG = 1;
136 static final int WRITE_USER_DELAY = 2*1000; // 2 seconds
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530137
Dianne Hackborn4428e172012-08-24 17:43:05 -0700138 private final Context mContext;
139 private final PackageManagerService mPm;
140 private final Object mInstallLock;
141 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143 private final Handler mHandler;
144
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private final File mUsersDir;
146 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700147 private final File mBaseUserPath;
148
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800149 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800150 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530151 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800152
Amith Yamasani655d0e22013-06-12 14:19:10 -0700153 class RestrictionsPinState {
154 long salt;
155 String pinHash;
156 int failedAttempts;
157 long lastAttemptTime;
158 }
159
160 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
161 new SparseArray<RestrictionsPinState>();
162
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800163 /**
164 * Set of user IDs being actively removed. Removed IDs linger in this set
165 * for several seconds to work around a VFS caching issue.
166 */
167 // @GuardedBy("mPackagesLock")
168 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700169
Amith Yamasani0b285492011-04-14 17:35:23 -0700170 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700171 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700172 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700173
Jason Monk62062992014-05-06 09:55:28 -0400174 private IAppOpsService mAppOpsService;
175
Amith Yamasani258848d2012-08-10 17:06:33 -0700176 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700177
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 public static UserManagerService getInstance() {
179 synchronized (UserManagerService.class) {
180 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700182 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183
184 /**
185 * Available for testing purposes.
186 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700187 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700188 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700189 }
190
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 /**
192 * Called by package manager to create the service. This is closely
193 * associated with the package manager, and the given lock is the
194 * package manager's own lock.
195 */
196 UserManagerService(Context context, PackageManagerService pm,
197 Object installLock, Object packagesLock) {
198 this(context, pm, installLock, packagesLock,
199 Environment.getDataDirectory(),
200 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700201 }
202
Dianne Hackborn4428e172012-08-24 17:43:05 -0700203 /**
204 * Available for testing purposes.
205 */
206 private UserManagerService(Context context, PackageManagerService pm,
207 Object installLock, Object packagesLock,
208 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700209 mContext = context;
210 mPm = pm;
211 mInstallLock = installLock;
212 mPackagesLock = packagesLock;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800213 mHandler = new MainHandler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700214 synchronized (mInstallLock) {
215 synchronized (mPackagesLock) {
216 mUsersDir = new File(dataDir, USER_INFO_DIR);
217 mUsersDir.mkdirs();
218 // Make zeroth user directory, for services to migrate their files to that location
219 File userZeroDir = new File(mUsersDir, "0");
220 userZeroDir.mkdirs();
221 mBaseUserPath = baseUserPath;
222 FileUtils.setPermissions(mUsersDir.toString(),
223 FileUtils.S_IRWXU|FileUtils.S_IRWXG
224 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
225 -1, -1);
226 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800227 initDefaultGuestRestrictions();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700228 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700229 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700230 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
231 for (int i = 0; i < mUsers.size(); i++) {
232 UserInfo ui = mUsers.valueAt(i);
Adam Lesinskieddeb492014-09-08 17:50:03 -0700233 if ((ui.partial || ui.guestToRemove) && i != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700234 partials.add(ui);
235 }
236 }
237 for (int i = 0; i < partials.size(); i++) {
238 UserInfo ui = partials.get(i);
239 Slog.w(LOG_TAG, "Removing partially created user #" + i
240 + " (name=" + ui.name + ")");
241 removeUserStateLocked(ui.id);
242 }
243 sInstance = this;
244 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700245 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700246 }
247
248 void systemReady() {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700249 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400250 mAppOpsService = IAppOpsService.Stub.asInterface(
251 ServiceManager.getService(Context.APP_OPS_SERVICE));
252 for (int i = 0; i < mUserIds.length; ++i) {
253 try {
254 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
255 } catch (RemoteException e) {
256 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
257 }
258 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700259 }
260
261 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700262 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700263 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700264 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700265 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
266 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700267 UserInfo ui = mUsers.valueAt(i);
268 if (ui.partial) {
269 continue;
270 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800271 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700272 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700273 }
Amith Yamasani13593602012-03-22 16:16:17 -0700274 }
275 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700276 }
Amith Yamasani13593602012-03-22 16:16:17 -0700277 }
278
Amith Yamasani258848d2012-08-10 17:06:33 -0700279 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100280 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800281 if (userId != UserHandle.getCallingUserId()) {
282 checkManageUsersPermission("getting profiles related to user " + userId);
283 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700284 final long ident = Binder.clearCallingIdentity();
285 try {
286 synchronized (mPackagesLock) {
287 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100288 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700289 } finally {
290 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000291 }
292 }
293
Amith Yamasanibe465322014-04-24 13:45:17 -0700294 /** Assume permissions already checked and caller's identity cleared */
295 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700296 UserInfo user = getUserInfoLocked(userId);
297 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700298 if (user == null) {
299 // Probably a dying user
300 return users;
301 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700302 for (int i = 0; i < mUsers.size(); i++) {
303 UserInfo profile = mUsers.valueAt(i);
304 if (!isProfileOf(user, profile)) {
305 continue;
306 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100307 if (enabledOnly && !profile.isEnabled()) {
308 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700309 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700310 if (mRemovingUserIds.get(profile.id)) {
311 continue;
312 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700313 users.add(profile);
314 }
315 return users;
316 }
317
Jessica Hummelbe81c802014-04-22 15:49:22 +0100318 @Override
319 public UserInfo getProfileParent(int userHandle) {
320 checkManageUsersPermission("get the profile parent");
321 synchronized (mPackagesLock) {
322 UserInfo profile = getUserInfoLocked(userHandle);
323 int parentUserId = profile.profileGroupId;
324 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
325 return null;
326 } else {
327 return getUserInfoLocked(parentUserId);
328 }
329 }
330 }
331
Kenny Guy2a764942014-04-02 13:29:20 +0100332 private boolean isProfileOf(UserInfo user, UserInfo profile) {
333 return user.id == profile.id ||
334 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
335 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000336 }
337
338 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100339 public void setUserEnabled(int userId) {
340 checkManageUsersPermission("enable user");
341 synchronized (mPackagesLock) {
342 UserInfo info = getUserInfoLocked(userId);
343 if (info != null && !info.isEnabled()) {
344 info.flags ^= UserInfo.FLAG_DISABLED;
345 writeUserLocked(info);
346 }
347 }
348 }
349
350 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700351 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700352 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700353 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700354 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700355 }
356 }
357
Amith Yamasani71e6c692013-03-24 17:39:28 -0700358 @Override
359 public boolean isRestricted() {
360 synchronized (mPackagesLock) {
361 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
362 }
363 }
364
Amith Yamasani195263742012-08-21 15:40:12 -0700365 /*
366 * Should be locked on mUsers before calling this.
367 */
368 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700369 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700370 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800371 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700372 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
373 return null;
374 }
375 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700376 }
377
Amith Yamasani13593602012-03-22 16:16:17 -0700378 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700379 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700380 return ArrayUtils.contains(mUserIds, userId);
381 }
382 }
383
Amith Yamasani258848d2012-08-10 17:06:33 -0700384 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700385 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700386 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700387 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700388 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700389 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700390 if (info == null || info.partial) {
391 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
392 return;
393 }
Amith Yamasani13593602012-03-22 16:16:17 -0700394 if (name != null && !name.equals(info.name)) {
395 info.name = name;
396 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700397 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700398 }
399 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700400 if (changed) {
401 sendUserInfoChangedBroadcast(userId);
402 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700403 }
404
Amith Yamasani258848d2012-08-10 17:06:33 -0700405 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700406 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700407 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400408 long ident = Binder.clearCallingIdentity();
409 try {
410 synchronized (mPackagesLock) {
411 UserInfo info = mUsers.get(userId);
412 if (info == null || info.partial) {
413 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
414 return;
415 }
416 writeBitmapLocked(info, bitmap);
417 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700418 }
Jason Monk9a944532014-07-08 09:31:21 -0400419 sendUserInfoChangedBroadcast(userId);
420 } finally {
421 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700422 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700423 }
424
425 private void sendUserInfoChangedBroadcast(int userId) {
426 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
427 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
428 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700429 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700430 }
431
Amith Yamasani258848d2012-08-10 17:06:33 -0700432 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700433 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700434 synchronized (mPackagesLock) {
435 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700436 if (info == null || info.partial) {
437 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
438 return null;
439 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100440 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
441 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
442 || callingGroupId != info.profileGroupId) {
443 checkManageUsersPermission("get the icon of a user who is not related");
444 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700445 if (info.iconPath == null) {
446 return null;
447 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700448 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700449 }
450 }
451
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700452 public void makeInitialized(int userId) {
453 checkManageUsersPermission("makeInitialized");
454 synchronized (mPackagesLock) {
455 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700456 if (info == null || info.partial) {
457 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
458 }
459 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700460 info.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800461 scheduleWriteUserLocked(info);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700462 }
463 }
464 }
465
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700466 /**
467 * If default guest restrictions haven't been initialized yet, add the basic
468 * restrictions.
469 */
470 private void initDefaultGuestRestrictions() {
471 if (mGuestRestrictions.isEmpty()) {
472 mGuestRestrictions.putBoolean(UserManager.DISALLOW_OUTGOING_CALLS, true);
Amith Yamasanida0b1682014-11-21 12:58:17 -0800473 mGuestRestrictions.putBoolean(UserManager.DISALLOW_SMS, true);
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700474 }
475 }
476
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800477 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530478 public Bundle getDefaultGuestRestrictions() {
479 checkManageUsersPermission("getDefaultGuestRestrictions");
480 synchronized (mPackagesLock) {
481 return new Bundle(mGuestRestrictions);
482 }
483 }
484
485 @Override
486 public void setDefaultGuestRestrictions(Bundle restrictions) {
487 checkManageUsersPermission("setDefaultGuestRestrictions");
488 synchronized (mPackagesLock) {
489 mGuestRestrictions.clear();
490 mGuestRestrictions.putAll(restrictions);
491 writeUserListLocked();
492 }
493 }
494
495 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700496 public boolean hasUserRestriction(String restrictionKey, int userId) {
497 synchronized (mPackagesLock) {
498 Bundle restrictions = mUserRestrictions.get(userId);
499 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
500 }
501 }
502
503 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800504 public Bundle getUserRestrictions(int userId) {
505 // checkManageUsersPermission("getUserRestrictions");
506
507 synchronized (mPackagesLock) {
508 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700509 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800510 }
511 }
512
513 @Override
514 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700515 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700516 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800517
518 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700519 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800520 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400521 long token = Binder.clearCallingIdentity();
522 try {
523 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
524 } catch (RemoteException e) {
525 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
526 } finally {
527 Binder.restoreCallingIdentity(token);
528 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800529 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800530 }
531 }
532
Amith Yamasani258848d2012-08-10 17:06:33 -0700533 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700534 * Check if we've hit the limit of how many users can be created.
535 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700536 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700537 int aliveUserCount = 0;
538 final int totalUserCount = mUsers.size();
539 // Skip over users being removed
540 for (int i = 0; i < totalUserCount; i++) {
541 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700542 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700543 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700544 aliveUserCount++;
545 }
546 }
547 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700548 }
549
550 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700551 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700552 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700553 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700554 *
555 * @param message used as message if SecurityException is thrown
556 * @throws SecurityException if the caller is not system or root
557 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700558 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700559 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700560 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400561 && ActivityManager.checkComponentPermission(
562 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700563 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
564 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
565 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400566 }
567
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700568 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700569 try {
570 File dir = new File(mUsersDir, Integer.toString(info.id));
571 File file = new File(dir, USER_PHOTO_FILENAME);
572 if (!dir.exists()) {
573 dir.mkdir();
574 FileUtils.setPermissions(
575 dir.getPath(),
576 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
577 -1, -1);
578 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700579 FileOutputStream os;
580 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700581 info.iconPath = file.getAbsolutePath();
582 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700583 try {
584 os.close();
585 } catch (IOException ioe) {
586 // What the ... !
587 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700588 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700589 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700590 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700591 }
592
Amith Yamasani0b285492011-04-14 17:35:23 -0700593 /**
594 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
595 * cache it elsewhere.
596 * @return the array of user ids.
597 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700598 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700599 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700600 return mUserIds;
601 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700602 }
603
Dianne Hackborn4428e172012-08-24 17:43:05 -0700604 int[] getUserIdsLPr() {
605 return mUserIds;
606 }
607
Amith Yamasani13593602012-03-22 16:16:17 -0700608 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700609 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700610 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700611 return;
612 }
613 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700614 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700615 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700616 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700617 XmlPullParser parser = Xml.newPullParser();
618 parser.setInput(fis, null);
619 int type;
620 while ((type = parser.next()) != XmlPullParser.START_TAG
621 && type != XmlPullParser.END_DOCUMENT) {
622 ;
623 }
624
625 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700626 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700627 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700628 return;
629 }
630
Amith Yamasani2a003292012-08-14 18:25:45 -0700631 mNextSerialNumber = -1;
632 if (parser.getName().equals(TAG_USERS)) {
633 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
634 if (lastSerialNumber != null) {
635 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
636 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700637 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
638 if (versionNumber != null) {
639 mUserVersion = Integer.parseInt(versionNumber);
640 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700641 }
642
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700643 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530644 if (type == XmlPullParser.START_TAG) {
645 final String name = parser.getName();
646 if (name.equals(TAG_USER)) {
647 String id = parser.getAttributeValue(null, ATTR_ID);
648 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700649
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530650 if (user != null) {
651 mUsers.put(user.id, user);
652 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
653 mNextSerialNumber = user.id + 1;
654 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700655 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530656 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
Amith Yamasanida0b1682014-11-21 12:58:17 -0800657 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
658 && type != XmlPullParser.END_TAG) {
659 if (type == XmlPullParser.START_TAG) {
660 if (parser.getName().equals(TAG_RESTRICTIONS)) {
661 readRestrictionsLocked(parser, mGuestRestrictions);
662 }
663 break;
664 }
665 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700666 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700667 }
668 }
Amith Yamasani13593602012-03-22 16:16:17 -0700669 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700670 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700671 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700672 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700673 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700674 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800675 } finally {
676 if (fis != null) {
677 try {
678 fis.close();
679 } catch (IOException e) {
680 }
681 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700682 }
683 }
684
Amith Yamasani6f34b412012-10-22 18:19:27 -0700685 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800686 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700687 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700688 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700689 int userVersion = mUserVersion;
690 if (userVersion < 1) {
691 // Assign a proper name for the owner, if not initialized correctly before
692 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
693 if ("Primary".equals(user.name)) {
694 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800695 scheduleWriteUserLocked(user);
Amith Yamasani6f34b412012-10-22 18:19:27 -0700696 }
697 userVersion = 1;
698 }
699
Amith Yamasanibc9625052012-11-15 14:39:18 -0800700 if (userVersion < 2) {
701 // Owner should be marked as initialized
702 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
703 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
704 user.flags |= UserInfo.FLAG_INITIALIZED;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800705 scheduleWriteUserLocked(user);
Amith Yamasanibc9625052012-11-15 14:39:18 -0800706 }
707 userVersion = 2;
708 }
709
Amith Yamasani350962c2013-08-06 11:18:53 -0700710
Amith Yamasani5e486f52013-08-07 11:06:44 -0700711 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700712 userVersion = 4;
713 }
714
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700715 if (userVersion < 5) {
716 initDefaultGuestRestrictions();
717 userVersion = 5;
718 }
719
Amith Yamasani6f34b412012-10-22 18:19:27 -0700720 if (userVersion < USER_VERSION) {
721 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
722 + USER_VERSION);
723 } else {
724 mUserVersion = userVersion;
725 writeUserListLocked();
726 }
727 }
728
Amith Yamasani13593602012-03-22 16:16:17 -0700729 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700730 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800731 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700732 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700733 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700734 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700735 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400736 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800737
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500738 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800739 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
740
Amith Yamasani13593602012-03-22 16:16:17 -0700741 updateUserIdsLocked();
Amith Yamasaniaa6634e2014-10-06 14:20:28 -0700742 initDefaultGuestRestrictions();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700743
Amith Yamasani13593602012-03-22 16:16:17 -0700744 writeUserListLocked();
745 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700746 }
747
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -0800748 private void scheduleWriteUserLocked(UserInfo userInfo) {
749 if (!mHandler.hasMessages(WRITE_USER_MSG, userInfo)) {
750 Message msg = mHandler.obtainMessage(WRITE_USER_MSG, userInfo);
751 mHandler.sendMessageDelayed(msg, WRITE_USER_DELAY);
752 }
753 }
754
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700755 /*
756 * Writes the user file in this format:
757 *
758 * <user flags="20039023" id="0">
759 * <name>Primary</name>
760 * </user>
761 */
Amith Yamasani13593602012-03-22 16:16:17 -0700762 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700763 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700764 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700765 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700766 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700767 final BufferedOutputStream bos = new BufferedOutputStream(fos);
768
769 // XmlSerializer serializer = XmlUtils.serializerInstance();
770 final XmlSerializer serializer = new FastXmlSerializer();
771 serializer.setOutput(bos, "utf-8");
772 serializer.startDocument(null, true);
773 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
774
775 serializer.startTag(null, TAG_USER);
776 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700777 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700778 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700779 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
780 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
781 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700782 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
783 if (pinState != null) {
784 if (pinState.salt != 0) {
785 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
786 }
787 if (pinState.pinHash != null) {
788 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
789 }
790 if (pinState.failedAttempts != 0) {
791 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
792 Integer.toString(pinState.failedAttempts));
793 serializer.attribute(null, ATTR_LAST_RETRY_MS,
794 Long.toString(pinState.lastAttemptTime));
795 }
796 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700797 if (userInfo.iconPath != null) {
798 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
799 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700800 if (userInfo.partial) {
801 serializer.attribute(null, ATTR_PARTIAL, "true");
802 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700803 if (userInfo.guestToRemove) {
804 serializer.attribute(null, ATTR_GUEST_TO_REMOVE, "true");
805 }
Kenny Guy2a764942014-04-02 13:29:20 +0100806 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
807 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
808 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000809 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700810
811 serializer.startTag(null, TAG_NAME);
812 serializer.text(userInfo.name);
813 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800814 Bundle restrictions = mUserRestrictions.get(userInfo.id);
815 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530816 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800817 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700818 serializer.endTag(null, TAG_USER);
819
820 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700821 userFile.finishWrite(fos);
822 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700823 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700824 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700825 }
826 }
827
828 /*
829 * Writes the user list file in this format:
830 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700831 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700832 * <user id="0"></user>
833 * <user id="2"></user>
834 * </users>
835 */
Amith Yamasani13593602012-03-22 16:16:17 -0700836 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700837 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700838 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700839 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700840 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700841 final BufferedOutputStream bos = new BufferedOutputStream(fos);
842
843 // XmlSerializer serializer = XmlUtils.serializerInstance();
844 final XmlSerializer serializer = new FastXmlSerializer();
845 serializer.setOutput(bos, "utf-8");
846 serializer.startDocument(null, true);
847 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
848
849 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700850 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700851 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700852
Adam Lesinskieddeb492014-09-08 17:50:03 -0700853 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530854 writeRestrictionsLocked(serializer, mGuestRestrictions);
855 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700856 for (int i = 0; i < mUsers.size(); i++) {
857 UserInfo user = mUsers.valueAt(i);
858 serializer.startTag(null, TAG_USER);
859 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
860 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700861 }
862
863 serializer.endTag(null, TAG_USERS);
864
865 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700866 userListFile.finishWrite(fos);
867 } catch (Exception e) {
868 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700869 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700870 }
871 }
872
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530873 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
874 throws IOException {
875 serializer.startTag(null, TAG_RESTRICTIONS);
876 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
877 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
878 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
879 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
880 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
881 writeBoolean(serializer, restrictions,
882 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
883 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
884 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
885 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
886 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
887 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
888 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
889 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
890 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
891 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
892 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
893 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
894 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
895 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
896 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
897 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
898 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700899 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
900 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400901 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700902 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
903 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530904 serializer.endTag(null, TAG_RESTRICTIONS);
905 }
906
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800907 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700908 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700909 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700910 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700911 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700912 long creationTime = 0L;
913 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700914 long salt = 0L;
915 String pinHash = null;
916 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100917 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700918 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700919 boolean partial = false;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700920 boolean guestToRemove = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800921 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700922
923 FileInputStream fis = null;
924 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700925 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700926 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700927 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 XmlPullParser parser = Xml.newPullParser();
929 parser.setInput(fis, null);
930 int type;
931 while ((type = parser.next()) != XmlPullParser.START_TAG
932 && type != XmlPullParser.END_DOCUMENT) {
933 ;
934 }
935
936 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700937 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700938 return null;
939 }
940
941 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700942 int storedId = readIntAttribute(parser, ATTR_ID, -1);
943 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700944 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700945 return null;
946 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700947 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
948 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700949 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700950 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
951 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700952 salt = readLongAttribute(parser, ATTR_SALT, 0L);
953 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
954 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
955 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100956 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
957 UserInfo.NO_PROFILE_GROUP_ID);
958 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
959 // This attribute was added and renamed during development of L.
960 // TODO Remove upgrade path by 1st May 2014
961 profileGroupId = readIntAttribute(parser, "relatedGroupId",
962 UserInfo.NO_PROFILE_GROUP_ID);
963 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700964 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
965 if ("true".equals(valueString)) {
966 partial = true;
967 }
Adam Lesinskieddeb492014-09-08 17:50:03 -0700968 valueString = parser.getAttributeValue(null, ATTR_GUEST_TO_REMOVE);
969 if ("true".equals(valueString)) {
970 guestToRemove = true;
971 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700972
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800973 int outerDepth = parser.getDepth();
974 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
975 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
976 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
977 continue;
978 }
979 String tag = parser.getName();
980 if (TAG_NAME.equals(tag)) {
981 type = parser.next();
982 if (type == XmlPullParser.TEXT) {
983 name = parser.getText();
984 }
985 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530986 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700987 }
988 }
989 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700990
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700991 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700992 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700993 userInfo.creationTime = creationTime;
994 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700995 userInfo.partial = partial;
Adam Lesinskieddeb492014-09-08 17:50:03 -0700996 userInfo.guestToRemove = guestToRemove;
Kenny Guy2a764942014-04-02 13:29:20 +0100997 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800998 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700999 if (salt != 0L) {
1000 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
1001 if (pinState == null) {
1002 pinState = new RestrictionsPinState();
1003 mRestrictionsPinStates.put(id, pinState);
1004 }
1005 pinState.salt = salt;
1006 pinState.pinHash = pinHash;
1007 pinState.failedAttempts = failedAttempts;
1008 pinState.lastAttemptTime = lastAttemptTime;
1009 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001010 return userInfo;
1011
1012 } catch (IOException ioe) {
1013 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -08001014 } finally {
1015 if (fis != null) {
1016 try {
1017 fis.close();
1018 } catch (IOException e) {
1019 }
1020 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001021 }
1022 return null;
1023 }
1024
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301025 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
1026 throws IOException {
1027 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
1028 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
1029 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
1030 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
1031 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
1032 readBoolean(parser, restrictions,
1033 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
1034 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
1035 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
1036 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
1037 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
1038 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
1039 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
1040 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1041 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1042 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1043 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1044 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1045 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1046 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1047 readBoolean(parser, restrictions,
1048 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1049 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1050 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001051 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1052 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001053 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001054 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1055 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301056 }
1057
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001058 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1059 String restrictionKey) {
1060 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001061 if (value != null) {
1062 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1063 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001064 }
1065
1066 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1067 throws IOException {
1068 if (restrictions.containsKey(restrictionKey)) {
1069 xml.attribute(null, restrictionKey,
1070 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1071 }
1072 }
1073
Amith Yamasani920ace02012-09-20 22:15:37 -07001074 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1075 String valueString = parser.getAttributeValue(null, attr);
1076 if (valueString == null) return defaultValue;
1077 try {
1078 return Integer.parseInt(valueString);
1079 } catch (NumberFormatException nfe) {
1080 return defaultValue;
1081 }
1082 }
1083
1084 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1085 String valueString = parser.getAttributeValue(null, attr);
1086 if (valueString == null) return defaultValue;
1087 try {
1088 return Long.parseLong(valueString);
1089 } catch (NumberFormatException nfe) {
1090 return defaultValue;
1091 }
1092 }
1093
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001094 private boolean isPackageInstalled(String pkg, int userId) {
1095 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1096 PackageManager.GET_UNINSTALLED_PACKAGES,
1097 userId);
1098 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1099 return false;
1100 }
1101 return true;
1102 }
1103
Amith Yamasanib82add22013-07-09 11:24:44 -07001104 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001105 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001106 * Does not do any permissions checking.
1107 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001108 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001109 synchronized (mPackagesLock) {
1110 File dir = Environment.getUserSystemDirectory(userId);
1111 String[] files = dir.list();
1112 if (files == null) return;
1113 for (String fileName : files) {
1114 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1115 File resFile = new File(dir, fileName);
1116 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001117 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001118 }
1119 }
1120 }
1121 }
1122 }
1123
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001124 /**
1125 * Removes the app restrictions file for a specific package and user id, if it exists.
1126 */
1127 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1128 synchronized (mPackagesLock) {
1129 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001130 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001131 if (resFile.exists()) {
1132 resFile.delete();
1133 }
1134 }
1135 }
1136
Kenny Guya52dc3e2014-02-11 15:33:14 +00001137 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001138 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001139 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001140 if (userId != UserHandle.USER_OWNER) {
1141 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001142 return null;
1143 }
Kenny Guy2a764942014-04-02 13:29:20 +01001144 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001145 }
1146
Amith Yamasani258848d2012-08-10 17:06:33 -07001147 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001148 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001149 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001150 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001151 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001152
Jessica Hummelbe81c802014-04-22 15:49:22 +01001153 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001154 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1155 UserManager.DISALLOW_ADD_USER, false)) {
1156 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1157 return null;
1158 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001159 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001160 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001161 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001162 try {
1163 synchronized (mInstallLock) {
1164 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001165 UserInfo parent = null;
1166 if (parentId != UserHandle.USER_NULL) {
1167 parent = getUserInfoLocked(parentId);
1168 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001169 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001170 // If we're not adding a guest user and the limit has been reached,
1171 // cannot add a user.
1172 if (!isGuest && isUserLimitReachedLocked()) {
1173 return null;
1174 }
1175 // If we're adding a guest and there already exists one, bail.
Adam Lesinskieddeb492014-09-08 17:50:03 -07001176 if (isGuest && findCurrentGuestUserLocked() != null) {
Amith Yamasani95ab7842014-08-11 17:09:26 -07001177 return null;
1178 }
1179 // Limit number of managed profiles that can be created
1180 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1181 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1182 >= MAX_MANAGED_PROFILES) {
1183 return null;
1184 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001185 int userId = getNextAvailableIdLocked();
1186 userInfo = new UserInfo(userId, name, null, flags);
1187 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1188 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001189 long now = System.currentTimeMillis();
1190 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001191 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001192 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001193 mUsers.put(userId, userInfo);
1194 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001195 if (parent != null) {
1196 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1197 parent.profileGroupId = parent.id;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001198 scheduleWriteUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001199 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001200 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001201 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001202 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001203 userInfo.partial = false;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001204 scheduleWriteUserLocked(userInfo);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001205 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001206 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001207 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001208 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001209 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001210 if (userInfo != null) {
1211 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1212 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1213 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1214 android.Manifest.permission.MANAGE_USERS);
1215 }
1216 } finally {
1217 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001218 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001219 return userInfo;
1220 }
1221
Amith Yamasani95ab7842014-08-11 17:09:26 -07001222 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1223 int count = 0;
1224 for (int i = mUsers.size() - 1; i >= 0; i--) {
1225 UserInfo user = mUsers.valueAt(i);
1226 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1227 if ((user.flags & flags) != 0) {
1228 count++;
1229 }
1230 }
1231 }
1232 return count;
1233 }
1234
Amith Yamasani0b285492011-04-14 17:35:23 -07001235 /**
Adam Lesinskieddeb492014-09-08 17:50:03 -07001236 * Find the current guest user. If the Guest user is partial,
1237 * then do not include it in the results as it is about to die.
1238 * This is different than {@link #numberOfUsersOfTypeLocked(int, boolean)} due to
1239 * the special handling of Guests being removed.
1240 */
1241 private UserInfo findCurrentGuestUserLocked() {
1242 final int size = mUsers.size();
1243 for (int i = 0; i < size; i++) {
1244 final UserInfo user = mUsers.valueAt(i);
1245 if (user.isGuest() && !user.guestToRemove && !mRemovingUserIds.get(user.id)) {
1246 return user;
1247 }
1248 }
1249 return null;
1250 }
1251
1252 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001253 * Mark this guest user for deletion to allow us to create another guest
1254 * and switch to that user before actually removing this guest.
1255 * @param userHandle the userid of the current guest
1256 * @return whether the user could be marked for deletion
1257 */
1258 public boolean markGuestForDeletion(int userHandle) {
1259 checkManageUsersPermission("Only the system can remove users");
1260 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1261 UserManager.DISALLOW_REMOVE_USER, false)) {
1262 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1263 return false;
1264 }
1265
1266 long ident = Binder.clearCallingIdentity();
1267 try {
1268 final UserInfo user;
1269 synchronized (mPackagesLock) {
1270 user = mUsers.get(userHandle);
1271 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1272 return false;
1273 }
1274 if (!user.isGuest()) {
1275 return false;
1276 }
Adam Lesinskieddeb492014-09-08 17:50:03 -07001277 // We set this to a guest user that is to be removed. This is a temporary state
1278 // where we are allowed to add new Guest users, even if this one is still not
1279 // removed. This user will still show up in getUserInfo() calls.
1280 // If we don't get around to removing this Guest user, it will be purged on next
1281 // startup.
1282 user.guestToRemove = true;
Amith Yamasani1df14732014-08-29 21:37:27 -07001283 // Mark it as disabled, so that it isn't returned any more when
1284 // profiles are queried.
1285 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani1df14732014-08-29 21:37:27 -07001286 writeUserLocked(user);
1287 }
1288 } finally {
1289 Binder.restoreCallingIdentity(ident);
1290 }
1291 return true;
1292 }
1293
1294 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001295 * Removes a user and all data directories created for that user. This method should be called
1296 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001297 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001298 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001299 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001300 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001301 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1302 UserManager.DISALLOW_REMOVE_USER, false)) {
1303 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1304 return false;
1305 }
1306
Kenny Guyee58b4f2014-05-23 15:19:53 +01001307 long ident = Binder.clearCallingIdentity();
1308 try {
1309 final UserInfo user;
1310 synchronized (mPackagesLock) {
1311 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001312 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001313 return false;
1314 }
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001315
1316 // We remember deleted user IDs to prevent them from being
1317 // reused during the current boot; they can still be reused
1318 // after a reboot.
Kenny Guyee58b4f2014-05-23 15:19:53 +01001319 mRemovingUserIds.put(userHandle, true);
Jeff Sharkey6eb09392014-11-14 15:57:59 -08001320
Kenny Guyee58b4f2014-05-23 15:19:53 +01001321 try {
1322 mAppOpsService.removeUser(userHandle);
1323 } catch (RemoteException e) {
1324 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1325 }
1326 // Set this to a partially created user, so that the user will be purged
1327 // on next startup, in case the runtime stops now before stopping and
1328 // removing the user completely.
1329 user.partial = true;
1330 // Mark it as disabled, so that it isn't returned any more when
1331 // profiles are queried.
1332 user.flags |= UserInfo.FLAG_DISABLED;
1333 writeUserLocked(user);
1334 }
1335
1336 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1337 && user.isManagedProfile()) {
1338 // Send broadcast to notify system that the user removed was a
1339 // managed user.
1340 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1341 }
1342
1343 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1344 int res;
1345 try {
1346 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1347 new IStopUserCallback.Stub() {
1348 @Override
1349 public void userStopped(int userId) {
1350 finishRemoveUser(userId);
1351 }
1352 @Override
1353 public void userStopAborted(int userId) {
1354 }
1355 });
1356 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001357 return false;
1358 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001359 return res == ActivityManager.USER_OP_SUCCESS;
1360 } finally {
1361 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001362 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001363 }
1364
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001365 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001366 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001367 // Let other services shutdown any activity and clean up their state before completely
1368 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001369 long ident = Binder.clearCallingIdentity();
1370 try {
1371 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1372 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001373 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1374 android.Manifest.permission.MANAGE_USERS,
1375
1376 new BroadcastReceiver() {
1377 @Override
1378 public void onReceive(Context context, Intent intent) {
1379 if (DBG) {
1380 Slog.i(LOG_TAG,
1381 "USER_REMOVED broadcast sent, cleaning up user data "
1382 + userHandle);
1383 }
1384 new Thread() {
1385 public void run() {
1386 synchronized (mInstallLock) {
1387 synchronized (mPackagesLock) {
1388 removeUserStateLocked(userHandle);
1389 }
1390 }
1391 }
1392 }.start();
1393 }
1394 },
1395
1396 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001397 } finally {
1398 Binder.restoreCallingIdentity(ident);
1399 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001400 }
1401
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001402 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001403 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001404 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001405
1406 // Remove this user from the list
1407 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001408
Amith Yamasani655d0e22013-06-12 14:19:10 -07001409 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001410 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001411 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001412 userFile.delete();
1413 // Update the user list
1414 writeUserListLocked();
1415 updateUserIdsLocked();
1416 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1417 }
1418
Amith Yamasani61f57372012-08-31 12:12:28 -07001419 private void removeDirectoryRecursive(File parent) {
1420 if (parent.isDirectory()) {
1421 String[] files = parent.list();
1422 for (String filename : files) {
1423 File child = new File(parent, filename);
1424 removeDirectoryRecursive(child);
1425 }
1426 }
1427 parent.delete();
1428 }
1429
Kenny Guyf8d3a232014-05-15 16:09:52 +01001430 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001431 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001432 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1433 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001434 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1435 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001436 }
1437
Amith Yamasani2a003292012-08-14 18:25:45 -07001438 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001439 public Bundle getApplicationRestrictions(String packageName) {
1440 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1441 }
1442
1443 @Override
1444 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001445 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001446 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001447 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001448 }
1449 synchronized (mPackagesLock) {
1450 // Read the restrictions from XML
1451 return readApplicationRestrictionsLocked(packageName, userId);
1452 }
1453 }
1454
1455 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001456 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001457 int userId) {
1458 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001459 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001460 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001461 }
1462 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001463 if (restrictions == null || restrictions.isEmpty()) {
1464 cleanAppRestrictionsForPackage(packageName, userId);
1465 } else {
1466 // Write the restrictions to XML
1467 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1468 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001469 }
Robin Lee66e5d962014-04-09 16:44:21 +01001470
Kenny Guyd21b2182014-07-17 16:38:55 +01001471 if (isPackageInstalled(packageName, userId)) {
1472 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1473 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1474 changeIntent.setPackage(packageName);
1475 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1476 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1477 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001478 }
1479
Amith Yamasani655d0e22013-06-12 14:19:10 -07001480 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001481 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001482 checkManageUsersPermission("Only system can modify the restrictions pin");
1483 int userId = UserHandle.getCallingUserId();
1484 synchronized (mPackagesLock) {
1485 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1486 if (pinState == null) {
1487 pinState = new RestrictionsPinState();
1488 }
1489 if (newPin == null) {
1490 pinState.salt = 0;
1491 pinState.pinHash = null;
1492 } else {
1493 try {
1494 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1495 } catch (NoSuchAlgorithmException e) {
1496 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1497 }
1498 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1499 pinState.failedAttempts = 0;
1500 }
1501 mRestrictionsPinStates.put(userId, pinState);
1502 writeUserLocked(mUsers.get(userId));
1503 }
1504 return true;
1505 }
1506
1507 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001508 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001509 checkManageUsersPermission("Only system can verify the restrictions pin");
1510 int userId = UserHandle.getCallingUserId();
1511 synchronized (mPackagesLock) {
1512 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1513 // If there's no pin set, return error code
1514 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1515 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1516 } else if (pin == null) {
1517 // If just checking if user can be prompted, return remaining time
1518 int waitTime = getRemainingTimeForPinAttempt(pinState);
1519 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1520 return waitTime;
1521 } else {
1522 int waitTime = getRemainingTimeForPinAttempt(pinState);
1523 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1524 if (waitTime > 0) {
1525 return waitTime;
1526 }
1527 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1528 pinState.failedAttempts = 0;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001529 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001530 return UserManager.PIN_VERIFICATION_SUCCESS;
1531 } else {
1532 pinState.failedAttempts++;
1533 pinState.lastAttemptTime = System.currentTimeMillis();
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001534 scheduleWriteUserLocked(mUsers.get(userId));
Amith Yamasani655d0e22013-06-12 14:19:10 -07001535 return waitTime;
1536 }
1537 }
1538 }
1539 }
1540
1541 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1542 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1543 BACKOFF_TIMES.length - 1);
1544 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1545 BACKOFF_TIMES[backoffIndex] : 0;
1546 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1547 0);
1548 }
1549
1550 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001551 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001552 int userId = UserHandle.getCallingUserId();
1553 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001554 return hasRestrictionsPinLocked(userId);
1555 }
1556 }
1557
1558 private boolean hasRestrictionsPinLocked(int userId) {
1559 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1560 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1561 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001562 }
1563 return true;
1564 }
1565
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001566 @Override
1567 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001568 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001569 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001570 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001571 }
1572
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001573 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001574 synchronized (mPackagesLock) {
1575 // Remove all user restrictions
1576 setUserRestrictions(new Bundle(), userHandle);
1577 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001578 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001579 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001580 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001581 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001582 if (unhideApps) {
1583 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001584 }
1585 }
1586
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001587 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001588 mHandler.post(new Runnable() {
1589 @Override
1590 public void run() {
1591 List<ApplicationInfo> apps =
1592 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1593 userHandle).getList();
1594 final long ident = Binder.clearCallingIdentity();
1595 try {
1596 for (ApplicationInfo appInfo : apps) {
1597 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001598 && (appInfo.flags & ApplicationInfo.FLAG_HIDDEN) != 0) {
1599 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001600 userHandle);
1601 }
1602 }
1603 } finally {
1604 Binder.restoreCallingIdentity(ident);
1605 }
1606 }
1607 });
1608 }
1609
Amith Yamasani655d0e22013-06-12 14:19:10 -07001610 /*
1611 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1612 * Not the most secure, but it is at least a second level of protection. First level is that
1613 * the file is in a location only readable by the system process.
1614 * @param password the password.
1615 * @param salt the randomly generated salt
1616 * @return the hash of the pattern in a String.
1617 */
1618 private String passwordToHash(String password, long salt) {
1619 if (password == null) {
1620 return null;
1621 }
1622 String algo = null;
1623 String hashed = salt + password;
1624 try {
1625 byte[] saltedPassword = (password + salt).getBytes();
1626 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1627 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1628 hashed = toHex(sha1) + toHex(md5);
1629 } catch (NoSuchAlgorithmException e) {
1630 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1631 }
1632 return hashed;
1633 }
1634
1635 private static String toHex(byte[] ary) {
1636 final String hex = "0123456789ABCDEF";
1637 String ret = "";
1638 for (int i = 0; i < ary.length; i++) {
1639 ret += hex.charAt((ary[i] >> 4) & 0xf);
1640 ret += hex.charAt(ary[i] & 0xf);
1641 }
1642 return ret;
1643 }
1644
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001645 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001646 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001647 try {
1648 return mContext.getPackageManager().getApplicationInfo(packageName,
1649 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1650 } catch (NameNotFoundException nnfe) {
1651 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001652 } finally {
1653 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001654 }
1655 }
1656
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001657 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001658 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001659 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001660 final ArrayList<String> values = new ArrayList<String>();
1661
1662 FileInputStream fis = null;
1663 try {
1664 AtomicFile restrictionsFile =
1665 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001666 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001667 fis = restrictionsFile.openRead();
1668 XmlPullParser parser = Xml.newPullParser();
1669 parser.setInput(fis, null);
1670 int type;
1671 while ((type = parser.next()) != XmlPullParser.START_TAG
1672 && type != XmlPullParser.END_DOCUMENT) {
1673 ;
1674 }
1675
1676 if (type != XmlPullParser.START_TAG) {
1677 Slog.e(LOG_TAG, "Unable to read restrictions file "
1678 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001679 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001680 }
1681
1682 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1683 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1684 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001685 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001686 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1687 if (multiple != null) {
Amith Yamasanie0840392014-08-27 10:33:17 -07001688 values.clear();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001689 int count = Integer.parseInt(multiple);
1690 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1691 if (type == XmlPullParser.START_TAG
1692 && parser.getName().equals(TAG_VALUE)) {
1693 values.add(parser.nextText().trim());
1694 count--;
1695 }
1696 }
1697 String [] valueStrings = new String[values.size()];
1698 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001699 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001700 } else {
1701 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001702 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1703 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1704 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1705 restrictions.putInt(key, Integer.parseInt(value));
1706 } else {
1707 restrictions.putString(key, value);
1708 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001709 }
1710 }
1711 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001712 } catch (IOException ioe) {
1713 } catch (XmlPullParserException pe) {
1714 } finally {
1715 if (fis != null) {
1716 try {
1717 fis.close();
1718 } catch (IOException e) {
1719 }
1720 }
1721 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001722 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001723 }
1724
1725 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001726 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001727 FileOutputStream fos = null;
1728 AtomicFile restrictionsFile = new AtomicFile(
1729 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001730 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001731 try {
1732 fos = restrictionsFile.startWrite();
1733 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1734
1735 // XmlSerializer serializer = XmlUtils.serializerInstance();
1736 final XmlSerializer serializer = new FastXmlSerializer();
1737 serializer.setOutput(bos, "utf-8");
1738 serializer.startDocument(null, true);
1739 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1740
1741 serializer.startTag(null, TAG_RESTRICTIONS);
1742
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001743 for (String key : restrictions.keySet()) {
1744 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001745 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001746 serializer.attribute(null, ATTR_KEY, key);
1747
1748 if (value instanceof Boolean) {
1749 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1750 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001751 } else if (value instanceof Integer) {
1752 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1753 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001754 } else if (value == null || value instanceof String) {
1755 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1756 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001757 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001758 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1759 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001760 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001761 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001762 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001763 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001764 serializer.endTag(null, TAG_VALUE);
1765 }
1766 }
1767 serializer.endTag(null, TAG_ENTRY);
1768 }
1769
1770 serializer.endTag(null, TAG_RESTRICTIONS);
1771
1772 serializer.endDocument();
1773 restrictionsFile.finishWrite(fos);
1774 } catch (Exception e) {
1775 restrictionsFile.failWrite(fos);
1776 Slog.e(LOG_TAG, "Error writing application restrictions list");
1777 }
1778 }
1779
1780 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001781 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001782 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001783 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001784 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001785 }
1786 }
1787
1788 @Override
1789 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001790 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001791 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001792 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001793 }
1794 // Not found
1795 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001796 }
1797 }
1798
Amith Yamasani0b285492011-04-14 17:35:23 -07001799 /**
1800 * Caches the list of user ids in an array, adjusting the array size when necessary.
1801 */
Amith Yamasani13593602012-03-22 16:16:17 -07001802 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001803 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001804 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001805 if (!mUsers.valueAt(i).partial) {
1806 num++;
1807 }
1808 }
Amith Yamasani16389312012-10-17 21:20:14 -07001809 final int[] newUsers = new int[num];
1810 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001811 for (int i = 0; i < mUsers.size(); i++) {
1812 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001813 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001814 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001815 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001816 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001817 }
1818
1819 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001820 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001821 * @param userId the user that was just foregrounded
1822 */
1823 public void userForeground(int userId) {
1824 synchronized (mPackagesLock) {
1825 UserInfo user = mUsers.get(userId);
1826 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001827 if (user == null || user.partial) {
1828 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1829 return;
1830 }
1831 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001832 user.lastLoggedInTime = now;
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001833 scheduleWriteUserLocked(user);
Amith Yamasani920ace02012-09-20 22:15:37 -07001834 }
1835 }
1836 }
1837
1838 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001839 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001840 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1841 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001842 * @return
1843 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001844 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001845 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001846 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001847 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001848 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001849 break;
1850 }
1851 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001852 }
Amith Yamasani195263742012-08-21 15:40:12 -07001853 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001854 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001855 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001856
Amith Yamasanifc95e702013-09-26 13:20:17 -07001857 private String packageToRestrictionsFileName(String packageName) {
1858 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1859 }
1860
1861 private String restrictionsFileNameToPackage(String fileName) {
1862 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1863 (int) (fileName.length() - XML_SUFFIX.length()));
1864 }
1865
Amith Yamasani920ace02012-09-20 22:15:37 -07001866 @Override
1867 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1868 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1869 != PackageManager.PERMISSION_GRANTED) {
1870 pw.println("Permission Denial: can't dump UserManager from from pid="
1871 + Binder.getCallingPid()
1872 + ", uid=" + Binder.getCallingUid()
1873 + " without permission "
1874 + android.Manifest.permission.DUMP);
1875 return;
1876 }
1877
1878 long now = System.currentTimeMillis();
1879 StringBuilder sb = new StringBuilder();
1880 synchronized (mPackagesLock) {
1881 pw.println("Users:");
1882 for (int i = 0; i < mUsers.size(); i++) {
1883 UserInfo user = mUsers.valueAt(i);
1884 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001885 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001886 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001887 if (user.partial) pw.print(" <partial>");
1888 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001889 pw.print(" Created: ");
1890 if (user.creationTime == 0) {
1891 pw.println("<unknown>");
1892 } else {
1893 sb.setLength(0);
1894 TimeUtils.formatDuration(now - user.creationTime, sb);
1895 sb.append(" ago");
1896 pw.println(sb);
1897 }
1898 pw.print(" Last logged in: ");
1899 if (user.lastLoggedInTime == 0) {
1900 pw.println("<unknown>");
1901 } else {
1902 sb.setLength(0);
1903 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1904 sb.append(" ago");
1905 pw.println(sb);
1906 }
1907 }
1908 }
1909 }
Fyodor Kupolov75d0ea82014-12-15 16:21:07 -08001910
1911 final class MainHandler extends Handler {
1912
1913 @Override
1914 public void handleMessage(Message msg) {
1915 switch (msg.what) {
1916 case WRITE_USER_MSG:
1917 removeMessages(WRITE_USER_MSG, msg.obj);
1918 synchronized (mPackagesLock) {
1919 int userId = ((UserInfo) msg.obj).id;
1920 UserInfo userInfo = mUsers.get(userId);
1921 if (userInfo != null) {
1922 writeUserLocked(userInfo);
1923 }
1924 }
1925 }
1926 }
1927 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001928}