blob: 210e151b10a79713598630bba359c770ada3f7d4 [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;
Emily Bernier7a2b4d12014-04-23 12:51:35 -040025import android.app.admin.DevicePolicyManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.IStopUserCallback;
Alexandra Gherghina385124d2014-04-03 13:37:39 +010027import android.app.admin.DevicePolicyManager;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070028import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070029import android.content.Context;
30import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070031import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070032import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080033import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070035import android.graphics.Bitmap;
36import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080038import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070039import android.os.Environment;
40import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080041import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070043import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070044import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070046import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070047import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070048import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.util.Slog;
50import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070052import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070053import android.util.Xml;
54
Amith Yamasani1a7472e2013-07-02 11:17:30 -070055import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import com.android.internal.util.ArrayUtils;
57import com.android.internal.util.FastXmlSerializer;
58
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.BufferedOutputStream;
64import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070067import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import java.io.FileOutputStream;
69import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070071import java.security.MessageDigest;
72import java.security.NoSuchAlgorithmException;
73import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.util.ArrayList;
75import java.util.List;
76
Amith Yamasani258848d2012-08-10 17:06:33 -070077public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani2a003292012-08-14 18:25:45 -070079 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080
Amith Yamasani16389312012-10-17 21:20:14 -070081 private static final boolean DBG = false;
82
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070085 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070087 private static final String ATTR_CREATION_TIME = "created";
88 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070089 private static final String ATTR_SALT = "salt";
90 private static final String ATTR_PIN_HASH = "pinHash";
91 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
92 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070093 private static final String ATTR_SERIAL_NO = "serialNumber";
94 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070095 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070096 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010097 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800100 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800101 private static final String TAG_ENTRY = "entry";
102 private static final String TAG_VALUE = "value";
103 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700107 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
108 private static final String ATTR_TYPE_STRING = "s";
109 private static final String ATTR_TYPE_BOOLEAN = "b";
110
Amith Yamasani0b285492011-04-14 17:35:23 -0700111 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700116 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800117
Amith Yamasani634cf312012-10-04 17:34:21 -0700118 private static final int MIN_USER_ID = 10;
119
Amith Yamasani5e486f52013-08-07 11:06:44 -0700120 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700121
Amith Yamasani920ace02012-09-20 22:15:37 -0700122 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
123
Amith Yamasani655d0e22013-06-12 14:19:10 -0700124 // Number of attempts before jumping to the next BACKOFF_TIMES slot
125 private static final int BACKOFF_INC_INTERVAL = 5;
126
127 // Amount of time to force the user to wait before entering the PIN again, after failing
128 // BACKOFF_INC_INTERVAL times.
129 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
130
Dianne Hackborn4428e172012-08-24 17:43:05 -0700131 private final Context mContext;
132 private final PackageManagerService mPm;
133 private final Object mInstallLock;
134 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800136 private final Handler mHandler;
137
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private final File mUsersDir;
139 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700140 private final File mBaseUserPath;
141
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800142 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800143 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800144
Amith Yamasani655d0e22013-06-12 14:19:10 -0700145 class RestrictionsPinState {
146 long salt;
147 String pinHash;
148 int failedAttempts;
149 long lastAttemptTime;
150 }
151
152 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
153 new SparseArray<RestrictionsPinState>();
154
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800155 /**
156 * Set of user IDs being actively removed. Removed IDs linger in this set
157 * for several seconds to work around a VFS caching issue.
158 */
159 // @GuardedBy("mPackagesLock")
160 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700161
Amith Yamasani0b285492011-04-14 17:35:23 -0700162 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700163 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700164 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700165 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700166
Amith Yamasani258848d2012-08-10 17:06:33 -0700167 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700168
Dianne Hackborn4428e172012-08-24 17:43:05 -0700169 public static UserManagerService getInstance() {
170 synchronized (UserManagerService.class) {
171 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700173 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700174
175 /**
176 * Available for testing purposes.
177 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700178 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700179 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700180 }
181
Dianne Hackborn4428e172012-08-24 17:43:05 -0700182 /**
183 * Called by package manager to create the service. This is closely
184 * associated with the package manager, and the given lock is the
185 * package manager's own lock.
186 */
187 UserManagerService(Context context, PackageManagerService pm,
188 Object installLock, Object packagesLock) {
189 this(context, pm, installLock, packagesLock,
190 Environment.getDataDirectory(),
191 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700192 }
193
Dianne Hackborn4428e172012-08-24 17:43:05 -0700194 /**
195 * Available for testing purposes.
196 */
197 private UserManagerService(Context context, PackageManagerService pm,
198 Object installLock, Object packagesLock,
199 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700200 mContext = context;
201 mPm = pm;
202 mInstallLock = installLock;
203 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800204 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700205 synchronized (mInstallLock) {
206 synchronized (mPackagesLock) {
207 mUsersDir = new File(dataDir, USER_INFO_DIR);
208 mUsersDir.mkdirs();
209 // Make zeroth user directory, for services to migrate their files to that location
210 File userZeroDir = new File(mUsersDir, "0");
211 userZeroDir.mkdirs();
212 mBaseUserPath = baseUserPath;
213 FileUtils.setPermissions(mUsersDir.toString(),
214 FileUtils.S_IRWXU|FileUtils.S_IRWXG
215 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
216 -1, -1);
217 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
218 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700219 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700220 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
221 for (int i = 0; i < mUsers.size(); i++) {
222 UserInfo ui = mUsers.valueAt(i);
223 if (ui.partial && i != 0) {
224 partials.add(ui);
225 }
226 }
227 for (int i = 0; i < partials.size(); i++) {
228 UserInfo ui = partials.get(i);
229 Slog.w(LOG_TAG, "Removing partially created user #" + i
230 + " (name=" + ui.name + ")");
231 removeUserStateLocked(ui.id);
232 }
233 sInstance = this;
234 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700235 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700236 }
237
238 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700239 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700240 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700241 }
242
243 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700244 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700245 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700246 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700247 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
248 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700249 UserInfo ui = mUsers.valueAt(i);
250 if (ui.partial) {
251 continue;
252 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800253 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700254 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700255 }
Amith Yamasani13593602012-03-22 16:16:17 -0700256 }
257 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700258 }
Amith Yamasani13593602012-03-22 16:16:17 -0700259 }
260
Amith Yamasani258848d2012-08-10 17:06:33 -0700261 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100262 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800263 if (userId != UserHandle.getCallingUserId()) {
264 checkManageUsersPermission("getting profiles related to user " + userId);
265 }
Kenny Guya52dc3e2014-02-11 15:33:14 +0000266 synchronized (mPackagesLock) {
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100267 // Getting the service here is not good for testing purposes. However, this service
268 // is not available when UserManagerService starts up so we need a lazy load.
269
270 DevicePolicyManager dpm = null;
271 if (enabledOnly) {
272 dpm = (DevicePolicyManager)
273 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
274 }
275
Kenny Guya52dc3e2014-02-11 15:33:14 +0000276 UserInfo user = getUserInfoLocked(userId);
277 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
278 for (int i = 0; i < mUsers.size(); i++) {
Kenny Guy2a764942014-04-02 13:29:20 +0100279 UserInfo profile = mUsers.valueAt(i);
280 if (!isProfileOf(user, profile)) {
Kenny Guya52dc3e2014-02-11 15:33:14 +0000281 continue;
282 }
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100283
284 if (enabledOnly && profile.isManagedProfile()) {
285 if (dpm != null) {
286 if(!dpm.isProfileEnabled(profile.id)) {
287 continue;
288 }
289 } else {
290 Log.w(LOG_TAG,
291 "Attempting to reach DevicePolicyManager before it was started");
292 // TODO: There might be system apps that need to call this. Make sure that
293 // DevicePolicyManagerService is ready at that time (otherwise, any default
294 // value is a bad one).
295 throw new IllegalArgumentException(String.format(
296 "Attempting to get enabled profiles for %d before "
297 + "DevicePolicyManagerService has been started.", userId));
298 }
299 }
Kenny Guy2a764942014-04-02 13:29:20 +0100300 users.add(profile);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000301 }
302 return users;
303 }
304 }
305
Kenny Guy2a764942014-04-02 13:29:20 +0100306 private boolean isProfileOf(UserInfo user, UserInfo profile) {
307 return user.id == profile.id ||
308 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
309 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000310 }
311
312 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700313 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700314 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700315 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700316 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700317 }
318 }
319
Amith Yamasani71e6c692013-03-24 17:39:28 -0700320 @Override
321 public boolean isRestricted() {
322 synchronized (mPackagesLock) {
323 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
324 }
325 }
326
Amith Yamasani195263742012-08-21 15:40:12 -0700327 /*
328 * Should be locked on mUsers before calling this.
329 */
330 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700331 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700332 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800333 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700334 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
335 return null;
336 }
337 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700338 }
339
Amith Yamasani13593602012-03-22 16:16:17 -0700340 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700341 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700342 return ArrayUtils.contains(mUserIds, userId);
343 }
344 }
345
Amith Yamasani258848d2012-08-10 17:06:33 -0700346 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700347 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700348 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700349 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700350 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700351 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700352 if (info == null || info.partial) {
353 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
354 return;
355 }
Amith Yamasani13593602012-03-22 16:16:17 -0700356 if (name != null && !name.equals(info.name)) {
357 info.name = name;
358 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700359 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700360 }
361 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700362 if (changed) {
363 sendUserInfoChangedBroadcast(userId);
364 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700365 }
366
Amith Yamasani258848d2012-08-10 17:06:33 -0700367 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700368 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700369 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700370 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700371 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700372 if (info == null || info.partial) {
373 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
374 return;
375 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700376 writeBitmapLocked(info, bitmap);
377 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700378 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700379 sendUserInfoChangedBroadcast(userId);
380 }
381
382 private void sendUserInfoChangedBroadcast(int userId) {
383 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
384 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
385 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700386 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700387 }
388
Amith Yamasani258848d2012-08-10 17:06:33 -0700389 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700390 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700391 checkManageUsersPermission("read users");
392 synchronized (mPackagesLock) {
393 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700394 if (info == null || info.partial) {
395 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
396 return null;
397 }
398 if (info.iconPath == null) {
399 return null;
400 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700401 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700402 }
403 }
404
405 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700406 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700407 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700408 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700409 if (mGuestEnabled != enable) {
410 mGuestEnabled = enable;
411 // Erase any guest user that currently exists
412 for (int i = 0; i < mUsers.size(); i++) {
413 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700414 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700415 if (!enable) {
416 removeUser(user.id);
417 }
418 return;
419 }
420 }
421 // No guest was found
422 if (enable) {
423 createUser("Guest", UserInfo.FLAG_GUEST);
424 }
425 }
426 }
427 }
428
429 @Override
430 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700431 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700432 return mGuestEnabled;
433 }
434 }
435
436 @Override
437 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700438 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700439 // TODO:
440 }
441
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700442 public void makeInitialized(int userId) {
443 checkManageUsersPermission("makeInitialized");
444 synchronized (mPackagesLock) {
445 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700446 if (info == null || info.partial) {
447 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
448 }
449 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700450 info.flags |= UserInfo.FLAG_INITIALIZED;
451 writeUserLocked(info);
452 }
453 }
454 }
455
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800456 @Override
457 public Bundle getUserRestrictions(int userId) {
458 // checkManageUsersPermission("getUserRestrictions");
459
460 synchronized (mPackagesLock) {
461 Bundle restrictions = mUserRestrictions.get(userId);
462 return restrictions != null ? restrictions : Bundle.EMPTY;
463 }
464 }
465
466 @Override
467 public void setUserRestrictions(Bundle restrictions, int userId) {
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400468 checkProfileOwnerOrManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700469 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800470
471 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700472 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800473 mUserRestrictions.get(userId).putAll(restrictions);
474 writeUserLocked(mUsers.get(userId));
475 }
476 }
477
Amith Yamasani258848d2012-08-10 17:06:33 -0700478 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700479 * Check if we've hit the limit of how many users can be created.
480 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700481 private boolean isUserLimitReachedLocked() {
482 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700483 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700484 }
485
486 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700487 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700488 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700489 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700490 *
491 * @param message used as message if SecurityException is thrown
492 * @throws SecurityException if the caller is not system or root
493 */
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400494 private final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700495 final int uid = Binder.getCallingUid();
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400496
497 if (missingManageUsersPermission(uid)) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700498 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700499 }
500 }
501
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400502 /**
503 * Enforces that only the system UID, root's UID, apps that have the
504 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
505 * permission, the profile owner, or the device owner can make certain calls to the
506 * UserManager.
507 *
508 * @param message used as message if SecurityException is thrown
509 * @throws SecurityException if the caller is not system, root, or device
510 * owner
511 */
512 private final void checkProfileOwnerOrManageUsersPermission(String message) {
513 final int uid = Binder.getCallingUid();
514 boolean isProfileOwner = false;
515 if (mContext != null && mContext.getPackageManager() != null) {
516 String[] pkgs = mContext.getPackageManager().getPackagesForUid(uid);
517 DevicePolicyManager dpm =
518 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
519 if (dpm != null) {
520 for (String pkg : pkgs) {
521 if (dpm.isDeviceOwnerApp(pkg) || dpm.isProfileOwnerApp(pkg)) {
522 isProfileOwner = true;
523 }
524 }
525 }
526 }
527
528 if (missingManageUsersPermission(uid) && !isProfileOwner) {
529 throw new SecurityException(
530 "You need MANAGE_USERS permission or device owner privileges to: " + message);
531 }
532 }
533
534 private boolean missingManageUsersPermission(int uid) {
535 return uid != Process.SYSTEM_UID && uid != 0
536 && ActivityManager.checkComponentPermission(
537 android.Manifest.permission.MANAGE_USERS,
538 uid, -1, true) != PackageManager.PERMISSION_GRANTED;
539 }
540
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700541 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700542 try {
543 File dir = new File(mUsersDir, Integer.toString(info.id));
544 File file = new File(dir, USER_PHOTO_FILENAME);
545 if (!dir.exists()) {
546 dir.mkdir();
547 FileUtils.setPermissions(
548 dir.getPath(),
549 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
550 -1, -1);
551 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700552 FileOutputStream os;
553 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700554 info.iconPath = file.getAbsolutePath();
555 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700556 try {
557 os.close();
558 } catch (IOException ioe) {
559 // What the ... !
560 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700561 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700562 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700563 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700564 }
565
Amith Yamasani0b285492011-04-14 17:35:23 -0700566 /**
567 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
568 * cache it elsewhere.
569 * @return the array of user ids.
570 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700571 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700572 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700573 return mUserIds;
574 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700575 }
576
Dianne Hackborn4428e172012-08-24 17:43:05 -0700577 int[] getUserIdsLPr() {
578 return mUserIds;
579 }
580
Amith Yamasani13593602012-03-22 16:16:17 -0700581 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700582 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700583 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700584 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700585 return;
586 }
587 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700588 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700589 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700590 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700591 XmlPullParser parser = Xml.newPullParser();
592 parser.setInput(fis, null);
593 int type;
594 while ((type = parser.next()) != XmlPullParser.START_TAG
595 && type != XmlPullParser.END_DOCUMENT) {
596 ;
597 }
598
599 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700600 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700601 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700602 return;
603 }
604
Amith Yamasani2a003292012-08-14 18:25:45 -0700605 mNextSerialNumber = -1;
606 if (parser.getName().equals(TAG_USERS)) {
607 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
608 if (lastSerialNumber != null) {
609 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
610 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700611 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
612 if (versionNumber != null) {
613 mUserVersion = Integer.parseInt(versionNumber);
614 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700615 }
616
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700617 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
618 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
619 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800620 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700621
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700622 if (user != null) {
623 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700624 if (user.isGuest()) {
625 mGuestEnabled = true;
626 }
627 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
628 mNextSerialNumber = user.id + 1;
629 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700630 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700631 }
632 }
Amith Yamasani13593602012-03-22 16:16:17 -0700633 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700634 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700635 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700636 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700637 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700638 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800639 } finally {
640 if (fis != null) {
641 try {
642 fis.close();
643 } catch (IOException e) {
644 }
645 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700646 }
647 }
648
Amith Yamasani6f34b412012-10-22 18:19:27 -0700649 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800650 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700651 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700652 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700653 int userVersion = mUserVersion;
654 if (userVersion < 1) {
655 // Assign a proper name for the owner, if not initialized correctly before
656 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
657 if ("Primary".equals(user.name)) {
658 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
659 writeUserLocked(user);
660 }
661 userVersion = 1;
662 }
663
Amith Yamasanibc9625052012-11-15 14:39:18 -0800664 if (userVersion < 2) {
665 // Owner should be marked as initialized
666 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
667 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
668 user.flags |= UserInfo.FLAG_INITIALIZED;
669 writeUserLocked(user);
670 }
671 userVersion = 2;
672 }
673
Amith Yamasani350962c2013-08-06 11:18:53 -0700674
Amith Yamasani5e486f52013-08-07 11:06:44 -0700675 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700676 userVersion = 4;
677 }
678
Amith Yamasani6f34b412012-10-22 18:19:27 -0700679 if (userVersion < USER_VERSION) {
680 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
681 + USER_VERSION);
682 } else {
683 mUserVersion = userVersion;
684 writeUserListLocked();
685 }
686 }
687
Amith Yamasani13593602012-03-22 16:16:17 -0700688 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700689 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800690 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700691 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700692 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700693 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700694 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400695 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800696
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500697 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800698 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
699
Amith Yamasani13593602012-03-22 16:16:17 -0700700 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700701
Amith Yamasani13593602012-03-22 16:16:17 -0700702 writeUserListLocked();
703 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700704 }
705
706 /*
707 * Writes the user file in this format:
708 *
709 * <user flags="20039023" id="0">
710 * <name>Primary</name>
711 * </user>
712 */
Amith Yamasani13593602012-03-22 16:16:17 -0700713 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700714 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700715 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700716 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700717 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700718 final BufferedOutputStream bos = new BufferedOutputStream(fos);
719
720 // XmlSerializer serializer = XmlUtils.serializerInstance();
721 final XmlSerializer serializer = new FastXmlSerializer();
722 serializer.setOutput(bos, "utf-8");
723 serializer.startDocument(null, true);
724 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
725
726 serializer.startTag(null, TAG_USER);
727 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700728 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700729 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700730 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
731 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
732 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700733 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
734 if (pinState != null) {
735 if (pinState.salt != 0) {
736 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
737 }
738 if (pinState.pinHash != null) {
739 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
740 }
741 if (pinState.failedAttempts != 0) {
742 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
743 Integer.toString(pinState.failedAttempts));
744 serializer.attribute(null, ATTR_LAST_RETRY_MS,
745 Long.toString(pinState.lastAttemptTime));
746 }
747 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700748 if (userInfo.iconPath != null) {
749 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
750 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700751 if (userInfo.partial) {
752 serializer.attribute(null, ATTR_PARTIAL, "true");
753 }
Kenny Guy2a764942014-04-02 13:29:20 +0100754 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
755 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
756 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000757 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700758
759 serializer.startTag(null, TAG_NAME);
760 serializer.text(userInfo.name);
761 serializer.endTag(null, TAG_NAME);
762
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800763 Bundle restrictions = mUserRestrictions.get(userInfo.id);
764 if (restrictions != null) {
765 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700766 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
767 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
768 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
769 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
770 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400771 writeBoolean(serializer, restrictions,
772 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
773 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
774 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400775 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
776 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800777 serializer.endTag(null, TAG_RESTRICTIONS);
778 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700779 serializer.endTag(null, TAG_USER);
780
781 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700782 userFile.finishWrite(fos);
783 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700784 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700785 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700786 }
787 }
788
789 /*
790 * Writes the user list file in this format:
791 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700792 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700793 * <user id="0"></user>
794 * <user id="2"></user>
795 * </users>
796 */
Amith Yamasani13593602012-03-22 16:16:17 -0700797 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700798 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700799 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700800 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700801 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700802 final BufferedOutputStream bos = new BufferedOutputStream(fos);
803
804 // XmlSerializer serializer = XmlUtils.serializerInstance();
805 final XmlSerializer serializer = new FastXmlSerializer();
806 serializer.setOutput(bos, "utf-8");
807 serializer.startDocument(null, true);
808 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
809
810 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700811 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700812 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700813
814 for (int i = 0; i < mUsers.size(); i++) {
815 UserInfo user = mUsers.valueAt(i);
816 serializer.startTag(null, TAG_USER);
817 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
818 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700819 }
820
821 serializer.endTag(null, TAG_USERS);
822
823 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700824 userListFile.finishWrite(fos);
825 } catch (Exception e) {
826 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700827 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700828 }
829 }
830
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800831 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700832 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700833 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700834 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700835 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700836 long creationTime = 0L;
837 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700838 long salt = 0L;
839 String pinHash = null;
840 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100841 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700842 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700843 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800844 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700845
846 FileInputStream fis = null;
847 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700848 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700849 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700850 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700851 XmlPullParser parser = Xml.newPullParser();
852 parser.setInput(fis, null);
853 int type;
854 while ((type = parser.next()) != XmlPullParser.START_TAG
855 && type != XmlPullParser.END_DOCUMENT) {
856 ;
857 }
858
859 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700860 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700861 return null;
862 }
863
864 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700865 int storedId = readIntAttribute(parser, ATTR_ID, -1);
866 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700867 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700868 return null;
869 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700870 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
871 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700872 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700873 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
874 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700875 salt = readLongAttribute(parser, ATTR_SALT, 0L);
876 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
877 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
878 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100879 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
880 UserInfo.NO_PROFILE_GROUP_ID);
881 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
882 // This attribute was added and renamed during development of L.
883 // TODO Remove upgrade path by 1st May 2014
884 profileGroupId = readIntAttribute(parser, "relatedGroupId",
885 UserInfo.NO_PROFILE_GROUP_ID);
886 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700887 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
888 if ("true".equals(valueString)) {
889 partial = true;
890 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700891
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800892 int outerDepth = parser.getDepth();
893 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
894 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
895 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
896 continue;
897 }
898 String tag = parser.getName();
899 if (TAG_NAME.equals(tag)) {
900 type = parser.next();
901 if (type == XmlPullParser.TEXT) {
902 name = parser.getText();
903 }
904 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700905 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
906 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
907 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
908 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
909 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400910 readBoolean(parser, restrictions,
911 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
912 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
913 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400914 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
915 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700916 }
917 }
918 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700919
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700920 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700921 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700922 userInfo.creationTime = creationTime;
923 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700924 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100925 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800926 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700927 if (salt != 0L) {
928 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
929 if (pinState == null) {
930 pinState = new RestrictionsPinState();
931 mRestrictionsPinStates.put(id, pinState);
932 }
933 pinState.salt = salt;
934 pinState.pinHash = pinHash;
935 pinState.failedAttempts = failedAttempts;
936 pinState.lastAttemptTime = lastAttemptTime;
937 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700938 return userInfo;
939
940 } catch (IOException ioe) {
941 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800942 } finally {
943 if (fis != null) {
944 try {
945 fis.close();
946 } catch (IOException e) {
947 }
948 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700949 }
950 return null;
951 }
952
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800953 private void readBoolean(XmlPullParser parser, Bundle restrictions,
954 String restrictionKey) {
955 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700956 if (value != null) {
957 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
958 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800959 }
960
961 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
962 throws IOException {
963 if (restrictions.containsKey(restrictionKey)) {
964 xml.attribute(null, restrictionKey,
965 Boolean.toString(restrictions.getBoolean(restrictionKey)));
966 }
967 }
968
Amith Yamasani920ace02012-09-20 22:15:37 -0700969 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
970 String valueString = parser.getAttributeValue(null, attr);
971 if (valueString == null) return defaultValue;
972 try {
973 return Integer.parseInt(valueString);
974 } catch (NumberFormatException nfe) {
975 return defaultValue;
976 }
977 }
978
979 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
980 String valueString = parser.getAttributeValue(null, attr);
981 if (valueString == null) return defaultValue;
982 try {
983 return Long.parseLong(valueString);
984 } catch (NumberFormatException nfe) {
985 return defaultValue;
986 }
987 }
988
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700989 private boolean isPackageInstalled(String pkg, int userId) {
990 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
991 PackageManager.GET_UNINSTALLED_PACKAGES,
992 userId);
993 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
994 return false;
995 }
996 return true;
997 }
998
Amith Yamasanib82add22013-07-09 11:24:44 -0700999 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001000 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
1001 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -07001002 * Does not do any permissions checking.
1003 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001004 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001005 synchronized (mPackagesLock) {
1006 File dir = Environment.getUserSystemDirectory(userId);
1007 String[] files = dir.list();
1008 if (files == null) return;
1009 for (String fileName : files) {
1010 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1011 File resFile = new File(dir, fileName);
1012 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001013 if (all) {
1014 resFile.delete();
1015 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -07001016 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001017 if (!isPackageInstalled(pkg, userId)) {
1018 resFile.delete();
1019 }
1020 }
Amith Yamasanib82add22013-07-09 11:24:44 -07001021 }
1022 }
1023 }
1024 }
1025 }
1026
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001027 /**
1028 * Removes the app restrictions file for a specific package and user id, if it exists.
1029 */
1030 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1031 synchronized (mPackagesLock) {
1032 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001033 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001034 if (resFile.exists()) {
1035 resFile.delete();
1036 }
1037 }
1038 }
1039
Kenny Guy2a764942014-04-02 13:29:20 +01001040 private int getNextProfileGroupIdLocked() {
1041 int maxGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001042 for (int i = 0; i < mUsers.size(); i++) {
1043 UserInfo ui = mUsers.valueAt(i);
Kenny Guy2a764942014-04-02 13:29:20 +01001044 if (maxGroupId < ui.profileGroupId) {
1045 maxGroupId = ui.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001046 }
1047 }
1048 return maxGroupId + 1;
1049 }
1050
1051 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001052 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001053 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001054 if (userId != UserHandle.USER_OWNER) {
1055 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001056 return null;
1057 }
Kenny Guy2a764942014-04-02 13:29:20 +01001058 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001059 }
1060
Amith Yamasani258848d2012-08-10 17:06:33 -07001061 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001062 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001063 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001064 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001065 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001066
Kenny Guy2a764942014-04-02 13:29:20 +01001067 private UserInfo createUserInternal(String name, int flags, int profileId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001068 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001069 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001070 try {
1071 synchronized (mInstallLock) {
1072 synchronized (mPackagesLock) {
Kenny Guy2a764942014-04-02 13:29:20 +01001073 UserInfo profile = null;
1074 if (profileId != UserHandle.USER_NULL) {
1075 profile = getUserInfoLocked(profileId);
1076 if (profile == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001077 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001078 if (isUserLimitReachedLocked()) return null;
1079 int userId = getNextAvailableIdLocked();
1080 userInfo = new UserInfo(userId, name, null, flags);
1081 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1082 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001083 long now = System.currentTimeMillis();
1084 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001085 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001086 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001087 mUsers.put(userId, userInfo);
1088 writeUserListLocked();
Kenny Guy2a764942014-04-02 13:29:20 +01001089 if (profile != null) {
1090 if (profile.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1091 profile.profileGroupId = getNextProfileGroupIdLocked();
1092 writeUserLocked(profile);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001093 }
Kenny Guy2a764942014-04-02 13:29:20 +01001094 userInfo.profileGroupId = profile.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001095 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001096 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001097 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001098 userInfo.partial = false;
1099 writeUserLocked(userInfo);
1100 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001101 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001102 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001103 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001104 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001105 if (userInfo != null) {
1106 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1107 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1108 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1109 android.Manifest.permission.MANAGE_USERS);
1110 }
1111 } finally {
1112 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001113 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001114 return userInfo;
1115 }
1116
Amith Yamasani0b285492011-04-14 17:35:23 -07001117 /**
1118 * Removes a user and all data directories created for that user. This method should be called
1119 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001120 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001121 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001122 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001123 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001124 final UserInfo user;
1125 synchronized (mPackagesLock) {
1126 user = mUsers.get(userHandle);
1127 if (userHandle == 0 || user == null) {
1128 return false;
1129 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001130 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -07001131 // Set this to a partially created user, so that the user will be purged
1132 // on next startup, in case the runtime stops now before stopping and
1133 // removing the user completely.
1134 user.partial = true;
1135 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001136 }
Amith Yamasani16389312012-10-17 21:20:14 -07001137 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001138 int res;
1139 try {
1140 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1141 new IStopUserCallback.Stub() {
1142 @Override
1143 public void userStopped(int userId) {
1144 finishRemoveUser(userId);
1145 }
1146 @Override
1147 public void userStopAborted(int userId) {
1148 }
1149 });
1150 } catch (RemoteException e) {
1151 return false;
1152 }
1153
1154 return res == ActivityManager.USER_OP_SUCCESS;
1155 }
1156
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001157 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001158 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001159 // Let other services shutdown any activity and clean up their state before completely
1160 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001161 long ident = Binder.clearCallingIdentity();
1162 try {
1163 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1164 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001165 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1166 android.Manifest.permission.MANAGE_USERS,
1167
1168 new BroadcastReceiver() {
1169 @Override
1170 public void onReceive(Context context, Intent intent) {
1171 if (DBG) {
1172 Slog.i(LOG_TAG,
1173 "USER_REMOVED broadcast sent, cleaning up user data "
1174 + userHandle);
1175 }
1176 new Thread() {
1177 public void run() {
1178 synchronized (mInstallLock) {
1179 synchronized (mPackagesLock) {
1180 removeUserStateLocked(userHandle);
1181 }
1182 }
1183 }
1184 }.start();
1185 }
1186 },
1187
1188 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001189 } finally {
1190 Binder.restoreCallingIdentity(ident);
1191 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001192 }
1193
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001194 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001195 // Cleanup package manager settings
1196 mPm.cleanUpUserLILPw(userHandle);
1197
1198 // Remove this user from the list
1199 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001200
1201 // Have user ID linger for several seconds to let external storage VFS
1202 // cache entries expire. This must be greater than the 'entry_valid'
1203 // timeout used by the FUSE daemon.
1204 mHandler.postDelayed(new Runnable() {
1205 @Override
1206 public void run() {
1207 synchronized (mPackagesLock) {
1208 mRemovingUserIds.delete(userHandle);
1209 }
1210 }
1211 }, MINUTE_IN_MILLIS);
1212
Amith Yamasani655d0e22013-06-12 14:19:10 -07001213 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001214 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001215 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001216 userFile.delete();
1217 // Update the user list
1218 writeUserListLocked();
1219 updateUserIdsLocked();
1220 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1221 }
1222
Amith Yamasani61f57372012-08-31 12:12:28 -07001223 private void removeDirectoryRecursive(File parent) {
1224 if (parent.isDirectory()) {
1225 String[] files = parent.list();
1226 for (String filename : files) {
1227 File child = new File(parent, filename);
1228 removeDirectoryRecursive(child);
1229 }
1230 }
1231 parent.delete();
1232 }
1233
Amith Yamasani2a003292012-08-14 18:25:45 -07001234 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001235 public Bundle getApplicationRestrictions(String packageName) {
1236 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1237 }
1238
1239 @Override
1240 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001241 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001242 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001243 checkProfileOwnerOrManageUsersPermission(
1244 "Only system or device owner can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001245 }
1246 synchronized (mPackagesLock) {
1247 // Read the restrictions from XML
1248 return readApplicationRestrictionsLocked(packageName, userId);
1249 }
1250 }
1251
1252 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001253 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001254 int userId) {
1255 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001256 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001257 checkProfileOwnerOrManageUsersPermission(
1258 "Only system or device owner can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001259 }
1260 synchronized (mPackagesLock) {
1261 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001262 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001263 }
Robin Lee66e5d962014-04-09 16:44:21 +01001264
1265 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1266 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1267 changeIntent.setPackage(packageName);
1268 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1269 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001270 }
1271
Amith Yamasani655d0e22013-06-12 14:19:10 -07001272 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001273 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001274 checkManageUsersPermission("Only system can modify the restrictions pin");
1275 int userId = UserHandle.getCallingUserId();
1276 synchronized (mPackagesLock) {
1277 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1278 if (pinState == null) {
1279 pinState = new RestrictionsPinState();
1280 }
1281 if (newPin == null) {
1282 pinState.salt = 0;
1283 pinState.pinHash = null;
1284 } else {
1285 try {
1286 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1287 } catch (NoSuchAlgorithmException e) {
1288 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1289 }
1290 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1291 pinState.failedAttempts = 0;
1292 }
1293 mRestrictionsPinStates.put(userId, pinState);
1294 writeUserLocked(mUsers.get(userId));
1295 }
1296 return true;
1297 }
1298
1299 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001300 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001301 checkManageUsersPermission("Only system can verify the restrictions pin");
1302 int userId = UserHandle.getCallingUserId();
1303 synchronized (mPackagesLock) {
1304 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1305 // If there's no pin set, return error code
1306 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1307 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1308 } else if (pin == null) {
1309 // If just checking if user can be prompted, return remaining time
1310 int waitTime = getRemainingTimeForPinAttempt(pinState);
1311 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1312 return waitTime;
1313 } else {
1314 int waitTime = getRemainingTimeForPinAttempt(pinState);
1315 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1316 if (waitTime > 0) {
1317 return waitTime;
1318 }
1319 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1320 pinState.failedAttempts = 0;
1321 writeUserLocked(mUsers.get(userId));
1322 return UserManager.PIN_VERIFICATION_SUCCESS;
1323 } else {
1324 pinState.failedAttempts++;
1325 pinState.lastAttemptTime = System.currentTimeMillis();
1326 writeUserLocked(mUsers.get(userId));
1327 return waitTime;
1328 }
1329 }
1330 }
1331 }
1332
1333 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1334 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1335 BACKOFF_TIMES.length - 1);
1336 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1337 BACKOFF_TIMES[backoffIndex] : 0;
1338 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1339 0);
1340 }
1341
1342 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001343 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001344 int userId = UserHandle.getCallingUserId();
1345 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001346 return hasRestrictionsPinLocked(userId);
1347 }
1348 }
1349
1350 private boolean hasRestrictionsPinLocked(int userId) {
1351 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1352 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1353 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001354 }
1355 return true;
1356 }
1357
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001358 @Override
1359 public void removeRestrictions() {
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001360 checkProfileOwnerOrManageUsersPermission(
1361 "Only system or device owner can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001362 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001363 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001364 }
1365
Amith Yamasani5e486f52013-08-07 11:06:44 -07001366 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001367 synchronized (mPackagesLock) {
1368 // Remove all user restrictions
1369 setUserRestrictions(new Bundle(), userHandle);
1370 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001371 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001372 // Remove any app restrictions
1373 cleanAppRestrictions(userHandle, true);
1374 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001375 if (unblockApps) {
1376 unblockAllAppsForUser(userHandle);
1377 }
1378 }
1379
1380 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001381 mHandler.post(new Runnable() {
1382 @Override
1383 public void run() {
1384 List<ApplicationInfo> apps =
1385 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1386 userHandle).getList();
1387 final long ident = Binder.clearCallingIdentity();
1388 try {
1389 for (ApplicationInfo appInfo : apps) {
1390 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1391 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1392 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1393 userHandle);
1394 }
1395 }
1396 } finally {
1397 Binder.restoreCallingIdentity(ident);
1398 }
1399 }
1400 });
1401 }
1402
Amith Yamasani655d0e22013-06-12 14:19:10 -07001403 /*
1404 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1405 * Not the most secure, but it is at least a second level of protection. First level is that
1406 * the file is in a location only readable by the system process.
1407 * @param password the password.
1408 * @param salt the randomly generated salt
1409 * @return the hash of the pattern in a String.
1410 */
1411 private String passwordToHash(String password, long salt) {
1412 if (password == null) {
1413 return null;
1414 }
1415 String algo = null;
1416 String hashed = salt + password;
1417 try {
1418 byte[] saltedPassword = (password + salt).getBytes();
1419 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1420 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1421 hashed = toHex(sha1) + toHex(md5);
1422 } catch (NoSuchAlgorithmException e) {
1423 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1424 }
1425 return hashed;
1426 }
1427
1428 private static String toHex(byte[] ary) {
1429 final String hex = "0123456789ABCDEF";
1430 String ret = "";
1431 for (int i = 0; i < ary.length; i++) {
1432 ret += hex.charAt((ary[i] >> 4) & 0xf);
1433 ret += hex.charAt(ary[i] & 0xf);
1434 }
1435 return ret;
1436 }
1437
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001438 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001439 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001440 try {
1441 return mContext.getPackageManager().getApplicationInfo(packageName,
1442 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1443 } catch (NameNotFoundException nnfe) {
1444 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001445 } finally {
1446 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001447 }
1448 }
1449
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001450 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001451 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001452 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001453 final ArrayList<String> values = new ArrayList<String>();
1454
1455 FileInputStream fis = null;
1456 try {
1457 AtomicFile restrictionsFile =
1458 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001459 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001460 fis = restrictionsFile.openRead();
1461 XmlPullParser parser = Xml.newPullParser();
1462 parser.setInput(fis, null);
1463 int type;
1464 while ((type = parser.next()) != XmlPullParser.START_TAG
1465 && type != XmlPullParser.END_DOCUMENT) {
1466 ;
1467 }
1468
1469 if (type != XmlPullParser.START_TAG) {
1470 Slog.e(LOG_TAG, "Unable to read restrictions file "
1471 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001472 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001473 }
1474
1475 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1476 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1477 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001478 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001479 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1480 if (multiple != null) {
1481 int count = Integer.parseInt(multiple);
1482 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1483 if (type == XmlPullParser.START_TAG
1484 && parser.getName().equals(TAG_VALUE)) {
1485 values.add(parser.nextText().trim());
1486 count--;
1487 }
1488 }
1489 String [] valueStrings = new String[values.size()];
1490 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001491 restrictions.putStringArray(key, valueStrings);
1492 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1493 restrictions.putBoolean(key, Boolean.parseBoolean(
1494 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001495 } else {
1496 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001497 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001498 }
1499 }
1500 }
1501
1502 } catch (IOException ioe) {
1503 } catch (XmlPullParserException pe) {
1504 } finally {
1505 if (fis != null) {
1506 try {
1507 fis.close();
1508 } catch (IOException e) {
1509 }
1510 }
1511 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001512 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001513 }
1514
1515 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001516 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001517 FileOutputStream fos = null;
1518 AtomicFile restrictionsFile = new AtomicFile(
1519 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001520 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001521 try {
1522 fos = restrictionsFile.startWrite();
1523 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1524
1525 // XmlSerializer serializer = XmlUtils.serializerInstance();
1526 final XmlSerializer serializer = new FastXmlSerializer();
1527 serializer.setOutput(bos, "utf-8");
1528 serializer.startDocument(null, true);
1529 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1530
1531 serializer.startTag(null, TAG_RESTRICTIONS);
1532
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001533 for (String key : restrictions.keySet()) {
1534 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001535 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001536 serializer.attribute(null, ATTR_KEY, key);
1537
1538 if (value instanceof Boolean) {
1539 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1540 serializer.text(value.toString());
1541 } else if (value == null || value instanceof String) {
1542 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1543 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001544 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001545 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1546 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001547 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001548 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001549 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001550 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001551 serializer.endTag(null, TAG_VALUE);
1552 }
1553 }
1554 serializer.endTag(null, TAG_ENTRY);
1555 }
1556
1557 serializer.endTag(null, TAG_RESTRICTIONS);
1558
1559 serializer.endDocument();
1560 restrictionsFile.finishWrite(fos);
1561 } catch (Exception e) {
1562 restrictionsFile.failWrite(fos);
1563 Slog.e(LOG_TAG, "Error writing application restrictions list");
1564 }
1565 }
1566
1567 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001568 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001569 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001570 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001571 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001572 }
1573 }
1574
1575 @Override
1576 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001577 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001578 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001579 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001580 }
1581 // Not found
1582 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001583 }
1584 }
1585
Amith Yamasani0b285492011-04-14 17:35:23 -07001586 /**
1587 * Caches the list of user ids in an array, adjusting the array size when necessary.
1588 */
Amith Yamasani13593602012-03-22 16:16:17 -07001589 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001590 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001591 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001592 if (!mUsers.valueAt(i).partial) {
1593 num++;
1594 }
1595 }
Amith Yamasani16389312012-10-17 21:20:14 -07001596 final int[] newUsers = new int[num];
1597 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001598 for (int i = 0; i < mUsers.size(); i++) {
1599 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001600 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001601 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001602 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001603 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001604 }
1605
1606 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001607 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001608 * @param userId the user that was just foregrounded
1609 */
1610 public void userForeground(int userId) {
1611 synchronized (mPackagesLock) {
1612 UserInfo user = mUsers.get(userId);
1613 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001614 if (user == null || user.partial) {
1615 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1616 return;
1617 }
1618 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001619 user.lastLoggedInTime = now;
1620 writeUserLocked(user);
1621 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001622 // If this is not a restricted profile and there is no restrictions pin, clean up
1623 // all restrictions files that might have been left behind, else clean up just the
1624 // ones with uninstalled packages
1625 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1626 final long salt = pinState == null ? 0 : pinState.salt;
1627 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001628 }
1629 }
1630
1631 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001632 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001633 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1634 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001635 * @return
1636 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001637 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001638 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001639 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001640 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001641 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001642 break;
1643 }
1644 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001645 }
Amith Yamasani195263742012-08-21 15:40:12 -07001646 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001647 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001648 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001649
Amith Yamasanifc95e702013-09-26 13:20:17 -07001650 private String packageToRestrictionsFileName(String packageName) {
1651 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1652 }
1653
1654 private String restrictionsFileNameToPackage(String fileName) {
1655 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1656 (int) (fileName.length() - XML_SUFFIX.length()));
1657 }
1658
Amith Yamasani920ace02012-09-20 22:15:37 -07001659 @Override
1660 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1661 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1662 != PackageManager.PERMISSION_GRANTED) {
1663 pw.println("Permission Denial: can't dump UserManager from from pid="
1664 + Binder.getCallingPid()
1665 + ", uid=" + Binder.getCallingUid()
1666 + " without permission "
1667 + android.Manifest.permission.DUMP);
1668 return;
1669 }
1670
1671 long now = System.currentTimeMillis();
1672 StringBuilder sb = new StringBuilder();
1673 synchronized (mPackagesLock) {
1674 pw.println("Users:");
1675 for (int i = 0; i < mUsers.size(); i++) {
1676 UserInfo user = mUsers.valueAt(i);
1677 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001678 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001679 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001680 if (user.partial) pw.print(" <partial>");
1681 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001682 pw.print(" Created: ");
1683 if (user.creationTime == 0) {
1684 pw.println("<unknown>");
1685 } else {
1686 sb.setLength(0);
1687 TimeUtils.formatDuration(now - user.creationTime, sb);
1688 sb.append(" ago");
1689 pw.println(sb);
1690 }
1691 pw.print(" Last logged in: ");
1692 if (user.lastLoggedInTime == 0) {
1693 pw.println("<unknown>");
1694 } else {
1695 sb.setLength(0);
1696 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1697 sb.append(" ago");
1698 pw.println(sb);
1699 }
1700 }
1701 }
1702 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001703
1704 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1705 @Override
1706 public void onPackageRemoved(String pkg, int uid) {
1707 final int userId = this.getChangingUserId();
1708 // Package could be disappearing because it is being blocked, so also check if
1709 // it has been uninstalled.
1710 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1711 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1712 cleanAppRestrictionsForPackage(pkg, userId);
1713 }
1714 }
1715 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001716}