blob: a6cac5e4e1ffee4762d86010b39854a81e4d771d [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080019import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070020
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070024import android.app.ActivityThread;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070045import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070046import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Slog;
48import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070050import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.util.Xml;
52
Amith Yamasani1a7472e2013-07-02 11:17:30 -070053import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080054import com.android.internal.util.ArrayUtils;
55import com.android.internal.util.FastXmlSerializer;
56
57import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59import org.xmlpull.v1.XmlSerializer;
60
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import java.io.BufferedOutputStream;
62import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070063import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070065import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileOutputStream;
67import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070068import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070069import java.security.MessageDigest;
70import java.security.NoSuchAlgorithmException;
71import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import java.util.ArrayList;
73import java.util.List;
74
Amith Yamasani258848d2012-08-10 17:06:33 -070075public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070076
Amith Yamasani2a003292012-08-14 18:25:45 -070077 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani16389312012-10-17 21:20:14 -070079 private static final boolean DBG = false;
80
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070083 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070085 private static final String ATTR_CREATION_TIME = "created";
86 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070087 private static final String ATTR_SALT = "salt";
88 private static final String ATTR_PIN_HASH = "pinHash";
89 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
90 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070091 private static final String ATTR_SERIAL_NO = "serialNumber";
92 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070093 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070094 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010095 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080098 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080099 private static final String TAG_ENTRY = "entry";
100 private static final String TAG_VALUE = "value";
101 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700102 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800103 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700105 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
106 private static final String ATTR_TYPE_STRING = "s";
107 private static final String ATTR_TYPE_BOOLEAN = "b";
108
Amith Yamasani0b285492011-04-14 17:35:23 -0700109 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800113 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700114 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115
Amith Yamasani634cf312012-10-04 17:34:21 -0700116 private static final int MIN_USER_ID = 10;
117
Amith Yamasani5e486f52013-08-07 11:06:44 -0700118 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700119
Amith Yamasani920ace02012-09-20 22:15:37 -0700120 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
121
Amith Yamasani655d0e22013-06-12 14:19:10 -0700122 // Number of attempts before jumping to the next BACKOFF_TIMES slot
123 private static final int BACKOFF_INC_INTERVAL = 5;
124
125 // Amount of time to force the user to wait before entering the PIN again, after failing
126 // BACKOFF_INC_INTERVAL times.
127 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
128
Dianne Hackborn4428e172012-08-24 17:43:05 -0700129 private final Context mContext;
130 private final PackageManagerService mPm;
131 private final Object mInstallLock;
132 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700133
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800134 private final Handler mHandler;
135
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136 private final File mUsersDir;
137 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700138 private final File mBaseUserPath;
139
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800140 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800141 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800142
Amith Yamasani655d0e22013-06-12 14:19:10 -0700143 class RestrictionsPinState {
144 long salt;
145 String pinHash;
146 int failedAttempts;
147 long lastAttemptTime;
148 }
149
150 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
151 new SparseArray<RestrictionsPinState>();
152
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800153 /**
154 * Set of user IDs being actively removed. Removed IDs linger in this set
155 * for several seconds to work around a VFS caching issue.
156 */
157 // @GuardedBy("mPackagesLock")
158 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700159
Amith Yamasani0b285492011-04-14 17:35:23 -0700160 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700161 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700162 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700163 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700164
Amith Yamasani258848d2012-08-10 17:06:33 -0700165 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700166
Dianne Hackborn4428e172012-08-24 17:43:05 -0700167 public static UserManagerService getInstance() {
168 synchronized (UserManagerService.class) {
169 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700170 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172
173 /**
174 * Available for testing purposes.
175 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700176 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700178 }
179
Dianne Hackborn4428e172012-08-24 17:43:05 -0700180 /**
181 * Called by package manager to create the service. This is closely
182 * associated with the package manager, and the given lock is the
183 * package manager's own lock.
184 */
185 UserManagerService(Context context, PackageManagerService pm,
186 Object installLock, Object packagesLock) {
187 this(context, pm, installLock, packagesLock,
188 Environment.getDataDirectory(),
189 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190 }
191
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192 /**
193 * Available for testing purposes.
194 */
195 private UserManagerService(Context context, PackageManagerService pm,
196 Object installLock, Object packagesLock,
197 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700198 mContext = context;
199 mPm = pm;
200 mInstallLock = installLock;
201 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800202 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700203 synchronized (mInstallLock) {
204 synchronized (mPackagesLock) {
205 mUsersDir = new File(dataDir, USER_INFO_DIR);
206 mUsersDir.mkdirs();
207 // Make zeroth user directory, for services to migrate their files to that location
208 File userZeroDir = new File(mUsersDir, "0");
209 userZeroDir.mkdirs();
210 mBaseUserPath = baseUserPath;
211 FileUtils.setPermissions(mUsersDir.toString(),
212 FileUtils.S_IRWXU|FileUtils.S_IRWXG
213 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
214 -1, -1);
215 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
216 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700217 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700218 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
219 for (int i = 0; i < mUsers.size(); i++) {
220 UserInfo ui = mUsers.valueAt(i);
221 if (ui.partial && i != 0) {
222 partials.add(ui);
223 }
224 }
225 for (int i = 0; i < partials.size(); i++) {
226 UserInfo ui = partials.get(i);
227 Slog.w(LOG_TAG, "Removing partially created user #" + i
228 + " (name=" + ui.name + ")");
229 removeUserStateLocked(ui.id);
230 }
231 sInstance = this;
232 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700233 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700234 }
235
236 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700237 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700238 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700239 }
240
241 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700242 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700243 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700244 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700245 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
246 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700247 UserInfo ui = mUsers.valueAt(i);
248 if (ui.partial) {
249 continue;
250 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800251 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700253 }
Amith Yamasani13593602012-03-22 16:16:17 -0700254 }
255 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700256 }
Amith Yamasani13593602012-03-22 16:16:17 -0700257 }
258
Amith Yamasani258848d2012-08-10 17:06:33 -0700259 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100260 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800261 if (userId != UserHandle.getCallingUserId()) {
262 checkManageUsersPermission("getting profiles related to user " + userId);
263 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700264 final long ident = Binder.clearCallingIdentity();
265 try {
266 synchronized (mPackagesLock) {
267 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100268 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700269 } finally {
270 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000271 }
272 }
273
Amith Yamasanibe465322014-04-24 13:45:17 -0700274 /** Assume permissions already checked and caller's identity cleared */
275 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700276 UserInfo user = getUserInfoLocked(userId);
277 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
278 for (int i = 0; i < mUsers.size(); i++) {
279 UserInfo profile = mUsers.valueAt(i);
280 if (!isProfileOf(user, profile)) {
281 continue;
282 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100283 if (enabledOnly && !profile.isEnabled()) {
284 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700285 }
286 users.add(profile);
287 }
288 return users;
289 }
290
Jessica Hummelbe81c802014-04-22 15:49:22 +0100291 @Override
292 public UserInfo getProfileParent(int userHandle) {
293 checkManageUsersPermission("get the profile parent");
294 synchronized (mPackagesLock) {
295 UserInfo profile = getUserInfoLocked(userHandle);
296 int parentUserId = profile.profileGroupId;
297 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
298 return null;
299 } else {
300 return getUserInfoLocked(parentUserId);
301 }
302 }
303 }
304
Kenny Guy2a764942014-04-02 13:29:20 +0100305 private boolean isProfileOf(UserInfo user, UserInfo profile) {
306 return user.id == profile.id ||
307 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
308 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000309 }
310
311 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100312 public void setUserEnabled(int userId) {
313 checkManageUsersPermission("enable user");
314 synchronized (mPackagesLock) {
315 UserInfo info = getUserInfoLocked(userId);
316 if (info != null && !info.isEnabled()) {
317 info.flags ^= UserInfo.FLAG_DISABLED;
318 writeUserLocked(info);
319 }
320 }
321 }
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);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400751 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
752 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
753 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
754 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
755 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
756 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
757 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
758 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
759 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_APPS);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400760 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
761 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
762 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800763 serializer.endTag(null, TAG_RESTRICTIONS);
764 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700765 serializer.endTag(null, TAG_USER);
766
767 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700768 userFile.finishWrite(fos);
769 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700770 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700771 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772 }
773 }
774
775 /*
776 * Writes the user list file in this format:
777 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700778 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700779 * <user id="0"></user>
780 * <user id="2"></user>
781 * </users>
782 */
Amith Yamasani13593602012-03-22 16:16:17 -0700783 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700784 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700785 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700786 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700787 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700788 final BufferedOutputStream bos = new BufferedOutputStream(fos);
789
790 // XmlSerializer serializer = XmlUtils.serializerInstance();
791 final XmlSerializer serializer = new FastXmlSerializer();
792 serializer.setOutput(bos, "utf-8");
793 serializer.startDocument(null, true);
794 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
795
796 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700797 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700798 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700799
800 for (int i = 0; i < mUsers.size(); i++) {
801 UserInfo user = mUsers.valueAt(i);
802 serializer.startTag(null, TAG_USER);
803 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
804 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700805 }
806
807 serializer.endTag(null, TAG_USERS);
808
809 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700810 userListFile.finishWrite(fos);
811 } catch (Exception e) {
812 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700813 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700814 }
815 }
816
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800817 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700818 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700819 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700820 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700821 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700822 long creationTime = 0L;
823 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700824 long salt = 0L;
825 String pinHash = null;
826 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100827 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700828 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700829 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800830 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700831
832 FileInputStream fis = null;
833 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700834 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700835 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700836 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700837 XmlPullParser parser = Xml.newPullParser();
838 parser.setInput(fis, null);
839 int type;
840 while ((type = parser.next()) != XmlPullParser.START_TAG
841 && type != XmlPullParser.END_DOCUMENT) {
842 ;
843 }
844
845 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700846 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700847 return null;
848 }
849
850 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700851 int storedId = readIntAttribute(parser, ATTR_ID, -1);
852 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700853 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700854 return null;
855 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700856 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
857 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700858 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700859 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
860 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700861 salt = readLongAttribute(parser, ATTR_SALT, 0L);
862 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
863 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
864 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100865 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
866 UserInfo.NO_PROFILE_GROUP_ID);
867 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
868 // This attribute was added and renamed during development of L.
869 // TODO Remove upgrade path by 1st May 2014
870 profileGroupId = readIntAttribute(parser, "relatedGroupId",
871 UserInfo.NO_PROFILE_GROUP_ID);
872 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700873 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
874 if ("true".equals(valueString)) {
875 partial = true;
876 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700877
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800878 int outerDepth = parser.getDepth();
879 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
880 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
881 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
882 continue;
883 }
884 String tag = parser.getName();
885 if (TAG_NAME.equals(tag)) {
886 type = parser.next();
887 if (type == XmlPullParser.TEXT) {
888 name = parser.getText();
889 }
890 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700891 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
892 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
893 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
894 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
895 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400896 readBoolean(parser, restrictions,
897 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
898 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
899 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400900 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
901 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400902 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
903 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
904 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
905 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
906 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
907 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
908 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
909 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
910 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_APPS);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400911 readBoolean(parser, restrictions,
912 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
913 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
914 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700915 }
916 }
917 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700918
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700919 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700920 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700921 userInfo.creationTime = creationTime;
922 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700923 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100924 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800925 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700926 if (salt != 0L) {
927 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
928 if (pinState == null) {
929 pinState = new RestrictionsPinState();
930 mRestrictionsPinStates.put(id, pinState);
931 }
932 pinState.salt = salt;
933 pinState.pinHash = pinHash;
934 pinState.failedAttempts = failedAttempts;
935 pinState.lastAttemptTime = lastAttemptTime;
936 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700937 return userInfo;
938
939 } catch (IOException ioe) {
940 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800941 } finally {
942 if (fis != null) {
943 try {
944 fis.close();
945 } catch (IOException e) {
946 }
947 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700948 }
949 return null;
950 }
951
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800952 private void readBoolean(XmlPullParser parser, Bundle restrictions,
953 String restrictionKey) {
954 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700955 if (value != null) {
956 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
957 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800958 }
959
960 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
961 throws IOException {
962 if (restrictions.containsKey(restrictionKey)) {
963 xml.attribute(null, restrictionKey,
964 Boolean.toString(restrictions.getBoolean(restrictionKey)));
965 }
966 }
967
Amith Yamasani920ace02012-09-20 22:15:37 -0700968 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
969 String valueString = parser.getAttributeValue(null, attr);
970 if (valueString == null) return defaultValue;
971 try {
972 return Integer.parseInt(valueString);
973 } catch (NumberFormatException nfe) {
974 return defaultValue;
975 }
976 }
977
978 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
979 String valueString = parser.getAttributeValue(null, attr);
980 if (valueString == null) return defaultValue;
981 try {
982 return Long.parseLong(valueString);
983 } catch (NumberFormatException nfe) {
984 return defaultValue;
985 }
986 }
987
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700988 private boolean isPackageInstalled(String pkg, int userId) {
989 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
990 PackageManager.GET_UNINSTALLED_PACKAGES,
991 userId);
992 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
993 return false;
994 }
995 return true;
996 }
997
Amith Yamasanib82add22013-07-09 11:24:44 -0700998 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700999 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
1000 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -07001001 * Does not do any permissions checking.
1002 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001003 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001004 synchronized (mPackagesLock) {
1005 File dir = Environment.getUserSystemDirectory(userId);
1006 String[] files = dir.list();
1007 if (files == null) return;
1008 for (String fileName : files) {
1009 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1010 File resFile = new File(dir, fileName);
1011 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001012 if (all) {
1013 resFile.delete();
1014 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -07001015 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001016 if (!isPackageInstalled(pkg, userId)) {
1017 resFile.delete();
1018 }
1019 }
Amith Yamasanib82add22013-07-09 11:24:44 -07001020 }
1021 }
1022 }
1023 }
1024 }
1025
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001026 /**
1027 * Removes the app restrictions file for a specific package and user id, if it exists.
1028 */
1029 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1030 synchronized (mPackagesLock) {
1031 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001032 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001033 if (resFile.exists()) {
1034 resFile.delete();
1035 }
1036 }
1037 }
1038
Kenny Guya52dc3e2014-02-11 15:33:14 +00001039 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001040 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001041 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001042 if (userId != UserHandle.USER_OWNER) {
1043 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001044 return null;
1045 }
Kenny Guy2a764942014-04-02 13:29:20 +01001046 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001047 }
1048
Amith Yamasani258848d2012-08-10 17:06:33 -07001049 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001050 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001051 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001052 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001053 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001054
Jessica Hummelbe81c802014-04-22 15:49:22 +01001055 private UserInfo createUserInternal(String name, int flags, int parentId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001056 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001057 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001058 try {
1059 synchronized (mInstallLock) {
1060 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001061 UserInfo parent = null;
1062 if (parentId != UserHandle.USER_NULL) {
1063 parent = getUserInfoLocked(parentId);
1064 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001065 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001066 if (isUserLimitReachedLocked()) return null;
1067 int userId = getNextAvailableIdLocked();
1068 userInfo = new UserInfo(userId, name, null, flags);
1069 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1070 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001071 long now = System.currentTimeMillis();
1072 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001073 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001074 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001075 mUsers.put(userId, userInfo);
1076 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001077 if (parent != null) {
1078 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1079 parent.profileGroupId = parent.id;
1080 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001081 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001082 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001083 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001084 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001085 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001086 userInfo.partial = false;
1087 writeUserLocked(userInfo);
1088 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001089 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001090 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001091 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001092 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001093 if (userInfo != null) {
1094 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1095 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1096 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1097 android.Manifest.permission.MANAGE_USERS);
1098 }
1099 } finally {
1100 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001101 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001102 return userInfo;
1103 }
1104
Amith Yamasani0b285492011-04-14 17:35:23 -07001105 /**
1106 * Removes a user and all data directories created for that user. This method should be called
1107 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001108 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001109 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001110 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001111 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001112 final UserInfo user;
1113 synchronized (mPackagesLock) {
1114 user = mUsers.get(userHandle);
1115 if (userHandle == 0 || user == null) {
1116 return false;
1117 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001118 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -07001119 // Set this to a partially created user, so that the user will be purged
1120 // on next startup, in case the runtime stops now before stopping and
1121 // removing the user completely.
1122 user.partial = true;
Adam Connors7b66ed52014-04-14 11:58:10 +01001123 // Mark it as disabled, so that it isn't returned any more when
1124 // profiles are queried.
1125 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani756901d2012-10-12 12:30:07 -07001126 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001127 }
Kenny Guyf8d3a232014-05-15 16:09:52 +01001128
1129 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1130 && user.isManagedProfile()) {
1131 // Send broadcast to notify system that the user removed was a
1132 // managed user.
1133 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1134 }
1135
Amith Yamasani16389312012-10-17 21:20:14 -07001136 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001137 int res;
1138 try {
1139 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1140 new IStopUserCallback.Stub() {
1141 @Override
1142 public void userStopped(int userId) {
1143 finishRemoveUser(userId);
1144 }
1145 @Override
1146 public void userStopAborted(int userId) {
1147 }
1148 });
1149 } catch (RemoteException e) {
1150 return false;
1151 }
1152
1153 return res == ActivityManager.USER_OP_SUCCESS;
1154 }
1155
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001156 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001157 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001158 // Let other services shutdown any activity and clean up their state before completely
1159 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001160 long ident = Binder.clearCallingIdentity();
1161 try {
1162 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1163 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001164 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1165 android.Manifest.permission.MANAGE_USERS,
1166
1167 new BroadcastReceiver() {
1168 @Override
1169 public void onReceive(Context context, Intent intent) {
1170 if (DBG) {
1171 Slog.i(LOG_TAG,
1172 "USER_REMOVED broadcast sent, cleaning up user data "
1173 + userHandle);
1174 }
1175 new Thread() {
1176 public void run() {
1177 synchronized (mInstallLock) {
1178 synchronized (mPackagesLock) {
1179 removeUserStateLocked(userHandle);
1180 }
1181 }
1182 }
1183 }.start();
1184 }
1185 },
1186
1187 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001188 } finally {
1189 Binder.restoreCallingIdentity(ident);
1190 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001191 }
1192
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001193 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001194 // Cleanup package manager settings
1195 mPm.cleanUpUserLILPw(userHandle);
1196
1197 // Remove this user from the list
1198 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001199
1200 // Have user ID linger for several seconds to let external storage VFS
1201 // cache entries expire. This must be greater than the 'entry_valid'
1202 // timeout used by the FUSE daemon.
1203 mHandler.postDelayed(new Runnable() {
1204 @Override
1205 public void run() {
1206 synchronized (mPackagesLock) {
1207 mRemovingUserIds.delete(userHandle);
1208 }
1209 }
1210 }, MINUTE_IN_MILLIS);
1211
Amith Yamasani655d0e22013-06-12 14:19:10 -07001212 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001213 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001214 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001215 userFile.delete();
1216 // Update the user list
1217 writeUserListLocked();
1218 updateUserIdsLocked();
1219 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1220 }
1221
Amith Yamasani61f57372012-08-31 12:12:28 -07001222 private void removeDirectoryRecursive(File parent) {
1223 if (parent.isDirectory()) {
1224 String[] files = parent.list();
1225 for (String filename : files) {
1226 File child = new File(parent, filename);
1227 removeDirectoryRecursive(child);
1228 }
1229 }
1230 parent.delete();
1231 }
1232
Kenny Guyf8d3a232014-05-15 16:09:52 +01001233 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001234 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001235 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1236 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1237 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001238 }
1239
Amith Yamasani2a003292012-08-14 18:25:45 -07001240 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001241 public Bundle getApplicationRestrictions(String packageName) {
1242 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1243 }
1244
1245 @Override
1246 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001247 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001248 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001249 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001250 }
1251 synchronized (mPackagesLock) {
1252 // Read the restrictions from XML
1253 return readApplicationRestrictionsLocked(packageName, userId);
1254 }
1255 }
1256
1257 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001258 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001259 int userId) {
1260 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001261 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001262 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001263 }
1264 synchronized (mPackagesLock) {
1265 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001266 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001267 }
Robin Lee66e5d962014-04-09 16:44:21 +01001268
1269 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1270 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1271 changeIntent.setPackage(packageName);
1272 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1273 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001274 }
1275
Amith Yamasani655d0e22013-06-12 14:19:10 -07001276 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001277 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001278 checkManageUsersPermission("Only system can modify the restrictions pin");
1279 int userId = UserHandle.getCallingUserId();
1280 synchronized (mPackagesLock) {
1281 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1282 if (pinState == null) {
1283 pinState = new RestrictionsPinState();
1284 }
1285 if (newPin == null) {
1286 pinState.salt = 0;
1287 pinState.pinHash = null;
1288 } else {
1289 try {
1290 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1291 } catch (NoSuchAlgorithmException e) {
1292 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1293 }
1294 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1295 pinState.failedAttempts = 0;
1296 }
1297 mRestrictionsPinStates.put(userId, pinState);
1298 writeUserLocked(mUsers.get(userId));
1299 }
1300 return true;
1301 }
1302
1303 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001304 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001305 checkManageUsersPermission("Only system can verify the restrictions pin");
1306 int userId = UserHandle.getCallingUserId();
1307 synchronized (mPackagesLock) {
1308 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1309 // If there's no pin set, return error code
1310 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1311 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1312 } else if (pin == null) {
1313 // If just checking if user can be prompted, return remaining time
1314 int waitTime = getRemainingTimeForPinAttempt(pinState);
1315 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1316 return waitTime;
1317 } else {
1318 int waitTime = getRemainingTimeForPinAttempt(pinState);
1319 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1320 if (waitTime > 0) {
1321 return waitTime;
1322 }
1323 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1324 pinState.failedAttempts = 0;
1325 writeUserLocked(mUsers.get(userId));
1326 return UserManager.PIN_VERIFICATION_SUCCESS;
1327 } else {
1328 pinState.failedAttempts++;
1329 pinState.lastAttemptTime = System.currentTimeMillis();
1330 writeUserLocked(mUsers.get(userId));
1331 return waitTime;
1332 }
1333 }
1334 }
1335 }
1336
1337 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1338 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1339 BACKOFF_TIMES.length - 1);
1340 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1341 BACKOFF_TIMES[backoffIndex] : 0;
1342 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1343 0);
1344 }
1345
1346 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001347 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001348 int userId = UserHandle.getCallingUserId();
1349 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001350 return hasRestrictionsPinLocked(userId);
1351 }
1352 }
1353
1354 private boolean hasRestrictionsPinLocked(int userId) {
1355 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1356 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1357 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001358 }
1359 return true;
1360 }
1361
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001362 @Override
1363 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001364 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001365 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001366 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001367 }
1368
Amith Yamasani5e486f52013-08-07 11:06:44 -07001369 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001370 synchronized (mPackagesLock) {
1371 // Remove all user restrictions
1372 setUserRestrictions(new Bundle(), userHandle);
1373 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001374 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001375 // Remove any app restrictions
1376 cleanAppRestrictions(userHandle, true);
1377 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001378 if (unblockApps) {
1379 unblockAllAppsForUser(userHandle);
1380 }
1381 }
1382
1383 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001384 mHandler.post(new Runnable() {
1385 @Override
1386 public void run() {
1387 List<ApplicationInfo> apps =
1388 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1389 userHandle).getList();
1390 final long ident = Binder.clearCallingIdentity();
1391 try {
1392 for (ApplicationInfo appInfo : apps) {
1393 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1394 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1395 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1396 userHandle);
1397 }
1398 }
1399 } finally {
1400 Binder.restoreCallingIdentity(ident);
1401 }
1402 }
1403 });
1404 }
1405
Amith Yamasani655d0e22013-06-12 14:19:10 -07001406 /*
1407 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1408 * Not the most secure, but it is at least a second level of protection. First level is that
1409 * the file is in a location only readable by the system process.
1410 * @param password the password.
1411 * @param salt the randomly generated salt
1412 * @return the hash of the pattern in a String.
1413 */
1414 private String passwordToHash(String password, long salt) {
1415 if (password == null) {
1416 return null;
1417 }
1418 String algo = null;
1419 String hashed = salt + password;
1420 try {
1421 byte[] saltedPassword = (password + salt).getBytes();
1422 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1423 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1424 hashed = toHex(sha1) + toHex(md5);
1425 } catch (NoSuchAlgorithmException e) {
1426 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1427 }
1428 return hashed;
1429 }
1430
1431 private static String toHex(byte[] ary) {
1432 final String hex = "0123456789ABCDEF";
1433 String ret = "";
1434 for (int i = 0; i < ary.length; i++) {
1435 ret += hex.charAt((ary[i] >> 4) & 0xf);
1436 ret += hex.charAt(ary[i] & 0xf);
1437 }
1438 return ret;
1439 }
1440
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001441 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001442 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001443 try {
1444 return mContext.getPackageManager().getApplicationInfo(packageName,
1445 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1446 } catch (NameNotFoundException nnfe) {
1447 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001448 } finally {
1449 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001450 }
1451 }
1452
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001453 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001454 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001455 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001456 final ArrayList<String> values = new ArrayList<String>();
1457
1458 FileInputStream fis = null;
1459 try {
1460 AtomicFile restrictionsFile =
1461 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001462 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001463 fis = restrictionsFile.openRead();
1464 XmlPullParser parser = Xml.newPullParser();
1465 parser.setInput(fis, null);
1466 int type;
1467 while ((type = parser.next()) != XmlPullParser.START_TAG
1468 && type != XmlPullParser.END_DOCUMENT) {
1469 ;
1470 }
1471
1472 if (type != XmlPullParser.START_TAG) {
1473 Slog.e(LOG_TAG, "Unable to read restrictions file "
1474 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001475 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001476 }
1477
1478 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1479 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1480 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001481 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001482 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1483 if (multiple != null) {
1484 int count = Integer.parseInt(multiple);
1485 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1486 if (type == XmlPullParser.START_TAG
1487 && parser.getName().equals(TAG_VALUE)) {
1488 values.add(parser.nextText().trim());
1489 count--;
1490 }
1491 }
1492 String [] valueStrings = new String[values.size()];
1493 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001494 restrictions.putStringArray(key, valueStrings);
1495 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1496 restrictions.putBoolean(key, Boolean.parseBoolean(
1497 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001498 } else {
1499 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001500 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001501 }
1502 }
1503 }
1504
1505 } catch (IOException ioe) {
1506 } catch (XmlPullParserException pe) {
1507 } finally {
1508 if (fis != null) {
1509 try {
1510 fis.close();
1511 } catch (IOException e) {
1512 }
1513 }
1514 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001515 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001516 }
1517
1518 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001519 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001520 FileOutputStream fos = null;
1521 AtomicFile restrictionsFile = new AtomicFile(
1522 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001523 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001524 try {
1525 fos = restrictionsFile.startWrite();
1526 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1527
1528 // XmlSerializer serializer = XmlUtils.serializerInstance();
1529 final XmlSerializer serializer = new FastXmlSerializer();
1530 serializer.setOutput(bos, "utf-8");
1531 serializer.startDocument(null, true);
1532 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1533
1534 serializer.startTag(null, TAG_RESTRICTIONS);
1535
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001536 for (String key : restrictions.keySet()) {
1537 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001538 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001539 serializer.attribute(null, ATTR_KEY, key);
1540
1541 if (value instanceof Boolean) {
1542 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1543 serializer.text(value.toString());
1544 } else if (value == null || value instanceof String) {
1545 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1546 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001547 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001548 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1549 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001550 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001551 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001552 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001553 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001554 serializer.endTag(null, TAG_VALUE);
1555 }
1556 }
1557 serializer.endTag(null, TAG_ENTRY);
1558 }
1559
1560 serializer.endTag(null, TAG_RESTRICTIONS);
1561
1562 serializer.endDocument();
1563 restrictionsFile.finishWrite(fos);
1564 } catch (Exception e) {
1565 restrictionsFile.failWrite(fos);
1566 Slog.e(LOG_TAG, "Error writing application restrictions list");
1567 }
1568 }
1569
1570 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001571 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001572 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001573 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001574 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001575 }
1576 }
1577
1578 @Override
1579 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001580 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001581 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001582 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001583 }
1584 // Not found
1585 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001586 }
1587 }
1588
Amith Yamasani0b285492011-04-14 17:35:23 -07001589 /**
1590 * Caches the list of user ids in an array, adjusting the array size when necessary.
1591 */
Amith Yamasani13593602012-03-22 16:16:17 -07001592 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001593 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001594 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001595 if (!mUsers.valueAt(i).partial) {
1596 num++;
1597 }
1598 }
Amith Yamasani16389312012-10-17 21:20:14 -07001599 final int[] newUsers = new int[num];
1600 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001601 for (int i = 0; i < mUsers.size(); i++) {
1602 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001603 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001604 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001605 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001606 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001607 }
1608
1609 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001610 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001611 * @param userId the user that was just foregrounded
1612 */
1613 public void userForeground(int userId) {
1614 synchronized (mPackagesLock) {
1615 UserInfo user = mUsers.get(userId);
1616 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001617 if (user == null || user.partial) {
1618 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1619 return;
1620 }
1621 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001622 user.lastLoggedInTime = now;
1623 writeUserLocked(user);
1624 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001625 // If this is not a restricted profile and there is no restrictions pin, clean up
1626 // all restrictions files that might have been left behind, else clean up just the
1627 // ones with uninstalled packages
1628 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1629 final long salt = pinState == null ? 0 : pinState.salt;
1630 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001631 }
1632 }
1633
1634 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001635 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001636 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1637 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001638 * @return
1639 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001640 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001641 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001642 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001643 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001644 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001645 break;
1646 }
1647 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001648 }
Amith Yamasani195263742012-08-21 15:40:12 -07001649 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001650 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001651 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001652
Amith Yamasanifc95e702013-09-26 13:20:17 -07001653 private String packageToRestrictionsFileName(String packageName) {
1654 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1655 }
1656
1657 private String restrictionsFileNameToPackage(String fileName) {
1658 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1659 (int) (fileName.length() - XML_SUFFIX.length()));
1660 }
1661
Amith Yamasani920ace02012-09-20 22:15:37 -07001662 @Override
1663 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1664 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1665 != PackageManager.PERMISSION_GRANTED) {
1666 pw.println("Permission Denial: can't dump UserManager from from pid="
1667 + Binder.getCallingPid()
1668 + ", uid=" + Binder.getCallingUid()
1669 + " without permission "
1670 + android.Manifest.permission.DUMP);
1671 return;
1672 }
1673
1674 long now = System.currentTimeMillis();
1675 StringBuilder sb = new StringBuilder();
1676 synchronized (mPackagesLock) {
1677 pw.println("Users:");
1678 for (int i = 0; i < mUsers.size(); i++) {
1679 UserInfo user = mUsers.valueAt(i);
1680 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001681 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001682 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001683 if (user.partial) pw.print(" <partial>");
1684 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001685 pw.print(" Created: ");
1686 if (user.creationTime == 0) {
1687 pw.println("<unknown>");
1688 } else {
1689 sb.setLength(0);
1690 TimeUtils.formatDuration(now - user.creationTime, sb);
1691 sb.append(" ago");
1692 pw.println(sb);
1693 }
1694 pw.print(" Last logged in: ");
1695 if (user.lastLoggedInTime == 0) {
1696 pw.println("<unknown>");
1697 } else {
1698 sb.setLength(0);
1699 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1700 sb.append(" ago");
1701 pw.println(sb);
1702 }
1703 }
1704 }
1705 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001706
1707 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1708 @Override
1709 public void onPackageRemoved(String pkg, int uid) {
1710 final int userId = this.getChangingUserId();
1711 // Package could be disappearing because it is being blocked, so also check if
1712 // it has been uninstalled.
1713 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1714 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1715 cleanAppRestrictionsForPackage(pkg, userId);
1716 }
1717 }
1718 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001719}