blob: f8103de7a2d856af0064433be8871914a2ed3525 [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;
Alexandra Gherghina385124d2014-04-03 13:37:39 +010026import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
35import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
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;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070044import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070045import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070046import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070047import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.util.Slog;
49import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070051import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Xml;
53
Amith Yamasani1a7472e2013-07-02 11:17:30 -070054import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import com.android.internal.util.ArrayUtils;
56import com.android.internal.util.FastXmlSerializer;
57
58import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60import org.xmlpull.v1.XmlSerializer;
61
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import java.io.BufferedOutputStream;
63import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070064import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070066import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import java.io.FileOutputStream;
68import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070069import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070070import java.security.MessageDigest;
71import java.security.NoSuchAlgorithmException;
72import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.util.ArrayList;
74import java.util.List;
75
Amith Yamasani258848d2012-08-10 17:06:33 -070076public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077
Amith Yamasani2a003292012-08-14 18:25:45 -070078 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070079
Amith Yamasani16389312012-10-17 21:20:14 -070080 private static final boolean DBG = false;
81
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070086 private static final String ATTR_CREATION_TIME = "created";
87 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070088 private static final String ATTR_SALT = "salt";
89 private static final String ATTR_PIN_HASH = "pinHash";
90 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
91 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070092 private static final String ATTR_SERIAL_NO = "serialNumber";
93 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070094 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070095 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010096 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080099 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800100 private static final String TAG_ENTRY = "entry";
101 private static final String TAG_VALUE = "value";
102 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700103 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800104 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700106 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
107 private static final String ATTR_TYPE_STRING = "s";
108 private static final String ATTR_TYPE_BOOLEAN = "b";
109
Amith Yamasani0b285492011-04-14 17:35:23 -0700110 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800114 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700115 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116
Amith Yamasani634cf312012-10-04 17:34:21 -0700117 private static final int MIN_USER_ID = 10;
118
Amith Yamasani5e486f52013-08-07 11:06:44 -0700119 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700120
Amith Yamasani920ace02012-09-20 22:15:37 -0700121 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
122
Amith Yamasani655d0e22013-06-12 14:19:10 -0700123 // Number of attempts before jumping to the next BACKOFF_TIMES slot
124 private static final int BACKOFF_INC_INTERVAL = 5;
125
126 // Amount of time to force the user to wait before entering the PIN again, after failing
127 // BACKOFF_INC_INTERVAL times.
128 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
129
Dianne Hackborn4428e172012-08-24 17:43:05 -0700130 private final Context mContext;
131 private final PackageManagerService mPm;
132 private final Object mInstallLock;
133 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800135 private final Handler mHandler;
136
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private final File mUsersDir;
138 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700139 private final File mBaseUserPath;
140
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800141 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800142 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143
Amith Yamasani655d0e22013-06-12 14:19:10 -0700144 class RestrictionsPinState {
145 long salt;
146 String pinHash;
147 int failedAttempts;
148 long lastAttemptTime;
149 }
150
151 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
152 new SparseArray<RestrictionsPinState>();
153
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800154 /**
155 * Set of user IDs being actively removed. Removed IDs linger in this set
156 * for several seconds to work around a VFS caching issue.
157 */
158 // @GuardedBy("mPackagesLock")
159 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700160
Amith Yamasani0b285492011-04-14 17:35:23 -0700161 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700162 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700163 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700164 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700165
Amith Yamasani258848d2012-08-10 17:06:33 -0700166 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700167
Dianne Hackborn4428e172012-08-24 17:43:05 -0700168 public static UserManagerService getInstance() {
169 synchronized (UserManagerService.class) {
170 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173
174 /**
175 * Available for testing purposes.
176 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700177 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179 }
180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 /**
182 * Called by package manager to create the service. This is closely
183 * associated with the package manager, and the given lock is the
184 * package manager's own lock.
185 */
186 UserManagerService(Context context, PackageManagerService pm,
187 Object installLock, Object packagesLock) {
188 this(context, pm, installLock, packagesLock,
189 Environment.getDataDirectory(),
190 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191 }
192
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193 /**
194 * Available for testing purposes.
195 */
196 private UserManagerService(Context context, PackageManagerService pm,
197 Object installLock, Object packagesLock,
198 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700199 mContext = context;
200 mPm = pm;
201 mInstallLock = installLock;
202 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800203 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700204 synchronized (mInstallLock) {
205 synchronized (mPackagesLock) {
206 mUsersDir = new File(dataDir, USER_INFO_DIR);
207 mUsersDir.mkdirs();
208 // Make zeroth user directory, for services to migrate their files to that location
209 File userZeroDir = new File(mUsersDir, "0");
210 userZeroDir.mkdirs();
211 mBaseUserPath = baseUserPath;
212 FileUtils.setPermissions(mUsersDir.toString(),
213 FileUtils.S_IRWXU|FileUtils.S_IRWXG
214 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
215 -1, -1);
216 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
217 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700218 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
220 for (int i = 0; i < mUsers.size(); i++) {
221 UserInfo ui = mUsers.valueAt(i);
222 if (ui.partial && i != 0) {
223 partials.add(ui);
224 }
225 }
226 for (int i = 0; i < partials.size(); i++) {
227 UserInfo ui = partials.get(i);
228 Slog.w(LOG_TAG, "Removing partially created user #" + i
229 + " (name=" + ui.name + ")");
230 removeUserStateLocked(ui.id);
231 }
232 sInstance = this;
233 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700235 }
236
237 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700238 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700239 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700240 }
241
242 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700243 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700244 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700245 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700246 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
247 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700248 UserInfo ui = mUsers.valueAt(i);
249 if (ui.partial) {
250 continue;
251 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800252 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700253 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700254 }
Amith Yamasani13593602012-03-22 16:16:17 -0700255 }
256 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700257 }
Amith Yamasani13593602012-03-22 16:16:17 -0700258 }
259
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100261 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800262 if (userId != UserHandle.getCallingUserId()) {
263 checkManageUsersPermission("getting profiles related to user " + userId);
264 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700265 final long ident = Binder.clearCallingIdentity();
266 try {
267 synchronized (mPackagesLock) {
268 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100269 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700270 } finally {
271 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000272 }
273 }
274
Amith Yamasanibe465322014-04-24 13:45:17 -0700275 /** Assume permissions already checked and caller's identity cleared */
276 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
277 // Getting the service here is not good for testing purposes.
278 // However, this service is not available when UserManagerService starts
279 // up so we need a lazy load.
280
281 DevicePolicyManager dpm = null;
282 if (enabledOnly) {
283 dpm = (DevicePolicyManager)
284 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
285 }
286
287 UserInfo user = getUserInfoLocked(userId);
288 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
289 for (int i = 0; i < mUsers.size(); i++) {
290 UserInfo profile = mUsers.valueAt(i);
291 if (!isProfileOf(user, profile)) {
292 continue;
293 }
294
295 if (enabledOnly && profile.isManagedProfile()) {
296 if (dpm != null) {
297 if (!dpm.isProfileEnabled(profile.id)) {
298 continue;
299 }
300 } else {
301 Log.w(LOG_TAG,
302 "Attempting to reach DevicePolicyManager before it is started");
303 // TODO: There might be system apps that need to call this.
304 // Make sure that DevicePolicyManagerService is ready at that
305 // time (otherwise, any default value is a bad one).
306 throw new IllegalArgumentException(String.format(
307 "Attempting to get enabled profiles for %d before "
308 + "DevicePolicyManagerService has been started.",
309 userId));
310 }
311 }
312 users.add(profile);
313 }
314 return users;
315 }
316
Kenny Guy2a764942014-04-02 13:29:20 +0100317 private boolean isProfileOf(UserInfo user, UserInfo profile) {
318 return user.id == profile.id ||
319 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
320 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000321 }
322
323 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700324 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700325 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700326 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700327 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700328 }
329 }
330
Amith Yamasani71e6c692013-03-24 17:39:28 -0700331 @Override
332 public boolean isRestricted() {
333 synchronized (mPackagesLock) {
334 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
335 }
336 }
337
Amith Yamasani195263742012-08-21 15:40:12 -0700338 /*
339 * Should be locked on mUsers before calling this.
340 */
341 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700342 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700343 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800344 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700345 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
346 return null;
347 }
348 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700349 }
350
Amith Yamasani13593602012-03-22 16:16:17 -0700351 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700352 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700353 return ArrayUtils.contains(mUserIds, userId);
354 }
355 }
356
Amith Yamasani258848d2012-08-10 17:06:33 -0700357 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700358 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700359 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700360 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700361 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700362 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700363 if (info == null || info.partial) {
364 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
365 return;
366 }
Amith Yamasani13593602012-03-22 16:16:17 -0700367 if (name != null && !name.equals(info.name)) {
368 info.name = name;
369 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700370 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700371 }
372 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700373 if (changed) {
374 sendUserInfoChangedBroadcast(userId);
375 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700376 }
377
Amith Yamasani258848d2012-08-10 17:06:33 -0700378 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700379 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700380 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700381 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700382 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700383 if (info == null || info.partial) {
384 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
385 return;
386 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700387 writeBitmapLocked(info, bitmap);
388 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700389 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700390 sendUserInfoChangedBroadcast(userId);
391 }
392
393 private void sendUserInfoChangedBroadcast(int userId) {
394 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
395 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
396 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700397 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700398 }
399
Amith Yamasani258848d2012-08-10 17:06:33 -0700400 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700401 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700402 checkManageUsersPermission("read users");
403 synchronized (mPackagesLock) {
404 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700405 if (info == null || info.partial) {
406 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
407 return null;
408 }
409 if (info.iconPath == null) {
410 return null;
411 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700412 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700413 }
414 }
415
416 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700417 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700418 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700419 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700420 if (mGuestEnabled != enable) {
421 mGuestEnabled = enable;
422 // Erase any guest user that currently exists
423 for (int i = 0; i < mUsers.size(); i++) {
424 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700425 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700426 if (!enable) {
427 removeUser(user.id);
428 }
429 return;
430 }
431 }
432 // No guest was found
433 if (enable) {
434 createUser("Guest", UserInfo.FLAG_GUEST);
435 }
436 }
437 }
438 }
439
440 @Override
441 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700442 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700443 return mGuestEnabled;
444 }
445 }
446
447 @Override
448 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700449 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700450 // TODO:
451 }
452
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700453 public void makeInitialized(int userId) {
454 checkManageUsersPermission("makeInitialized");
455 synchronized (mPackagesLock) {
456 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700457 if (info == null || info.partial) {
458 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
459 }
460 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700461 info.flags |= UserInfo.FLAG_INITIALIZED;
462 writeUserLocked(info);
463 }
464 }
465 }
466
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800467 @Override
468 public Bundle getUserRestrictions(int userId) {
469 // checkManageUsersPermission("getUserRestrictions");
470
471 synchronized (mPackagesLock) {
472 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700473 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800474 }
475 }
476
477 @Override
478 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700479 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700480 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800481
482 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700483 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800484 mUserRestrictions.get(userId).putAll(restrictions);
485 writeUserLocked(mUsers.get(userId));
486 }
487 }
488
Amith Yamasani258848d2012-08-10 17:06:33 -0700489 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700490 * Check if we've hit the limit of how many users can be created.
491 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700492 private boolean isUserLimitReachedLocked() {
493 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700494 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700495 }
496
497 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700498 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700499 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700500 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700501 *
502 * @param message used as message if SecurityException is thrown
503 * @throws SecurityException if the caller is not system or root
504 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700505 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700506 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700507 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400508 && ActivityManager.checkComponentPermission(
509 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700510 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
511 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
512 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400513 }
514
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700515 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700516 try {
517 File dir = new File(mUsersDir, Integer.toString(info.id));
518 File file = new File(dir, USER_PHOTO_FILENAME);
519 if (!dir.exists()) {
520 dir.mkdir();
521 FileUtils.setPermissions(
522 dir.getPath(),
523 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
524 -1, -1);
525 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700526 FileOutputStream os;
527 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700528 info.iconPath = file.getAbsolutePath();
529 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700530 try {
531 os.close();
532 } catch (IOException ioe) {
533 // What the ... !
534 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700535 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700536 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700537 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700538 }
539
Amith Yamasani0b285492011-04-14 17:35:23 -0700540 /**
541 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
542 * cache it elsewhere.
543 * @return the array of user ids.
544 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700545 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700546 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700547 return mUserIds;
548 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700549 }
550
Dianne Hackborn4428e172012-08-24 17:43:05 -0700551 int[] getUserIdsLPr() {
552 return mUserIds;
553 }
554
Amith Yamasani13593602012-03-22 16:16:17 -0700555 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700556 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700557 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700558 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700559 return;
560 }
561 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700562 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700563 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700564 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700565 XmlPullParser parser = Xml.newPullParser();
566 parser.setInput(fis, null);
567 int type;
568 while ((type = parser.next()) != XmlPullParser.START_TAG
569 && type != XmlPullParser.END_DOCUMENT) {
570 ;
571 }
572
573 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700574 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700575 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700576 return;
577 }
578
Amith Yamasani2a003292012-08-14 18:25:45 -0700579 mNextSerialNumber = -1;
580 if (parser.getName().equals(TAG_USERS)) {
581 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
582 if (lastSerialNumber != null) {
583 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
584 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700585 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
586 if (versionNumber != null) {
587 mUserVersion = Integer.parseInt(versionNumber);
588 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700589 }
590
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700591 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
592 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
593 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800594 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700595
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700596 if (user != null) {
597 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700598 if (user.isGuest()) {
599 mGuestEnabled = true;
600 }
601 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
602 mNextSerialNumber = user.id + 1;
603 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700604 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700605 }
606 }
Amith Yamasani13593602012-03-22 16:16:17 -0700607 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700608 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700609 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700610 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700611 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700612 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800613 } finally {
614 if (fis != null) {
615 try {
616 fis.close();
617 } catch (IOException e) {
618 }
619 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700620 }
621 }
622
Amith Yamasani6f34b412012-10-22 18:19:27 -0700623 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800624 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700625 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700626 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700627 int userVersion = mUserVersion;
628 if (userVersion < 1) {
629 // Assign a proper name for the owner, if not initialized correctly before
630 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
631 if ("Primary".equals(user.name)) {
632 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
633 writeUserLocked(user);
634 }
635 userVersion = 1;
636 }
637
Amith Yamasanibc9625052012-11-15 14:39:18 -0800638 if (userVersion < 2) {
639 // Owner should be marked as initialized
640 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
641 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
642 user.flags |= UserInfo.FLAG_INITIALIZED;
643 writeUserLocked(user);
644 }
645 userVersion = 2;
646 }
647
Amith Yamasani350962c2013-08-06 11:18:53 -0700648
Amith Yamasani5e486f52013-08-07 11:06:44 -0700649 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700650 userVersion = 4;
651 }
652
Amith Yamasani6f34b412012-10-22 18:19:27 -0700653 if (userVersion < USER_VERSION) {
654 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
655 + USER_VERSION);
656 } else {
657 mUserVersion = userVersion;
658 writeUserListLocked();
659 }
660 }
661
Amith Yamasani13593602012-03-22 16:16:17 -0700662 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700663 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800664 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700665 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700666 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700667 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700668 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400669 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800670
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500671 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800672 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
673
Amith Yamasani13593602012-03-22 16:16:17 -0700674 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700675
Amith Yamasani13593602012-03-22 16:16:17 -0700676 writeUserListLocked();
677 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700678 }
679
680 /*
681 * Writes the user file in this format:
682 *
683 * <user flags="20039023" id="0">
684 * <name>Primary</name>
685 * </user>
686 */
Amith Yamasani13593602012-03-22 16:16:17 -0700687 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700688 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700689 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700690 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700691 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700692 final BufferedOutputStream bos = new BufferedOutputStream(fos);
693
694 // XmlSerializer serializer = XmlUtils.serializerInstance();
695 final XmlSerializer serializer = new FastXmlSerializer();
696 serializer.setOutput(bos, "utf-8");
697 serializer.startDocument(null, true);
698 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
699
700 serializer.startTag(null, TAG_USER);
701 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700702 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700703 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700704 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
705 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
706 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700707 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
708 if (pinState != null) {
709 if (pinState.salt != 0) {
710 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
711 }
712 if (pinState.pinHash != null) {
713 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
714 }
715 if (pinState.failedAttempts != 0) {
716 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
717 Integer.toString(pinState.failedAttempts));
718 serializer.attribute(null, ATTR_LAST_RETRY_MS,
719 Long.toString(pinState.lastAttemptTime));
720 }
721 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700722 if (userInfo.iconPath != null) {
723 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
724 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700725 if (userInfo.partial) {
726 serializer.attribute(null, ATTR_PARTIAL, "true");
727 }
Kenny Guy2a764942014-04-02 13:29:20 +0100728 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
729 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
730 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000731 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700732
733 serializer.startTag(null, TAG_NAME);
734 serializer.text(userInfo.name);
735 serializer.endTag(null, TAG_NAME);
736
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800737 Bundle restrictions = mUserRestrictions.get(userInfo.id);
738 if (restrictions != null) {
739 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700740 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
741 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
742 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
743 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
744 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400745 writeBoolean(serializer, restrictions,
746 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
747 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
748 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400749 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
750 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800751 serializer.endTag(null, TAG_RESTRICTIONS);
752 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700753 serializer.endTag(null, TAG_USER);
754
755 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700756 userFile.finishWrite(fos);
757 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700758 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700759 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700760 }
761 }
762
763 /*
764 * Writes the user list file in this format:
765 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700766 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700767 * <user id="0"></user>
768 * <user id="2"></user>
769 * </users>
770 */
Amith Yamasani13593602012-03-22 16:16:17 -0700771 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700772 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700773 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700775 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700776 final BufferedOutputStream bos = new BufferedOutputStream(fos);
777
778 // XmlSerializer serializer = XmlUtils.serializerInstance();
779 final XmlSerializer serializer = new FastXmlSerializer();
780 serializer.setOutput(bos, "utf-8");
781 serializer.startDocument(null, true);
782 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
783
784 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700785 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700786 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700787
788 for (int i = 0; i < mUsers.size(); i++) {
789 UserInfo user = mUsers.valueAt(i);
790 serializer.startTag(null, TAG_USER);
791 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
792 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700793 }
794
795 serializer.endTag(null, TAG_USERS);
796
797 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700798 userListFile.finishWrite(fos);
799 } catch (Exception e) {
800 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700801 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700802 }
803 }
804
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800805 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700806 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700807 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700808 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700809 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700810 long creationTime = 0L;
811 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700812 long salt = 0L;
813 String pinHash = null;
814 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100815 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700816 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700817 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800818 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700819
820 FileInputStream fis = null;
821 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700822 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700823 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700824 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700825 XmlPullParser parser = Xml.newPullParser();
826 parser.setInput(fis, null);
827 int type;
828 while ((type = parser.next()) != XmlPullParser.START_TAG
829 && type != XmlPullParser.END_DOCUMENT) {
830 ;
831 }
832
833 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700834 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700835 return null;
836 }
837
838 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700839 int storedId = readIntAttribute(parser, ATTR_ID, -1);
840 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700841 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700842 return null;
843 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700844 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
845 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700846 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700847 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
848 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700849 salt = readLongAttribute(parser, ATTR_SALT, 0L);
850 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
851 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
852 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100853 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
854 UserInfo.NO_PROFILE_GROUP_ID);
855 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
856 // This attribute was added and renamed during development of L.
857 // TODO Remove upgrade path by 1st May 2014
858 profileGroupId = readIntAttribute(parser, "relatedGroupId",
859 UserInfo.NO_PROFILE_GROUP_ID);
860 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700861 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
862 if ("true".equals(valueString)) {
863 partial = true;
864 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700865
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800866 int outerDepth = parser.getDepth();
867 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
868 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
869 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
870 continue;
871 }
872 String tag = parser.getName();
873 if (TAG_NAME.equals(tag)) {
874 type = parser.next();
875 if (type == XmlPullParser.TEXT) {
876 name = parser.getText();
877 }
878 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700879 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
880 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
881 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
882 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
883 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400884 readBoolean(parser, restrictions,
885 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
886 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
887 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400888 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
889 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700890 }
891 }
892 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700893
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700894 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700895 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700896 userInfo.creationTime = creationTime;
897 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700898 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100899 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800900 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700901 if (salt != 0L) {
902 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
903 if (pinState == null) {
904 pinState = new RestrictionsPinState();
905 mRestrictionsPinStates.put(id, pinState);
906 }
907 pinState.salt = salt;
908 pinState.pinHash = pinHash;
909 pinState.failedAttempts = failedAttempts;
910 pinState.lastAttemptTime = lastAttemptTime;
911 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700912 return userInfo;
913
914 } catch (IOException ioe) {
915 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800916 } finally {
917 if (fis != null) {
918 try {
919 fis.close();
920 } catch (IOException e) {
921 }
922 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700923 }
924 return null;
925 }
926
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800927 private void readBoolean(XmlPullParser parser, Bundle restrictions,
928 String restrictionKey) {
929 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700930 if (value != null) {
931 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
932 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800933 }
934
935 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
936 throws IOException {
937 if (restrictions.containsKey(restrictionKey)) {
938 xml.attribute(null, restrictionKey,
939 Boolean.toString(restrictions.getBoolean(restrictionKey)));
940 }
941 }
942
Amith Yamasani920ace02012-09-20 22:15:37 -0700943 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
944 String valueString = parser.getAttributeValue(null, attr);
945 if (valueString == null) return defaultValue;
946 try {
947 return Integer.parseInt(valueString);
948 } catch (NumberFormatException nfe) {
949 return defaultValue;
950 }
951 }
952
953 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
954 String valueString = parser.getAttributeValue(null, attr);
955 if (valueString == null) return defaultValue;
956 try {
957 return Long.parseLong(valueString);
958 } catch (NumberFormatException nfe) {
959 return defaultValue;
960 }
961 }
962
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700963 private boolean isPackageInstalled(String pkg, int userId) {
964 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
965 PackageManager.GET_UNINSTALLED_PACKAGES,
966 userId);
967 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
968 return false;
969 }
970 return true;
971 }
972
Amith Yamasanib82add22013-07-09 11:24:44 -0700973 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700974 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
975 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -0700976 * Does not do any permissions checking.
977 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700978 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -0700979 synchronized (mPackagesLock) {
980 File dir = Environment.getUserSystemDirectory(userId);
981 String[] files = dir.list();
982 if (files == null) return;
983 for (String fileName : files) {
984 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
985 File resFile = new File(dir, fileName);
986 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700987 if (all) {
988 resFile.delete();
989 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -0700990 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700991 if (!isPackageInstalled(pkg, userId)) {
992 resFile.delete();
993 }
994 }
Amith Yamasanib82add22013-07-09 11:24:44 -0700995 }
996 }
997 }
998 }
999 }
1000
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001001 /**
1002 * Removes the app restrictions file for a specific package and user id, if it exists.
1003 */
1004 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1005 synchronized (mPackagesLock) {
1006 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001007 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001008 if (resFile.exists()) {
1009 resFile.delete();
1010 }
1011 }
1012 }
1013
Kenny Guy2a764942014-04-02 13:29:20 +01001014 private int getNextProfileGroupIdLocked() {
1015 int maxGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001016 for (int i = 0; i < mUsers.size(); i++) {
1017 UserInfo ui = mUsers.valueAt(i);
Kenny Guy2a764942014-04-02 13:29:20 +01001018 if (maxGroupId < ui.profileGroupId) {
1019 maxGroupId = ui.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001020 }
1021 }
1022 return maxGroupId + 1;
1023 }
1024
1025 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001026 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001027 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001028 if (userId != UserHandle.USER_OWNER) {
1029 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001030 return null;
1031 }
Kenny Guy2a764942014-04-02 13:29:20 +01001032 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001033 }
1034
Amith Yamasani258848d2012-08-10 17:06:33 -07001035 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001036 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001037 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001038 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001039 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001040
Kenny Guy2a764942014-04-02 13:29:20 +01001041 private UserInfo createUserInternal(String name, int flags, int profileId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001042 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001043 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001044 try {
1045 synchronized (mInstallLock) {
1046 synchronized (mPackagesLock) {
Kenny Guy2a764942014-04-02 13:29:20 +01001047 UserInfo profile = null;
1048 if (profileId != UserHandle.USER_NULL) {
1049 profile = getUserInfoLocked(profileId);
1050 if (profile == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001051 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001052 if (isUserLimitReachedLocked()) return null;
1053 int userId = getNextAvailableIdLocked();
1054 userInfo = new UserInfo(userId, name, null, flags);
1055 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1056 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001057 long now = System.currentTimeMillis();
1058 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001059 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001060 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001061 mUsers.put(userId, userInfo);
1062 writeUserListLocked();
Kenny Guy2a764942014-04-02 13:29:20 +01001063 if (profile != null) {
1064 if (profile.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1065 profile.profileGroupId = getNextProfileGroupIdLocked();
1066 writeUserLocked(profile);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001067 }
Kenny Guy2a764942014-04-02 13:29:20 +01001068 userInfo.profileGroupId = profile.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001069 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001070 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001071 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001072 userInfo.partial = false;
1073 writeUserLocked(userInfo);
1074 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001075 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001076 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001077 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001078 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001079 if (userInfo != null) {
1080 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1081 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1082 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1083 android.Manifest.permission.MANAGE_USERS);
1084 }
1085 } finally {
1086 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001087 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001088 return userInfo;
1089 }
1090
Amith Yamasani0b285492011-04-14 17:35:23 -07001091 /**
1092 * Removes a user and all data directories created for that user. This method should be called
1093 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001094 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001095 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001096 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001097 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001098 final UserInfo user;
1099 synchronized (mPackagesLock) {
1100 user = mUsers.get(userHandle);
1101 if (userHandle == 0 || user == null) {
1102 return false;
1103 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001104 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -07001105 // Set this to a partially created user, so that the user will be purged
1106 // on next startup, in case the runtime stops now before stopping and
1107 // removing the user completely.
1108 user.partial = true;
1109 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001110 }
Amith Yamasani16389312012-10-17 21:20:14 -07001111 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001112 int res;
1113 try {
1114 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1115 new IStopUserCallback.Stub() {
1116 @Override
1117 public void userStopped(int userId) {
1118 finishRemoveUser(userId);
1119 }
1120 @Override
1121 public void userStopAborted(int userId) {
1122 }
1123 });
1124 } catch (RemoteException e) {
1125 return false;
1126 }
1127
1128 return res == ActivityManager.USER_OP_SUCCESS;
1129 }
1130
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001131 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001132 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001133 // Let other services shutdown any activity and clean up their state before completely
1134 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001135 long ident = Binder.clearCallingIdentity();
1136 try {
1137 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1138 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001139 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1140 android.Manifest.permission.MANAGE_USERS,
1141
1142 new BroadcastReceiver() {
1143 @Override
1144 public void onReceive(Context context, Intent intent) {
1145 if (DBG) {
1146 Slog.i(LOG_TAG,
1147 "USER_REMOVED broadcast sent, cleaning up user data "
1148 + userHandle);
1149 }
1150 new Thread() {
1151 public void run() {
1152 synchronized (mInstallLock) {
1153 synchronized (mPackagesLock) {
1154 removeUserStateLocked(userHandle);
1155 }
1156 }
1157 }
1158 }.start();
1159 }
1160 },
1161
1162 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001163 } finally {
1164 Binder.restoreCallingIdentity(ident);
1165 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001166 }
1167
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001168 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001169 // Cleanup package manager settings
1170 mPm.cleanUpUserLILPw(userHandle);
1171
1172 // Remove this user from the list
1173 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001174
1175 // Have user ID linger for several seconds to let external storage VFS
1176 // cache entries expire. This must be greater than the 'entry_valid'
1177 // timeout used by the FUSE daemon.
1178 mHandler.postDelayed(new Runnable() {
1179 @Override
1180 public void run() {
1181 synchronized (mPackagesLock) {
1182 mRemovingUserIds.delete(userHandle);
1183 }
1184 }
1185 }, MINUTE_IN_MILLIS);
1186
Amith Yamasani655d0e22013-06-12 14:19:10 -07001187 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001188 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001189 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001190 userFile.delete();
1191 // Update the user list
1192 writeUserListLocked();
1193 updateUserIdsLocked();
1194 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1195 }
1196
Amith Yamasani61f57372012-08-31 12:12:28 -07001197 private void removeDirectoryRecursive(File parent) {
1198 if (parent.isDirectory()) {
1199 String[] files = parent.list();
1200 for (String filename : files) {
1201 File child = new File(parent, filename);
1202 removeDirectoryRecursive(child);
1203 }
1204 }
1205 parent.delete();
1206 }
1207
Amith Yamasani2a003292012-08-14 18:25:45 -07001208 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001209 public Bundle getApplicationRestrictions(String packageName) {
1210 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1211 }
1212
1213 @Override
1214 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001215 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001216 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001217 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001218 }
1219 synchronized (mPackagesLock) {
1220 // Read the restrictions from XML
1221 return readApplicationRestrictionsLocked(packageName, userId);
1222 }
1223 }
1224
1225 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001226 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001227 int userId) {
1228 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001229 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001230 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001231 }
1232 synchronized (mPackagesLock) {
1233 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001234 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001235 }
Robin Lee66e5d962014-04-09 16:44:21 +01001236
1237 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1238 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1239 changeIntent.setPackage(packageName);
1240 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1241 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001242 }
1243
Amith Yamasani655d0e22013-06-12 14:19:10 -07001244 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001245 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001246 checkManageUsersPermission("Only system can modify the restrictions pin");
1247 int userId = UserHandle.getCallingUserId();
1248 synchronized (mPackagesLock) {
1249 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1250 if (pinState == null) {
1251 pinState = new RestrictionsPinState();
1252 }
1253 if (newPin == null) {
1254 pinState.salt = 0;
1255 pinState.pinHash = null;
1256 } else {
1257 try {
1258 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1259 } catch (NoSuchAlgorithmException e) {
1260 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1261 }
1262 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1263 pinState.failedAttempts = 0;
1264 }
1265 mRestrictionsPinStates.put(userId, pinState);
1266 writeUserLocked(mUsers.get(userId));
1267 }
1268 return true;
1269 }
1270
1271 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001272 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001273 checkManageUsersPermission("Only system can verify the restrictions pin");
1274 int userId = UserHandle.getCallingUserId();
1275 synchronized (mPackagesLock) {
1276 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1277 // If there's no pin set, return error code
1278 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1279 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1280 } else if (pin == null) {
1281 // If just checking if user can be prompted, return remaining time
1282 int waitTime = getRemainingTimeForPinAttempt(pinState);
1283 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1284 return waitTime;
1285 } else {
1286 int waitTime = getRemainingTimeForPinAttempt(pinState);
1287 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1288 if (waitTime > 0) {
1289 return waitTime;
1290 }
1291 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1292 pinState.failedAttempts = 0;
1293 writeUserLocked(mUsers.get(userId));
1294 return UserManager.PIN_VERIFICATION_SUCCESS;
1295 } else {
1296 pinState.failedAttempts++;
1297 pinState.lastAttemptTime = System.currentTimeMillis();
1298 writeUserLocked(mUsers.get(userId));
1299 return waitTime;
1300 }
1301 }
1302 }
1303 }
1304
1305 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1306 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1307 BACKOFF_TIMES.length - 1);
1308 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1309 BACKOFF_TIMES[backoffIndex] : 0;
1310 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1311 0);
1312 }
1313
1314 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001315 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001316 int userId = UserHandle.getCallingUserId();
1317 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001318 return hasRestrictionsPinLocked(userId);
1319 }
1320 }
1321
1322 private boolean hasRestrictionsPinLocked(int userId) {
1323 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1324 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1325 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001326 }
1327 return true;
1328 }
1329
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001330 @Override
1331 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001332 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001333 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001334 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001335 }
1336
Amith Yamasani5e486f52013-08-07 11:06:44 -07001337 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001338 synchronized (mPackagesLock) {
1339 // Remove all user restrictions
1340 setUserRestrictions(new Bundle(), userHandle);
1341 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001342 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001343 // Remove any app restrictions
1344 cleanAppRestrictions(userHandle, true);
1345 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001346 if (unblockApps) {
1347 unblockAllAppsForUser(userHandle);
1348 }
1349 }
1350
1351 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001352 mHandler.post(new Runnable() {
1353 @Override
1354 public void run() {
1355 List<ApplicationInfo> apps =
1356 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1357 userHandle).getList();
1358 final long ident = Binder.clearCallingIdentity();
1359 try {
1360 for (ApplicationInfo appInfo : apps) {
1361 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1362 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1363 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1364 userHandle);
1365 }
1366 }
1367 } finally {
1368 Binder.restoreCallingIdentity(ident);
1369 }
1370 }
1371 });
1372 }
1373
Amith Yamasani655d0e22013-06-12 14:19:10 -07001374 /*
1375 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1376 * Not the most secure, but it is at least a second level of protection. First level is that
1377 * the file is in a location only readable by the system process.
1378 * @param password the password.
1379 * @param salt the randomly generated salt
1380 * @return the hash of the pattern in a String.
1381 */
1382 private String passwordToHash(String password, long salt) {
1383 if (password == null) {
1384 return null;
1385 }
1386 String algo = null;
1387 String hashed = salt + password;
1388 try {
1389 byte[] saltedPassword = (password + salt).getBytes();
1390 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1391 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1392 hashed = toHex(sha1) + toHex(md5);
1393 } catch (NoSuchAlgorithmException e) {
1394 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1395 }
1396 return hashed;
1397 }
1398
1399 private static String toHex(byte[] ary) {
1400 final String hex = "0123456789ABCDEF";
1401 String ret = "";
1402 for (int i = 0; i < ary.length; i++) {
1403 ret += hex.charAt((ary[i] >> 4) & 0xf);
1404 ret += hex.charAt(ary[i] & 0xf);
1405 }
1406 return ret;
1407 }
1408
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001409 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001410 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001411 try {
1412 return mContext.getPackageManager().getApplicationInfo(packageName,
1413 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1414 } catch (NameNotFoundException nnfe) {
1415 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001416 } finally {
1417 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001418 }
1419 }
1420
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001421 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001422 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001423 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001424 final ArrayList<String> values = new ArrayList<String>();
1425
1426 FileInputStream fis = null;
1427 try {
1428 AtomicFile restrictionsFile =
1429 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001430 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001431 fis = restrictionsFile.openRead();
1432 XmlPullParser parser = Xml.newPullParser();
1433 parser.setInput(fis, null);
1434 int type;
1435 while ((type = parser.next()) != XmlPullParser.START_TAG
1436 && type != XmlPullParser.END_DOCUMENT) {
1437 ;
1438 }
1439
1440 if (type != XmlPullParser.START_TAG) {
1441 Slog.e(LOG_TAG, "Unable to read restrictions file "
1442 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001443 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001444 }
1445
1446 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1447 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1448 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001449 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001450 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1451 if (multiple != null) {
1452 int count = Integer.parseInt(multiple);
1453 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1454 if (type == XmlPullParser.START_TAG
1455 && parser.getName().equals(TAG_VALUE)) {
1456 values.add(parser.nextText().trim());
1457 count--;
1458 }
1459 }
1460 String [] valueStrings = new String[values.size()];
1461 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001462 restrictions.putStringArray(key, valueStrings);
1463 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1464 restrictions.putBoolean(key, Boolean.parseBoolean(
1465 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001466 } else {
1467 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001468 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001469 }
1470 }
1471 }
1472
1473 } catch (IOException ioe) {
1474 } catch (XmlPullParserException pe) {
1475 } finally {
1476 if (fis != null) {
1477 try {
1478 fis.close();
1479 } catch (IOException e) {
1480 }
1481 }
1482 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001483 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001484 }
1485
1486 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001487 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001488 FileOutputStream fos = null;
1489 AtomicFile restrictionsFile = new AtomicFile(
1490 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001491 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001492 try {
1493 fos = restrictionsFile.startWrite();
1494 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1495
1496 // XmlSerializer serializer = XmlUtils.serializerInstance();
1497 final XmlSerializer serializer = new FastXmlSerializer();
1498 serializer.setOutput(bos, "utf-8");
1499 serializer.startDocument(null, true);
1500 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1501
1502 serializer.startTag(null, TAG_RESTRICTIONS);
1503
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001504 for (String key : restrictions.keySet()) {
1505 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001506 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001507 serializer.attribute(null, ATTR_KEY, key);
1508
1509 if (value instanceof Boolean) {
1510 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1511 serializer.text(value.toString());
1512 } else if (value == null || value instanceof String) {
1513 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1514 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001515 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001516 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1517 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001518 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001519 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001520 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001521 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001522 serializer.endTag(null, TAG_VALUE);
1523 }
1524 }
1525 serializer.endTag(null, TAG_ENTRY);
1526 }
1527
1528 serializer.endTag(null, TAG_RESTRICTIONS);
1529
1530 serializer.endDocument();
1531 restrictionsFile.finishWrite(fos);
1532 } catch (Exception e) {
1533 restrictionsFile.failWrite(fos);
1534 Slog.e(LOG_TAG, "Error writing application restrictions list");
1535 }
1536 }
1537
1538 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001539 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001540 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001541 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001542 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001543 }
1544 }
1545
1546 @Override
1547 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001548 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001549 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001550 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001551 }
1552 // Not found
1553 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001554 }
1555 }
1556
Amith Yamasani0b285492011-04-14 17:35:23 -07001557 /**
1558 * Caches the list of user ids in an array, adjusting the array size when necessary.
1559 */
Amith Yamasani13593602012-03-22 16:16:17 -07001560 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001561 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001562 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001563 if (!mUsers.valueAt(i).partial) {
1564 num++;
1565 }
1566 }
Amith Yamasani16389312012-10-17 21:20:14 -07001567 final int[] newUsers = new int[num];
1568 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001569 for (int i = 0; i < mUsers.size(); i++) {
1570 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001571 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001572 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001573 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001574 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001575 }
1576
1577 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001578 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001579 * @param userId the user that was just foregrounded
1580 */
1581 public void userForeground(int userId) {
1582 synchronized (mPackagesLock) {
1583 UserInfo user = mUsers.get(userId);
1584 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001585 if (user == null || user.partial) {
1586 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1587 return;
1588 }
1589 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001590 user.lastLoggedInTime = now;
1591 writeUserLocked(user);
1592 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001593 // If this is not a restricted profile and there is no restrictions pin, clean up
1594 // all restrictions files that might have been left behind, else clean up just the
1595 // ones with uninstalled packages
1596 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1597 final long salt = pinState == null ? 0 : pinState.salt;
1598 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001599 }
1600 }
1601
1602 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001603 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001604 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1605 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001606 * @return
1607 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001608 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001609 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001610 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001611 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001612 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001613 break;
1614 }
1615 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001616 }
Amith Yamasani195263742012-08-21 15:40:12 -07001617 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001618 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001619 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001620
Amith Yamasanifc95e702013-09-26 13:20:17 -07001621 private String packageToRestrictionsFileName(String packageName) {
1622 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1623 }
1624
1625 private String restrictionsFileNameToPackage(String fileName) {
1626 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1627 (int) (fileName.length() - XML_SUFFIX.length()));
1628 }
1629
Amith Yamasani920ace02012-09-20 22:15:37 -07001630 @Override
1631 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1632 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1633 != PackageManager.PERMISSION_GRANTED) {
1634 pw.println("Permission Denial: can't dump UserManager from from pid="
1635 + Binder.getCallingPid()
1636 + ", uid=" + Binder.getCallingUid()
1637 + " without permission "
1638 + android.Manifest.permission.DUMP);
1639 return;
1640 }
1641
1642 long now = System.currentTimeMillis();
1643 StringBuilder sb = new StringBuilder();
1644 synchronized (mPackagesLock) {
1645 pw.println("Users:");
1646 for (int i = 0; i < mUsers.size(); i++) {
1647 UserInfo user = mUsers.valueAt(i);
1648 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001649 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001650 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001651 if (user.partial) pw.print(" <partial>");
1652 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001653 pw.print(" Created: ");
1654 if (user.creationTime == 0) {
1655 pw.println("<unknown>");
1656 } else {
1657 sb.setLength(0);
1658 TimeUtils.formatDuration(now - user.creationTime, sb);
1659 sb.append(" ago");
1660 pw.println(sb);
1661 }
1662 pw.print(" Last logged in: ");
1663 if (user.lastLoggedInTime == 0) {
1664 pw.println("<unknown>");
1665 } else {
1666 sb.setLength(0);
1667 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1668 sb.append(" ago");
1669 pw.println(sb);
1670 }
1671 }
1672 }
1673 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001674
1675 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1676 @Override
1677 public void onPackageRemoved(String pkg, int uid) {
1678 final int userId = this.getChangingUserId();
1679 // Package could be disappearing because it is being blocked, so also check if
1680 // it has been uninstalled.
1681 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1682 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1683 cleanAppRestrictionsForPackage(pkg, userId);
1684 }
1685 }
1686 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001687}