blob: a06e0410f7ac81a7e4ca434d2b95d6e05ce417bd [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080019import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070020
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070024import android.app.ActivityThread;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani8cd28b52014-06-08 17:54:27 -070037import android.os.Debug;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.RemoteException;
Jason Monk62062992014-05-06 09:55:28 -040044import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070046import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070047import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070048import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.util.Slog;
50import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070052import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070053import android.util.Xml;
54
Jason Monk62062992014-05-06 09:55:28 -040055import com.android.internal.app.IAppOpsService;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import com.android.internal.util.ArrayUtils;
57import com.android.internal.util.FastXmlSerializer;
58
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.BufferedOutputStream;
64import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070067import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import java.io.FileOutputStream;
69import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070071import java.security.MessageDigest;
72import java.security.NoSuchAlgorithmException;
73import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.util.ArrayList;
75import java.util.List;
76
Amith Yamasani258848d2012-08-10 17:06:33 -070077public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani2a003292012-08-14 18:25:45 -070079 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080
Amith Yamasani16389312012-10-17 21:20:14 -070081 private static final boolean DBG = false;
82
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070085 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070087 private static final String ATTR_CREATION_TIME = "created";
88 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070089 private static final String ATTR_SALT = "salt";
90 private static final String ATTR_PIN_HASH = "pinHash";
91 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
92 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070093 private static final String ATTR_SERIAL_NO = "serialNumber";
94 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070095 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070096 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010097 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasanie4afaa32014-06-30 14:55:07 +053098 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700100 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800101 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800102 private static final String TAG_ENTRY = "entry";
103 private static final String TAG_VALUE = "value";
104 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700105 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800106 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700108 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
109 private static final String ATTR_TYPE_STRING = "s";
110 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700111 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700112
Amith Yamasani0b285492011-04-14 17:35:23 -0700113 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700115 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800117 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700118 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800119
Amith Yamasani634cf312012-10-04 17:34:21 -0700120 private static final int MIN_USER_ID = 10;
121
Amith Yamasani5e486f52013-08-07 11:06:44 -0700122 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700123
Amith Yamasani920ace02012-09-20 22:15:37 -0700124 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
125
Amith Yamasani655d0e22013-06-12 14:19:10 -0700126 // Number of attempts before jumping to the next BACKOFF_TIMES slot
127 private static final int BACKOFF_INC_INTERVAL = 5;
128
Amith Yamasani95ab7842014-08-11 17:09:26 -0700129 // Maximum number of managed profiles permitted is 1. This cannot be increased
130 // without first making sure that the rest of the framework is prepared for it.
131 private static final int MAX_MANAGED_PROFILES = 1;
132
Amith Yamasani655d0e22013-06-12 14:19:10 -0700133 // Amount of time to force the user to wait before entering the PIN again, after failing
134 // BACKOFF_INC_INTERVAL times.
135 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
136
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530137
Dianne Hackborn4428e172012-08-24 17:43:05 -0700138 private final Context mContext;
139 private final PackageManagerService mPm;
140 private final Object mInstallLock;
141 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700142
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143 private final Handler mHandler;
144
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 private final File mUsersDir;
146 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700147 private final File mBaseUserPath;
148
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800149 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800150 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530151 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800152
Amith Yamasani655d0e22013-06-12 14:19:10 -0700153 class RestrictionsPinState {
154 long salt;
155 String pinHash;
156 int failedAttempts;
157 long lastAttemptTime;
158 }
159
160 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
161 new SparseArray<RestrictionsPinState>();
162
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800163 /**
164 * Set of user IDs being actively removed. Removed IDs linger in this set
165 * for several seconds to work around a VFS caching issue.
166 */
167 // @GuardedBy("mPackagesLock")
168 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700169
Amith Yamasani0b285492011-04-14 17:35:23 -0700170 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700171 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700172 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700173
Jason Monk62062992014-05-06 09:55:28 -0400174 private IAppOpsService mAppOpsService;
175
Amith Yamasani258848d2012-08-10 17:06:33 -0700176 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700177
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 public static UserManagerService getInstance() {
179 synchronized (UserManagerService.class) {
180 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700182 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700183
184 /**
185 * Available for testing purposes.
186 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700187 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700188 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700189 }
190
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 /**
192 * Called by package manager to create the service. This is closely
193 * associated with the package manager, and the given lock is the
194 * package manager's own lock.
195 */
196 UserManagerService(Context context, PackageManagerService pm,
197 Object installLock, Object packagesLock) {
198 this(context, pm, installLock, packagesLock,
199 Environment.getDataDirectory(),
200 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700201 }
202
Dianne Hackborn4428e172012-08-24 17:43:05 -0700203 /**
204 * Available for testing purposes.
205 */
206 private UserManagerService(Context context, PackageManagerService pm,
207 Object installLock, Object packagesLock,
208 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700209 mContext = context;
210 mPm = pm;
211 mInstallLock = installLock;
212 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800213 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700214 synchronized (mInstallLock) {
215 synchronized (mPackagesLock) {
216 mUsersDir = new File(dataDir, USER_INFO_DIR);
217 mUsersDir.mkdirs();
218 // Make zeroth user directory, for services to migrate their files to that location
219 File userZeroDir = new File(mUsersDir, "0");
220 userZeroDir.mkdirs();
221 mBaseUserPath = baseUserPath;
222 FileUtils.setPermissions(mUsersDir.toString(),
223 FileUtils.S_IRWXU|FileUtils.S_IRWXG
224 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
225 -1, -1);
226 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
227 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700228 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700229 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
230 for (int i = 0; i < mUsers.size(); i++) {
231 UserInfo ui = mUsers.valueAt(i);
232 if (ui.partial && i != 0) {
233 partials.add(ui);
234 }
235 }
236 for (int i = 0; i < partials.size(); i++) {
237 UserInfo ui = partials.get(i);
238 Slog.w(LOG_TAG, "Removing partially created user #" + i
239 + " (name=" + ui.name + ")");
240 removeUserStateLocked(ui.id);
241 }
242 sInstance = this;
243 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700244 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700245 }
246
247 void systemReady() {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700248 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400249 mAppOpsService = IAppOpsService.Stub.asInterface(
250 ServiceManager.getService(Context.APP_OPS_SERVICE));
251 for (int i = 0; i < mUserIds.length; ++i) {
252 try {
253 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
254 } catch (RemoteException e) {
255 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
256 }
257 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700258 }
259
260 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700261 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700262 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700263 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700264 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
265 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700266 UserInfo ui = mUsers.valueAt(i);
267 if (ui.partial) {
268 continue;
269 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800270 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700271 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700272 }
Amith Yamasani13593602012-03-22 16:16:17 -0700273 }
274 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700275 }
Amith Yamasani13593602012-03-22 16:16:17 -0700276 }
277
Amith Yamasani258848d2012-08-10 17:06:33 -0700278 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100279 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800280 if (userId != UserHandle.getCallingUserId()) {
281 checkManageUsersPermission("getting profiles related to user " + userId);
282 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700283 final long ident = Binder.clearCallingIdentity();
284 try {
285 synchronized (mPackagesLock) {
286 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100287 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700288 } finally {
289 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000290 }
291 }
292
Amith Yamasanibe465322014-04-24 13:45:17 -0700293 /** Assume permissions already checked and caller's identity cleared */
294 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700295 UserInfo user = getUserInfoLocked(userId);
296 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
Amith Yamasanidda003f2014-08-28 18:06:51 -0700297 if (user == null) {
298 // Probably a dying user
299 return users;
300 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700301 for (int i = 0; i < mUsers.size(); i++) {
302 UserInfo profile = mUsers.valueAt(i);
303 if (!isProfileOf(user, profile)) {
304 continue;
305 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100306 if (enabledOnly && !profile.isEnabled()) {
307 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700308 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700309 if (mRemovingUserIds.get(profile.id)) {
310 continue;
311 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700312 users.add(profile);
313 }
314 return users;
315 }
316
Jessica Hummelbe81c802014-04-22 15:49:22 +0100317 @Override
318 public UserInfo getProfileParent(int userHandle) {
319 checkManageUsersPermission("get the profile parent");
320 synchronized (mPackagesLock) {
321 UserInfo profile = getUserInfoLocked(userHandle);
322 int parentUserId = profile.profileGroupId;
323 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
324 return null;
325 } else {
326 return getUserInfoLocked(parentUserId);
327 }
328 }
329 }
330
Kenny Guy2a764942014-04-02 13:29:20 +0100331 private boolean isProfileOf(UserInfo user, UserInfo profile) {
332 return user.id == profile.id ||
333 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
334 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000335 }
336
337 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100338 public void setUserEnabled(int userId) {
339 checkManageUsersPermission("enable user");
340 synchronized (mPackagesLock) {
341 UserInfo info = getUserInfoLocked(userId);
342 if (info != null && !info.isEnabled()) {
343 info.flags ^= UserInfo.FLAG_DISABLED;
344 writeUserLocked(info);
345 }
346 }
347 }
348
349 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700350 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700351 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700352 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700353 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700354 }
355 }
356
Amith Yamasani71e6c692013-03-24 17:39:28 -0700357 @Override
358 public boolean isRestricted() {
359 synchronized (mPackagesLock) {
360 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
361 }
362 }
363
Amith Yamasani195263742012-08-21 15:40:12 -0700364 /*
365 * Should be locked on mUsers before calling this.
366 */
367 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700368 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700369 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800370 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700371 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
372 return null;
373 }
374 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700375 }
376
Amith Yamasani13593602012-03-22 16:16:17 -0700377 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700378 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700379 return ArrayUtils.contains(mUserIds, userId);
380 }
381 }
382
Amith Yamasani258848d2012-08-10 17:06:33 -0700383 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700384 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700385 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700386 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700387 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700388 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700389 if (info == null || info.partial) {
390 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
391 return;
392 }
Amith Yamasani13593602012-03-22 16:16:17 -0700393 if (name != null && !name.equals(info.name)) {
394 info.name = name;
395 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700396 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700397 }
398 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700399 if (changed) {
400 sendUserInfoChangedBroadcast(userId);
401 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700402 }
403
Amith Yamasani258848d2012-08-10 17:06:33 -0700404 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700405 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700406 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400407 long ident = Binder.clearCallingIdentity();
408 try {
409 synchronized (mPackagesLock) {
410 UserInfo info = mUsers.get(userId);
411 if (info == null || info.partial) {
412 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
413 return;
414 }
415 writeBitmapLocked(info, bitmap);
416 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700417 }
Jason Monk9a944532014-07-08 09:31:21 -0400418 sendUserInfoChangedBroadcast(userId);
419 } finally {
420 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700421 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700422 }
423
424 private void sendUserInfoChangedBroadcast(int userId) {
425 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
426 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
427 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700428 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700429 }
430
Amith Yamasani258848d2012-08-10 17:06:33 -0700431 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700432 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700433 synchronized (mPackagesLock) {
434 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700435 if (info == null || info.partial) {
436 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
437 return null;
438 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100439 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
440 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
441 || callingGroupId != info.profileGroupId) {
442 checkManageUsersPermission("get the icon of a user who is not related");
443 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700444 if (info.iconPath == null) {
445 return null;
446 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700447 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700448 }
449 }
450
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700451 public void makeInitialized(int userId) {
452 checkManageUsersPermission("makeInitialized");
453 synchronized (mPackagesLock) {
454 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700455 if (info == null || info.partial) {
456 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
457 }
458 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700459 info.flags |= UserInfo.FLAG_INITIALIZED;
460 writeUserLocked(info);
461 }
462 }
463 }
464
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800465 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530466 public Bundle getDefaultGuestRestrictions() {
467 checkManageUsersPermission("getDefaultGuestRestrictions");
468 synchronized (mPackagesLock) {
469 return new Bundle(mGuestRestrictions);
470 }
471 }
472
473 @Override
474 public void setDefaultGuestRestrictions(Bundle restrictions) {
475 checkManageUsersPermission("setDefaultGuestRestrictions");
476 synchronized (mPackagesLock) {
477 mGuestRestrictions.clear();
478 mGuestRestrictions.putAll(restrictions);
479 writeUserListLocked();
480 }
481 }
482
483 @Override
Amith Yamasani8cd28b52014-06-08 17:54:27 -0700484 public boolean hasUserRestriction(String restrictionKey, int userId) {
485 synchronized (mPackagesLock) {
486 Bundle restrictions = mUserRestrictions.get(userId);
487 return restrictions != null ? restrictions.getBoolean(restrictionKey) : false;
488 }
489 }
490
491 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800492 public Bundle getUserRestrictions(int userId) {
493 // checkManageUsersPermission("getUserRestrictions");
494
495 synchronized (mPackagesLock) {
496 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700497 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800498 }
499 }
500
501 @Override
502 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700503 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700504 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800505
506 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700507 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800508 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400509 long token = Binder.clearCallingIdentity();
510 try {
511 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
512 } catch (RemoteException e) {
513 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
514 } finally {
515 Binder.restoreCallingIdentity(token);
516 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800517 writeUserLocked(mUsers.get(userId));
518 }
519 }
520
Amith Yamasani258848d2012-08-10 17:06:33 -0700521 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700522 * Check if we've hit the limit of how many users can be created.
523 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700524 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700525 int aliveUserCount = 0;
526 final int totalUserCount = mUsers.size();
527 // Skip over users being removed
528 for (int i = 0; i < totalUserCount; i++) {
529 UserInfo user = mUsers.valueAt(i);
Amith Yamasani95ab7842014-08-11 17:09:26 -0700530 if (!mRemovingUserIds.get(user.id)
Amith Yamasani1df14732014-08-29 21:37:27 -0700531 && !user.isGuest() && !user.partial) {
Amith Yamasanif584f012014-05-19 17:57:25 -0700532 aliveUserCount++;
533 }
534 }
535 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700536 }
537
538 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700539 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700540 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700541 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700542 *
543 * @param message used as message if SecurityException is thrown
544 * @throws SecurityException if the caller is not system or root
545 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700546 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700547 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700548 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400549 && ActivityManager.checkComponentPermission(
550 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700551 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
552 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
553 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400554 }
555
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700556 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700557 try {
558 File dir = new File(mUsersDir, Integer.toString(info.id));
559 File file = new File(dir, USER_PHOTO_FILENAME);
560 if (!dir.exists()) {
561 dir.mkdir();
562 FileUtils.setPermissions(
563 dir.getPath(),
564 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
565 -1, -1);
566 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700567 FileOutputStream os;
568 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700569 info.iconPath = file.getAbsolutePath();
570 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700571 try {
572 os.close();
573 } catch (IOException ioe) {
574 // What the ... !
575 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700576 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700577 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700578 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700579 }
580
Amith Yamasani0b285492011-04-14 17:35:23 -0700581 /**
582 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
583 * cache it elsewhere.
584 * @return the array of user ids.
585 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700586 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700587 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700588 return mUserIds;
589 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700590 }
591
Dianne Hackborn4428e172012-08-24 17:43:05 -0700592 int[] getUserIdsLPr() {
593 return mUserIds;
594 }
595
Amith Yamasani13593602012-03-22 16:16:17 -0700596 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700597 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700598 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700599 return;
600 }
601 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700602 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700603 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700604 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700605 XmlPullParser parser = Xml.newPullParser();
606 parser.setInput(fis, null);
607 int type;
608 while ((type = parser.next()) != XmlPullParser.START_TAG
609 && type != XmlPullParser.END_DOCUMENT) {
610 ;
611 }
612
613 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700614 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700615 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700616 return;
617 }
618
Amith Yamasani2a003292012-08-14 18:25:45 -0700619 mNextSerialNumber = -1;
620 if (parser.getName().equals(TAG_USERS)) {
621 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
622 if (lastSerialNumber != null) {
623 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
624 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700625 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
626 if (versionNumber != null) {
627 mUserVersion = Integer.parseInt(versionNumber);
628 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700629 }
630
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700631 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530632 if (type == XmlPullParser.START_TAG) {
633 final String name = parser.getName();
634 if (name.equals(TAG_USER)) {
635 String id = parser.getAttributeValue(null, ATTR_ID);
636 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700637
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530638 if (user != null) {
639 mUsers.put(user.id, user);
640 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
641 mNextSerialNumber = user.id + 1;
642 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700643 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530644 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
645 mGuestRestrictions.clear();
646 readRestrictionsLocked(parser, mGuestRestrictions);
Amith Yamasani258848d2012-08-10 17:06:33 -0700647 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700648 }
649 }
Amith Yamasani13593602012-03-22 16:16:17 -0700650 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700651 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700652 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700653 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700654 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700655 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800656 } finally {
657 if (fis != null) {
658 try {
659 fis.close();
660 } catch (IOException e) {
661 }
662 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700663 }
664 }
665
Amith Yamasani6f34b412012-10-22 18:19:27 -0700666 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800667 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700668 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700669 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700670 int userVersion = mUserVersion;
671 if (userVersion < 1) {
672 // Assign a proper name for the owner, if not initialized correctly before
673 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
674 if ("Primary".equals(user.name)) {
675 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
676 writeUserLocked(user);
677 }
678 userVersion = 1;
679 }
680
Amith Yamasanibc9625052012-11-15 14:39:18 -0800681 if (userVersion < 2) {
682 // Owner should be marked as initialized
683 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
684 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
685 user.flags |= UserInfo.FLAG_INITIALIZED;
686 writeUserLocked(user);
687 }
688 userVersion = 2;
689 }
690
Amith Yamasani350962c2013-08-06 11:18:53 -0700691
Amith Yamasani5e486f52013-08-07 11:06:44 -0700692 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700693 userVersion = 4;
694 }
695
Amith Yamasani6f34b412012-10-22 18:19:27 -0700696 if (userVersion < USER_VERSION) {
697 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
698 + USER_VERSION);
699 } else {
700 mUserVersion = userVersion;
701 writeUserListLocked();
702 }
703 }
704
Amith Yamasani13593602012-03-22 16:16:17 -0700705 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700706 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800707 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700708 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700709 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700710 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700711 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400712 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800713
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500714 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800715 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
716
Amith Yamasani13593602012-03-22 16:16:17 -0700717 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700718
Amith Yamasani13593602012-03-22 16:16:17 -0700719 writeUserListLocked();
720 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700721 }
722
723 /*
724 * Writes the user file in this format:
725 *
726 * <user flags="20039023" id="0">
727 * <name>Primary</name>
728 * </user>
729 */
Amith Yamasani13593602012-03-22 16:16:17 -0700730 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700731 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700732 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700733 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700734 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700735 final BufferedOutputStream bos = new BufferedOutputStream(fos);
736
737 // XmlSerializer serializer = XmlUtils.serializerInstance();
738 final XmlSerializer serializer = new FastXmlSerializer();
739 serializer.setOutput(bos, "utf-8");
740 serializer.startDocument(null, true);
741 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
742
743 serializer.startTag(null, TAG_USER);
744 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700745 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700746 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700747 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
748 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
749 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700750 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
751 if (pinState != null) {
752 if (pinState.salt != 0) {
753 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
754 }
755 if (pinState.pinHash != null) {
756 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
757 }
758 if (pinState.failedAttempts != 0) {
759 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
760 Integer.toString(pinState.failedAttempts));
761 serializer.attribute(null, ATTR_LAST_RETRY_MS,
762 Long.toString(pinState.lastAttemptTime));
763 }
764 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700765 if (userInfo.iconPath != null) {
766 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
767 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700768 if (userInfo.partial) {
769 serializer.attribute(null, ATTR_PARTIAL, "true");
770 }
Kenny Guy2a764942014-04-02 13:29:20 +0100771 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
772 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
773 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000774 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700775
776 serializer.startTag(null, TAG_NAME);
777 serializer.text(userInfo.name);
778 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800779 Bundle restrictions = mUserRestrictions.get(userInfo.id);
780 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530781 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800782 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700783 serializer.endTag(null, TAG_USER);
784
785 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700786 userFile.finishWrite(fos);
787 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700788 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700789 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700790 }
791 }
792
793 /*
794 * Writes the user list file in this format:
795 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700796 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700797 * <user id="0"></user>
798 * <user id="2"></user>
799 * </users>
800 */
Amith Yamasani13593602012-03-22 16:16:17 -0700801 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700802 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700803 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700804 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700805 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700806 final BufferedOutputStream bos = new BufferedOutputStream(fos);
807
808 // XmlSerializer serializer = XmlUtils.serializerInstance();
809 final XmlSerializer serializer = new FastXmlSerializer();
810 serializer.setOutput(bos, "utf-8");
811 serializer.startDocument(null, true);
812 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
813
814 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700815 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700816 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530818 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
819 writeRestrictionsLocked(serializer, mGuestRestrictions);
820 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700821 for (int i = 0; i < mUsers.size(); i++) {
822 UserInfo user = mUsers.valueAt(i);
823 serializer.startTag(null, TAG_USER);
824 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
825 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700826 }
827
828 serializer.endTag(null, TAG_USERS);
829
830 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700831 userListFile.finishWrite(fos);
832 } catch (Exception e) {
833 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700834 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700835 }
836 }
837
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530838 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
839 throws IOException {
840 serializer.startTag(null, TAG_RESTRICTIONS);
841 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
842 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
843 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
844 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
845 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
846 writeBoolean(serializer, restrictions,
847 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
848 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
849 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
850 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
851 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
852 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
853 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
854 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
855 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
856 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
857 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
858 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
859 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
860 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
861 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
862 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
863 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -0700864 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
865 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -0400866 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -0700867 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
868 writeBoolean(serializer, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530869 serializer.endTag(null, TAG_RESTRICTIONS);
870 }
871
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800872 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700873 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700874 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700875 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700876 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700877 long creationTime = 0L;
878 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700879 long salt = 0L;
880 String pinHash = null;
881 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100882 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700883 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700884 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800885 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700886
887 FileInputStream fis = null;
888 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700889 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700890 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700891 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700892 XmlPullParser parser = Xml.newPullParser();
893 parser.setInput(fis, null);
894 int type;
895 while ((type = parser.next()) != XmlPullParser.START_TAG
896 && type != XmlPullParser.END_DOCUMENT) {
897 ;
898 }
899
900 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700901 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700902 return null;
903 }
904
905 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700906 int storedId = readIntAttribute(parser, ATTR_ID, -1);
907 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700908 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700909 return null;
910 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700911 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
912 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700913 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700914 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
915 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700916 salt = readLongAttribute(parser, ATTR_SALT, 0L);
917 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
918 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
919 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100920 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
921 UserInfo.NO_PROFILE_GROUP_ID);
922 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
923 // This attribute was added and renamed during development of L.
924 // TODO Remove upgrade path by 1st May 2014
925 profileGroupId = readIntAttribute(parser, "relatedGroupId",
926 UserInfo.NO_PROFILE_GROUP_ID);
927 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700928 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
929 if ("true".equals(valueString)) {
930 partial = true;
931 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700932
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800933 int outerDepth = parser.getDepth();
934 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
935 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
936 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
937 continue;
938 }
939 String tag = parser.getName();
940 if (TAG_NAME.equals(tag)) {
941 type = parser.next();
942 if (type == XmlPullParser.TEXT) {
943 name = parser.getText();
944 }
945 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530946 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947 }
948 }
949 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700950
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700951 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700952 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700953 userInfo.creationTime = creationTime;
954 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700955 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100956 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800957 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700958 if (salt != 0L) {
959 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
960 if (pinState == null) {
961 pinState = new RestrictionsPinState();
962 mRestrictionsPinStates.put(id, pinState);
963 }
964 pinState.salt = salt;
965 pinState.pinHash = pinHash;
966 pinState.failedAttempts = failedAttempts;
967 pinState.lastAttemptTime = lastAttemptTime;
968 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700969 return userInfo;
970
971 } catch (IOException ioe) {
972 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800973 } finally {
974 if (fis != null) {
975 try {
976 fis.close();
977 } catch (IOException e) {
978 }
979 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700980 }
981 return null;
982 }
983
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530984 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
985 throws IOException {
986 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
987 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
988 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
989 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
990 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
991 readBoolean(parser, restrictions,
992 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
993 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
994 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
995 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
996 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
997 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
998 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
999 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
1000 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
1001 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
1002 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
1003 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
1004 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
1005 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
1006 readBoolean(parser, restrictions,
1007 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
1008 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1009 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani390989d2014-07-17 10:52:03 -07001010 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_CALLS);
1011 readBoolean(parser, restrictions, UserManager.DISALLOW_SMS);
Jason Monk1c7c3192014-06-26 12:52:18 -04001012 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasani26af8292014-09-09 09:57:27 -07001013 readBoolean(parser, restrictions, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
1014 readBoolean(parser, restrictions, UserManager.DISALLOW_OUTGOING_BEAM);
Amith Yamasanie4afaa32014-06-30 14:55:07 +05301015 }
1016
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001017 private void readBoolean(XmlPullParser parser, Bundle restrictions,
1018 String restrictionKey) {
1019 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -07001020 if (value != null) {
1021 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1022 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001023 }
1024
1025 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1026 throws IOException {
1027 if (restrictions.containsKey(restrictionKey)) {
1028 xml.attribute(null, restrictionKey,
1029 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1030 }
1031 }
1032
Amith Yamasani920ace02012-09-20 22:15:37 -07001033 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1034 String valueString = parser.getAttributeValue(null, attr);
1035 if (valueString == null) return defaultValue;
1036 try {
1037 return Integer.parseInt(valueString);
1038 } catch (NumberFormatException nfe) {
1039 return defaultValue;
1040 }
1041 }
1042
1043 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1044 String valueString = parser.getAttributeValue(null, attr);
1045 if (valueString == null) return defaultValue;
1046 try {
1047 return Long.parseLong(valueString);
1048 } catch (NumberFormatException nfe) {
1049 return defaultValue;
1050 }
1051 }
1052
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001053 private boolean isPackageInstalled(String pkg, int userId) {
1054 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1055 PackageManager.GET_UNINSTALLED_PACKAGES,
1056 userId);
1057 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1058 return false;
1059 }
1060 return true;
1061 }
1062
Amith Yamasanib82add22013-07-09 11:24:44 -07001063 /**
Kenny Guyd21b2182014-07-17 16:38:55 +01001064 * Removes all the restrictions files (res_<packagename>) for a given user.
Amith Yamasanib82add22013-07-09 11:24:44 -07001065 * Does not do any permissions checking.
1066 */
Kenny Guyd21b2182014-07-17 16:38:55 +01001067 private void cleanAppRestrictions(int userId) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001068 synchronized (mPackagesLock) {
1069 File dir = Environment.getUserSystemDirectory(userId);
1070 String[] files = dir.list();
1071 if (files == null) return;
1072 for (String fileName : files) {
1073 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1074 File resFile = new File(dir, fileName);
1075 if (resFile.exists()) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001076 resFile.delete();
Amith Yamasanib82add22013-07-09 11:24:44 -07001077 }
1078 }
1079 }
1080 }
1081 }
1082
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001083 /**
1084 * Removes the app restrictions file for a specific package and user id, if it exists.
1085 */
1086 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1087 synchronized (mPackagesLock) {
1088 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001089 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001090 if (resFile.exists()) {
1091 resFile.delete();
1092 }
1093 }
1094 }
1095
Kenny Guya52dc3e2014-02-11 15:33:14 +00001096 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001097 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001098 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001099 if (userId != UserHandle.USER_OWNER) {
1100 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001101 return null;
1102 }
Kenny Guy2a764942014-04-02 13:29:20 +01001103 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001104 }
1105
Amith Yamasani258848d2012-08-10 17:06:33 -07001106 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001107 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001108 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001109 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001110 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001111
Jessica Hummelbe81c802014-04-22 15:49:22 +01001112 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001113 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1114 UserManager.DISALLOW_ADD_USER, false)) {
1115 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1116 return null;
1117 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001118 final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001119 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001120 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001121 try {
1122 synchronized (mInstallLock) {
1123 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001124 UserInfo parent = null;
1125 if (parentId != UserHandle.USER_NULL) {
1126 parent = getUserInfoLocked(parentId);
1127 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001128 }
Amith Yamasani95ab7842014-08-11 17:09:26 -07001129 // If we're not adding a guest user and the limit has been reached,
1130 // cannot add a user.
1131 if (!isGuest && isUserLimitReachedLocked()) {
1132 return null;
1133 }
1134 // If we're adding a guest and there already exists one, bail.
1135 if (isGuest && numberOfUsersOfTypeLocked(UserInfo.FLAG_GUEST, true) > 0) {
1136 return null;
1137 }
1138 // Limit number of managed profiles that can be created
1139 if ((flags & UserInfo.FLAG_MANAGED_PROFILE) != 0
1140 && numberOfUsersOfTypeLocked(UserInfo.FLAG_MANAGED_PROFILE, true)
1141 >= MAX_MANAGED_PROFILES) {
1142 return null;
1143 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001144 int userId = getNextAvailableIdLocked();
1145 userInfo = new UserInfo(userId, name, null, flags);
1146 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1147 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001148 long now = System.currentTimeMillis();
1149 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001150 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001151 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001152 mUsers.put(userId, userInfo);
1153 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001154 if (parent != null) {
1155 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1156 parent.profileGroupId = parent.id;
1157 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001158 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001159 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001160 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001161 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001162 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001163 userInfo.partial = false;
1164 writeUserLocked(userInfo);
1165 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001166 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001167 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001168 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001169 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001170 if (userInfo != null) {
1171 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1172 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1173 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1174 android.Manifest.permission.MANAGE_USERS);
1175 }
1176 } finally {
1177 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001178 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001179 return userInfo;
1180 }
1181
Amith Yamasani95ab7842014-08-11 17:09:26 -07001182 private int numberOfUsersOfTypeLocked(int flags, boolean excludeDying) {
1183 int count = 0;
1184 for (int i = mUsers.size() - 1; i >= 0; i--) {
1185 UserInfo user = mUsers.valueAt(i);
1186 if (!excludeDying || !mRemovingUserIds.get(user.id)) {
1187 if ((user.flags & flags) != 0) {
1188 count++;
1189 }
1190 }
1191 }
1192 return count;
1193 }
1194
Amith Yamasani0b285492011-04-14 17:35:23 -07001195 /**
Amith Yamasani1df14732014-08-29 21:37:27 -07001196 * Mark this guest user for deletion to allow us to create another guest
1197 * and switch to that user before actually removing this guest.
1198 * @param userHandle the userid of the current guest
1199 * @return whether the user could be marked for deletion
1200 */
1201 public boolean markGuestForDeletion(int userHandle) {
1202 checkManageUsersPermission("Only the system can remove users");
1203 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1204 UserManager.DISALLOW_REMOVE_USER, false)) {
1205 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1206 return false;
1207 }
1208
1209 long ident = Binder.clearCallingIdentity();
1210 try {
1211 final UserInfo user;
1212 synchronized (mPackagesLock) {
1213 user = mUsers.get(userHandle);
1214 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
1215 return false;
1216 }
1217 if (!user.isGuest()) {
1218 return false;
1219 }
1220 // Set this to a partially created user, so that the user will be purged
1221 // on next startup, in case the runtime stops now before stopping and
1222 // removing the user completely.
1223 user.partial = true;
1224 // Mark it as disabled, so that it isn't returned any more when
1225 // profiles are queried.
1226 user.flags |= UserInfo.FLAG_DISABLED;
1227 user.flags &= ~UserInfo.FLAG_GUEST;
1228 writeUserLocked(user);
1229 }
1230 } finally {
1231 Binder.restoreCallingIdentity(ident);
1232 }
1233 return true;
1234 }
1235
1236 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001237 * Removes a user and all data directories created for that user. This method should be called
1238 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001239 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001240 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001241 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001242 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001243 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1244 UserManager.DISALLOW_REMOVE_USER, false)) {
1245 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1246 return false;
1247 }
1248
Kenny Guyee58b4f2014-05-23 15:19:53 +01001249 long ident = Binder.clearCallingIdentity();
1250 try {
1251 final UserInfo user;
1252 synchronized (mPackagesLock) {
1253 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001254 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001255 return false;
1256 }
1257 mRemovingUserIds.put(userHandle, true);
1258 try {
1259 mAppOpsService.removeUser(userHandle);
1260 } catch (RemoteException e) {
1261 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1262 }
1263 // Set this to a partially created user, so that the user will be purged
1264 // on next startup, in case the runtime stops now before stopping and
1265 // removing the user completely.
1266 user.partial = true;
1267 // Mark it as disabled, so that it isn't returned any more when
1268 // profiles are queried.
1269 user.flags |= UserInfo.FLAG_DISABLED;
1270 writeUserLocked(user);
1271 }
1272
1273 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1274 && user.isManagedProfile()) {
1275 // Send broadcast to notify system that the user removed was a
1276 // managed user.
1277 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1278 }
1279
1280 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1281 int res;
1282 try {
1283 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1284 new IStopUserCallback.Stub() {
1285 @Override
1286 public void userStopped(int userId) {
1287 finishRemoveUser(userId);
1288 }
1289 @Override
1290 public void userStopAborted(int userId) {
1291 }
1292 });
1293 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001294 return false;
1295 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001296 return res == ActivityManager.USER_OP_SUCCESS;
1297 } finally {
1298 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001299 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001300 }
1301
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001302 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001303 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001304 // Let other services shutdown any activity and clean up their state before completely
1305 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001306 long ident = Binder.clearCallingIdentity();
1307 try {
1308 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1309 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001310 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1311 android.Manifest.permission.MANAGE_USERS,
1312
1313 new BroadcastReceiver() {
1314 @Override
1315 public void onReceive(Context context, Intent intent) {
1316 if (DBG) {
1317 Slog.i(LOG_TAG,
1318 "USER_REMOVED broadcast sent, cleaning up user data "
1319 + userHandle);
1320 }
1321 new Thread() {
1322 public void run() {
1323 synchronized (mInstallLock) {
1324 synchronized (mPackagesLock) {
1325 removeUserStateLocked(userHandle);
1326 }
1327 }
1328 }
1329 }.start();
1330 }
1331 },
1332
1333 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001334 } finally {
1335 Binder.restoreCallingIdentity(ident);
1336 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001337 }
1338
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001339 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001340 // Cleanup package manager settings
Amith Yamasanidda003f2014-08-28 18:06:51 -07001341 mPm.cleanUpUserLILPw(this, userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001342
1343 // Remove this user from the list
1344 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001345
1346 // Have user ID linger for several seconds to let external storage VFS
1347 // cache entries expire. This must be greater than the 'entry_valid'
1348 // timeout used by the FUSE daemon.
1349 mHandler.postDelayed(new Runnable() {
1350 @Override
1351 public void run() {
1352 synchronized (mPackagesLock) {
1353 mRemovingUserIds.delete(userHandle);
1354 }
1355 }
1356 }, MINUTE_IN_MILLIS);
1357
Amith Yamasani655d0e22013-06-12 14:19:10 -07001358 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001359 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001360 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001361 userFile.delete();
1362 // Update the user list
1363 writeUserListLocked();
1364 updateUserIdsLocked();
1365 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1366 }
1367
Amith Yamasani61f57372012-08-31 12:12:28 -07001368 private void removeDirectoryRecursive(File parent) {
1369 if (parent.isDirectory()) {
1370 String[] files = parent.list();
1371 for (String filename : files) {
1372 File child = new File(parent, filename);
1373 removeDirectoryRecursive(child);
1374 }
1375 }
1376 parent.delete();
1377 }
1378
Kenny Guyf8d3a232014-05-15 16:09:52 +01001379 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001380 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001381 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1382 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001383 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1384 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001385 }
1386
Amith Yamasani2a003292012-08-14 18:25:45 -07001387 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001388 public Bundle getApplicationRestrictions(String packageName) {
1389 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1390 }
1391
1392 @Override
1393 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001394 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001395 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001396 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001397 }
1398 synchronized (mPackagesLock) {
1399 // Read the restrictions from XML
1400 return readApplicationRestrictionsLocked(packageName, userId);
1401 }
1402 }
1403
1404 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001405 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001406 int userId) {
1407 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001408 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001409 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001410 }
1411 synchronized (mPackagesLock) {
Kenny Guyd21b2182014-07-17 16:38:55 +01001412 if (restrictions == null || restrictions.isEmpty()) {
1413 cleanAppRestrictionsForPackage(packageName, userId);
1414 } else {
1415 // Write the restrictions to XML
1416 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1417 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001418 }
Robin Lee66e5d962014-04-09 16:44:21 +01001419
Kenny Guyd21b2182014-07-17 16:38:55 +01001420 if (isPackageInstalled(packageName, userId)) {
1421 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1422 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1423 changeIntent.setPackage(packageName);
1424 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1425 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
1426 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001427 }
1428
Amith Yamasani655d0e22013-06-12 14:19:10 -07001429 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001430 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001431 checkManageUsersPermission("Only system can modify the restrictions pin");
1432 int userId = UserHandle.getCallingUserId();
1433 synchronized (mPackagesLock) {
1434 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1435 if (pinState == null) {
1436 pinState = new RestrictionsPinState();
1437 }
1438 if (newPin == null) {
1439 pinState.salt = 0;
1440 pinState.pinHash = null;
1441 } else {
1442 try {
1443 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1444 } catch (NoSuchAlgorithmException e) {
1445 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1446 }
1447 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1448 pinState.failedAttempts = 0;
1449 }
1450 mRestrictionsPinStates.put(userId, pinState);
1451 writeUserLocked(mUsers.get(userId));
1452 }
1453 return true;
1454 }
1455
1456 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001457 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001458 checkManageUsersPermission("Only system can verify the restrictions pin");
1459 int userId = UserHandle.getCallingUserId();
1460 synchronized (mPackagesLock) {
1461 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1462 // If there's no pin set, return error code
1463 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1464 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1465 } else if (pin == null) {
1466 // If just checking if user can be prompted, return remaining time
1467 int waitTime = getRemainingTimeForPinAttempt(pinState);
1468 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1469 return waitTime;
1470 } else {
1471 int waitTime = getRemainingTimeForPinAttempt(pinState);
1472 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1473 if (waitTime > 0) {
1474 return waitTime;
1475 }
1476 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1477 pinState.failedAttempts = 0;
1478 writeUserLocked(mUsers.get(userId));
1479 return UserManager.PIN_VERIFICATION_SUCCESS;
1480 } else {
1481 pinState.failedAttempts++;
1482 pinState.lastAttemptTime = System.currentTimeMillis();
1483 writeUserLocked(mUsers.get(userId));
1484 return waitTime;
1485 }
1486 }
1487 }
1488 }
1489
1490 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1491 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1492 BACKOFF_TIMES.length - 1);
1493 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1494 BACKOFF_TIMES[backoffIndex] : 0;
1495 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1496 0);
1497 }
1498
1499 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001500 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001501 int userId = UserHandle.getCallingUserId();
1502 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001503 return hasRestrictionsPinLocked(userId);
1504 }
1505 }
1506
1507 private boolean hasRestrictionsPinLocked(int userId) {
1508 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1509 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1510 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001511 }
1512 return true;
1513 }
1514
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001515 @Override
1516 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001517 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001518 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001519 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001520 }
1521
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001522 private void removeRestrictionsForUser(final int userHandle, boolean unhideApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001523 synchronized (mPackagesLock) {
1524 // Remove all user restrictions
1525 setUserRestrictions(new Bundle(), userHandle);
1526 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001527 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001528 // Remove any app restrictions
Kenny Guyd21b2182014-07-17 16:38:55 +01001529 cleanAppRestrictions(userHandle);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001530 }
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001531 if (unhideApps) {
1532 unhideAllInstalledAppsForUser(userHandle);
Amith Yamasani5e486f52013-08-07 11:06:44 -07001533 }
1534 }
1535
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001536 private void unhideAllInstalledAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001537 mHandler.post(new Runnable() {
1538 @Override
1539 public void run() {
1540 List<ApplicationInfo> apps =
1541 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1542 userHandle).getList();
1543 final long ident = Binder.clearCallingIdentity();
1544 try {
1545 for (ApplicationInfo appInfo : apps) {
1546 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
Amith Yamasanie5bcff62014-07-19 15:44:09 -07001547 && (appInfo.flags & ApplicationInfo.FLAG_HIDDEN) != 0) {
1548 mPm.setApplicationHiddenSettingAsUser(appInfo.packageName, false,
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001549 userHandle);
1550 }
1551 }
1552 } finally {
1553 Binder.restoreCallingIdentity(ident);
1554 }
1555 }
1556 });
1557 }
1558
Amith Yamasani655d0e22013-06-12 14:19:10 -07001559 /*
1560 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1561 * Not the most secure, but it is at least a second level of protection. First level is that
1562 * the file is in a location only readable by the system process.
1563 * @param password the password.
1564 * @param salt the randomly generated salt
1565 * @return the hash of the pattern in a String.
1566 */
1567 private String passwordToHash(String password, long salt) {
1568 if (password == null) {
1569 return null;
1570 }
1571 String algo = null;
1572 String hashed = salt + password;
1573 try {
1574 byte[] saltedPassword = (password + salt).getBytes();
1575 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1576 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1577 hashed = toHex(sha1) + toHex(md5);
1578 } catch (NoSuchAlgorithmException e) {
1579 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1580 }
1581 return hashed;
1582 }
1583
1584 private static String toHex(byte[] ary) {
1585 final String hex = "0123456789ABCDEF";
1586 String ret = "";
1587 for (int i = 0; i < ary.length; i++) {
1588 ret += hex.charAt((ary[i] >> 4) & 0xf);
1589 ret += hex.charAt(ary[i] & 0xf);
1590 }
1591 return ret;
1592 }
1593
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001594 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001595 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001596 try {
1597 return mContext.getPackageManager().getApplicationInfo(packageName,
1598 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1599 } catch (NameNotFoundException nnfe) {
1600 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001601 } finally {
1602 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001603 }
1604 }
1605
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001606 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001607 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001608 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001609 final ArrayList<String> values = new ArrayList<String>();
1610
1611 FileInputStream fis = null;
1612 try {
1613 AtomicFile restrictionsFile =
1614 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001615 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001616 fis = restrictionsFile.openRead();
1617 XmlPullParser parser = Xml.newPullParser();
1618 parser.setInput(fis, null);
1619 int type;
1620 while ((type = parser.next()) != XmlPullParser.START_TAG
1621 && type != XmlPullParser.END_DOCUMENT) {
1622 ;
1623 }
1624
1625 if (type != XmlPullParser.START_TAG) {
1626 Slog.e(LOG_TAG, "Unable to read restrictions file "
1627 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001628 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001629 }
1630
1631 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1632 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1633 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001634 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001635 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1636 if (multiple != null) {
Amith Yamasanie0840392014-08-27 10:33:17 -07001637 values.clear();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001638 int count = Integer.parseInt(multiple);
1639 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1640 if (type == XmlPullParser.START_TAG
1641 && parser.getName().equals(TAG_VALUE)) {
1642 values.add(parser.nextText().trim());
1643 count--;
1644 }
1645 }
1646 String [] valueStrings = new String[values.size()];
1647 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001648 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001649 } else {
1650 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001651 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1652 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1653 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1654 restrictions.putInt(key, Integer.parseInt(value));
1655 } else {
1656 restrictions.putString(key, value);
1657 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001658 }
1659 }
1660 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001661 } catch (IOException ioe) {
1662 } catch (XmlPullParserException pe) {
1663 } finally {
1664 if (fis != null) {
1665 try {
1666 fis.close();
1667 } catch (IOException e) {
1668 }
1669 }
1670 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001671 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001672 }
1673
1674 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001675 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001676 FileOutputStream fos = null;
1677 AtomicFile restrictionsFile = new AtomicFile(
1678 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001679 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001680 try {
1681 fos = restrictionsFile.startWrite();
1682 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1683
1684 // XmlSerializer serializer = XmlUtils.serializerInstance();
1685 final XmlSerializer serializer = new FastXmlSerializer();
1686 serializer.setOutput(bos, "utf-8");
1687 serializer.startDocument(null, true);
1688 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1689
1690 serializer.startTag(null, TAG_RESTRICTIONS);
1691
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001692 for (String key : restrictions.keySet()) {
1693 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001694 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001695 serializer.attribute(null, ATTR_KEY, key);
1696
1697 if (value instanceof Boolean) {
1698 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1699 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001700 } else if (value instanceof Integer) {
1701 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1702 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001703 } else if (value == null || value instanceof String) {
1704 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1705 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001706 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001707 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1708 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001709 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001710 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001711 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001712 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001713 serializer.endTag(null, TAG_VALUE);
1714 }
1715 }
1716 serializer.endTag(null, TAG_ENTRY);
1717 }
1718
1719 serializer.endTag(null, TAG_RESTRICTIONS);
1720
1721 serializer.endDocument();
1722 restrictionsFile.finishWrite(fos);
1723 } catch (Exception e) {
1724 restrictionsFile.failWrite(fos);
1725 Slog.e(LOG_TAG, "Error writing application restrictions list");
1726 }
1727 }
1728
1729 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001730 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001731 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001732 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001733 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001734 }
1735 }
1736
1737 @Override
1738 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001739 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001740 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001741 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001742 }
1743 // Not found
1744 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001745 }
1746 }
1747
Amith Yamasani0b285492011-04-14 17:35:23 -07001748 /**
1749 * Caches the list of user ids in an array, adjusting the array size when necessary.
1750 */
Amith Yamasani13593602012-03-22 16:16:17 -07001751 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001752 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001753 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001754 if (!mUsers.valueAt(i).partial) {
1755 num++;
1756 }
1757 }
Amith Yamasani16389312012-10-17 21:20:14 -07001758 final int[] newUsers = new int[num];
1759 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001760 for (int i = 0; i < mUsers.size(); i++) {
1761 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001762 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001763 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001764 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001765 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001766 }
1767
1768 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001769 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001770 * @param userId the user that was just foregrounded
1771 */
1772 public void userForeground(int userId) {
1773 synchronized (mPackagesLock) {
1774 UserInfo user = mUsers.get(userId);
1775 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001776 if (user == null || user.partial) {
1777 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1778 return;
1779 }
1780 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001781 user.lastLoggedInTime = now;
1782 writeUserLocked(user);
1783 }
1784 }
1785 }
1786
1787 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001788 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001789 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1790 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001791 * @return
1792 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001793 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001794 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001795 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001796 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001797 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001798 break;
1799 }
1800 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001801 }
Amith Yamasani195263742012-08-21 15:40:12 -07001802 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001803 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001804 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001805
Amith Yamasanifc95e702013-09-26 13:20:17 -07001806 private String packageToRestrictionsFileName(String packageName) {
1807 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1808 }
1809
1810 private String restrictionsFileNameToPackage(String fileName) {
1811 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1812 (int) (fileName.length() - XML_SUFFIX.length()));
1813 }
1814
Amith Yamasani920ace02012-09-20 22:15:37 -07001815 @Override
1816 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1817 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1818 != PackageManager.PERMISSION_GRANTED) {
1819 pw.println("Permission Denial: can't dump UserManager from from pid="
1820 + Binder.getCallingPid()
1821 + ", uid=" + Binder.getCallingUid()
1822 + " without permission "
1823 + android.Manifest.permission.DUMP);
1824 return;
1825 }
1826
1827 long now = System.currentTimeMillis();
1828 StringBuilder sb = new StringBuilder();
1829 synchronized (mPackagesLock) {
1830 pw.println("Users:");
1831 for (int i = 0; i < mUsers.size(); i++) {
1832 UserInfo user = mUsers.valueAt(i);
1833 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001834 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001835 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001836 if (user.partial) pw.print(" <partial>");
1837 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001838 pw.print(" Created: ");
1839 if (user.creationTime == 0) {
1840 pw.println("<unknown>");
1841 } else {
1842 sb.setLength(0);
1843 TimeUtils.formatDuration(now - user.creationTime, sb);
1844 sb.append(" ago");
1845 pw.println(sb);
1846 }
1847 pw.print(" Last logged in: ");
1848 if (user.lastLoggedInTime == 0) {
1849 pw.println("<unknown>");
1850 } else {
1851 sb.setLength(0);
1852 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1853 sb.append(" ago");
1854 pw.println(sb);
1855 }
1856 }
1857 }
1858 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001859}