blob: 53db9efa1474bfecde2323dfb138ab900a510854 [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;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070027import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
35import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070044import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070045import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070046import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070047import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070048import android.util.Slog;
49import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080050import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070051import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Xml;
53
Amith Yamasani1a7472e2013-07-02 11:17:30 -070054import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080055import com.android.internal.util.ArrayUtils;
56import com.android.internal.util.FastXmlSerializer;
57
58import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60import org.xmlpull.v1.XmlSerializer;
61
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import java.io.BufferedOutputStream;
63import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070064import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070065import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070066import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import java.io.FileOutputStream;
68import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070069import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070070import java.security.MessageDigest;
71import java.security.NoSuchAlgorithmException;
72import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073import java.util.ArrayList;
74import java.util.List;
75
Amith Yamasani258848d2012-08-10 17:06:33 -070076public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070077
Amith Yamasani2a003292012-08-14 18:25:45 -070078 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070079
Amith Yamasani16389312012-10-17 21:20:14 -070080 private static final boolean DBG = false;
81
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070084 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070086 private static final String ATTR_CREATION_TIME = "created";
87 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070088 private static final String ATTR_SALT = "salt";
89 private static final String ATTR_PIN_HASH = "pinHash";
90 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
91 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070092 private static final String ATTR_SERIAL_NO = "serialNumber";
93 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070094 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070095 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010096 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080099 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800100 private static final String TAG_ENTRY = "entry";
101 private static final String TAG_VALUE = "value";
102 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700103 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800104 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700105
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700106 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
107 private static final String ATTR_TYPE_STRING = "s";
108 private static final String ATTR_TYPE_BOOLEAN = "b";
109
Amith Yamasani0b285492011-04-14 17:35:23 -0700110 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700112 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800114 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700115 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116
Amith Yamasani634cf312012-10-04 17:34:21 -0700117 private static final int MIN_USER_ID = 10;
118
Amith Yamasani5e486f52013-08-07 11:06:44 -0700119 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700120
Amith Yamasani920ace02012-09-20 22:15:37 -0700121 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
122
Amith Yamasani655d0e22013-06-12 14:19:10 -0700123 // Number of attempts before jumping to the next BACKOFF_TIMES slot
124 private static final int BACKOFF_INC_INTERVAL = 5;
125
126 // Amount of time to force the user to wait before entering the PIN again, after failing
127 // BACKOFF_INC_INTERVAL times.
128 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
129
Dianne Hackborn4428e172012-08-24 17:43:05 -0700130 private final Context mContext;
131 private final PackageManagerService mPm;
132 private final Object mInstallLock;
133 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800135 private final Handler mHandler;
136
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private final File mUsersDir;
138 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700139 private final File mBaseUserPath;
140
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800141 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800142 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143
Amith Yamasani655d0e22013-06-12 14:19:10 -0700144 class RestrictionsPinState {
145 long salt;
146 String pinHash;
147 int failedAttempts;
148 long lastAttemptTime;
149 }
150
151 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
152 new SparseArray<RestrictionsPinState>();
153
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800154 /**
155 * Set of user IDs being actively removed. Removed IDs linger in this set
156 * for several seconds to work around a VFS caching issue.
157 */
158 // @GuardedBy("mPackagesLock")
159 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700160
Amith Yamasani0b285492011-04-14 17:35:23 -0700161 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700162 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700163 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700164 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700165
Amith Yamasani258848d2012-08-10 17:06:33 -0700166 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700167
Dianne Hackborn4428e172012-08-24 17:43:05 -0700168 public static UserManagerService getInstance() {
169 synchronized (UserManagerService.class) {
170 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173
174 /**
175 * Available for testing purposes.
176 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700177 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179 }
180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 /**
182 * Called by package manager to create the service. This is closely
183 * associated with the package manager, and the given lock is the
184 * package manager's own lock.
185 */
186 UserManagerService(Context context, PackageManagerService pm,
187 Object installLock, Object packagesLock) {
188 this(context, pm, installLock, packagesLock,
189 Environment.getDataDirectory(),
190 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191 }
192
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193 /**
194 * Available for testing purposes.
195 */
196 private UserManagerService(Context context, PackageManagerService pm,
197 Object installLock, Object packagesLock,
198 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700199 mContext = context;
200 mPm = pm;
201 mInstallLock = installLock;
202 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800203 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700204 synchronized (mInstallLock) {
205 synchronized (mPackagesLock) {
206 mUsersDir = new File(dataDir, USER_INFO_DIR);
207 mUsersDir.mkdirs();
208 // Make zeroth user directory, for services to migrate their files to that location
209 File userZeroDir = new File(mUsersDir, "0");
210 userZeroDir.mkdirs();
211 mBaseUserPath = baseUserPath;
212 FileUtils.setPermissions(mUsersDir.toString(),
213 FileUtils.S_IRWXU|FileUtils.S_IRWXG
214 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
215 -1, -1);
216 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
217 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700218 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
220 for (int i = 0; i < mUsers.size(); i++) {
221 UserInfo ui = mUsers.valueAt(i);
222 if (ui.partial && i != 0) {
223 partials.add(ui);
224 }
225 }
226 for (int i = 0; i < partials.size(); i++) {
227 UserInfo ui = partials.get(i);
228 Slog.w(LOG_TAG, "Removing partially created user #" + i
229 + " (name=" + ui.name + ")");
230 removeUserStateLocked(ui.id);
231 }
232 sInstance = this;
233 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700235 }
236
237 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700238 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700239 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700240 }
241
242 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700243 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700244 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700245 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700246 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
247 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700248 UserInfo ui = mUsers.valueAt(i);
249 if (ui.partial) {
250 continue;
251 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800252 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700253 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700254 }
Amith Yamasani13593602012-03-22 16:16:17 -0700255 }
256 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700257 }
Amith Yamasani13593602012-03-22 16:16:17 -0700258 }
259
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 @Override
Kenny Guy2a764942014-04-02 13:29:20 +0100261 public List<UserInfo> getProfiles(int userId) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800262 if (userId != UserHandle.getCallingUserId()) {
263 checkManageUsersPermission("getting profiles related to user " + userId);
264 }
Kenny Guya52dc3e2014-02-11 15:33:14 +0000265 synchronized (mPackagesLock) {
266 UserInfo user = getUserInfoLocked(userId);
267 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
268 for (int i = 0; i < mUsers.size(); i++) {
Kenny Guy2a764942014-04-02 13:29:20 +0100269 UserInfo profile = mUsers.valueAt(i);
270 if (!isProfileOf(user, profile)) {
Kenny Guya52dc3e2014-02-11 15:33:14 +0000271 continue;
272 }
Kenny Guy2a764942014-04-02 13:29:20 +0100273 users.add(profile);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000274 }
275 return users;
276 }
277 }
278
Kenny Guy2a764942014-04-02 13:29:20 +0100279 private boolean isProfileOf(UserInfo user, UserInfo profile) {
280 return user.id == profile.id ||
281 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
282 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000283 }
284
285 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700286 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700287 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700288 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700289 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700290 }
291 }
292
Amith Yamasani71e6c692013-03-24 17:39:28 -0700293 @Override
294 public boolean isRestricted() {
295 synchronized (mPackagesLock) {
296 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
297 }
298 }
299
Amith Yamasani195263742012-08-21 15:40:12 -0700300 /*
301 * Should be locked on mUsers before calling this.
302 */
303 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700304 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700305 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800306 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700307 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
308 return null;
309 }
310 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700311 }
312
Amith Yamasani13593602012-03-22 16:16:17 -0700313 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700314 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700315 return ArrayUtils.contains(mUserIds, userId);
316 }
317 }
318
Amith Yamasani258848d2012-08-10 17:06:33 -0700319 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700320 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700321 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700322 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700323 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700324 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700325 if (info == null || info.partial) {
326 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
327 return;
328 }
Amith Yamasani13593602012-03-22 16:16:17 -0700329 if (name != null && !name.equals(info.name)) {
330 info.name = name;
331 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700332 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700333 }
334 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700335 if (changed) {
336 sendUserInfoChangedBroadcast(userId);
337 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700338 }
339
Amith Yamasani258848d2012-08-10 17:06:33 -0700340 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700341 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700342 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700343 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700344 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700345 if (info == null || info.partial) {
346 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
347 return;
348 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700349 writeBitmapLocked(info, bitmap);
350 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700351 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700352 sendUserInfoChangedBroadcast(userId);
353 }
354
355 private void sendUserInfoChangedBroadcast(int userId) {
356 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
357 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
358 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700359 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700360 }
361
Amith Yamasani258848d2012-08-10 17:06:33 -0700362 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700363 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700364 checkManageUsersPermission("read users");
365 synchronized (mPackagesLock) {
366 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700367 if (info == null || info.partial) {
368 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
369 return null;
370 }
371 if (info.iconPath == null) {
372 return null;
373 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700374 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700375 }
376 }
377
378 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700379 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700380 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700381 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700382 if (mGuestEnabled != enable) {
383 mGuestEnabled = enable;
384 // Erase any guest user that currently exists
385 for (int i = 0; i < mUsers.size(); i++) {
386 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700387 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700388 if (!enable) {
389 removeUser(user.id);
390 }
391 return;
392 }
393 }
394 // No guest was found
395 if (enable) {
396 createUser("Guest", UserInfo.FLAG_GUEST);
397 }
398 }
399 }
400 }
401
402 @Override
403 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700404 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700405 return mGuestEnabled;
406 }
407 }
408
409 @Override
410 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700411 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700412 // TODO:
413 }
414
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700415 public void makeInitialized(int userId) {
416 checkManageUsersPermission("makeInitialized");
417 synchronized (mPackagesLock) {
418 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700419 if (info == null || info.partial) {
420 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
421 }
422 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700423 info.flags |= UserInfo.FLAG_INITIALIZED;
424 writeUserLocked(info);
425 }
426 }
427 }
428
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800429 @Override
430 public Bundle getUserRestrictions(int userId) {
431 // checkManageUsersPermission("getUserRestrictions");
432
433 synchronized (mPackagesLock) {
434 Bundle restrictions = mUserRestrictions.get(userId);
435 return restrictions != null ? restrictions : Bundle.EMPTY;
436 }
437 }
438
439 @Override
440 public void setUserRestrictions(Bundle restrictions, int userId) {
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400441 checkProfileOwnerOrManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700442 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800443
444 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700445 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800446 mUserRestrictions.get(userId).putAll(restrictions);
447 writeUserLocked(mUsers.get(userId));
448 }
449 }
450
Amith Yamasani258848d2012-08-10 17:06:33 -0700451 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700452 * Check if we've hit the limit of how many users can be created.
453 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700454 private boolean isUserLimitReachedLocked() {
455 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700456 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700457 }
458
459 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700460 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700461 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700462 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700463 *
464 * @param message used as message if SecurityException is thrown
465 * @throws SecurityException if the caller is not system or root
466 */
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400467 private final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700468 final int uid = Binder.getCallingUid();
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400469
470 if (missingManageUsersPermission(uid)) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700471 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700472 }
473 }
474
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400475 /**
476 * Enforces that only the system UID, root's UID, apps that have the
477 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
478 * permission, the profile owner, or the device owner can make certain calls to the
479 * UserManager.
480 *
481 * @param message used as message if SecurityException is thrown
482 * @throws SecurityException if the caller is not system, root, or device
483 * owner
484 */
485 private final void checkProfileOwnerOrManageUsersPermission(String message) {
486 final int uid = Binder.getCallingUid();
487 boolean isProfileOwner = false;
488 if (mContext != null && mContext.getPackageManager() != null) {
489 String[] pkgs = mContext.getPackageManager().getPackagesForUid(uid);
490 DevicePolicyManager dpm =
491 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
492 if (dpm != null) {
493 for (String pkg : pkgs) {
494 if (dpm.isDeviceOwnerApp(pkg) || dpm.isProfileOwnerApp(pkg)) {
495 isProfileOwner = true;
496 }
497 }
498 }
499 }
500
501 if (missingManageUsersPermission(uid) && !isProfileOwner) {
502 throw new SecurityException(
503 "You need MANAGE_USERS permission or device owner privileges to: " + message);
504 }
505 }
506
507 private boolean missingManageUsersPermission(int uid) {
508 return uid != Process.SYSTEM_UID && uid != 0
509 && ActivityManager.checkComponentPermission(
510 android.Manifest.permission.MANAGE_USERS,
511 uid, -1, true) != PackageManager.PERMISSION_GRANTED;
512 }
513
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700514 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700515 try {
516 File dir = new File(mUsersDir, Integer.toString(info.id));
517 File file = new File(dir, USER_PHOTO_FILENAME);
518 if (!dir.exists()) {
519 dir.mkdir();
520 FileUtils.setPermissions(
521 dir.getPath(),
522 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
523 -1, -1);
524 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700525 FileOutputStream os;
526 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700527 info.iconPath = file.getAbsolutePath();
528 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700529 try {
530 os.close();
531 } catch (IOException ioe) {
532 // What the ... !
533 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700534 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700535 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700536 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700537 }
538
Amith Yamasani0b285492011-04-14 17:35:23 -0700539 /**
540 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
541 * cache it elsewhere.
542 * @return the array of user ids.
543 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700544 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700545 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700546 return mUserIds;
547 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700548 }
549
Dianne Hackborn4428e172012-08-24 17:43:05 -0700550 int[] getUserIdsLPr() {
551 return mUserIds;
552 }
553
Amith Yamasani13593602012-03-22 16:16:17 -0700554 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700555 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700556 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700557 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700558 return;
559 }
560 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700561 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700562 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700563 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700564 XmlPullParser parser = Xml.newPullParser();
565 parser.setInput(fis, null);
566 int type;
567 while ((type = parser.next()) != XmlPullParser.START_TAG
568 && type != XmlPullParser.END_DOCUMENT) {
569 ;
570 }
571
572 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700573 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700574 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700575 return;
576 }
577
Amith Yamasani2a003292012-08-14 18:25:45 -0700578 mNextSerialNumber = -1;
579 if (parser.getName().equals(TAG_USERS)) {
580 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
581 if (lastSerialNumber != null) {
582 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
583 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700584 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
585 if (versionNumber != null) {
586 mUserVersion = Integer.parseInt(versionNumber);
587 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700588 }
589
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700590 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
591 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
592 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800593 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700594
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700595 if (user != null) {
596 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700597 if (user.isGuest()) {
598 mGuestEnabled = true;
599 }
600 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
601 mNextSerialNumber = user.id + 1;
602 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700603 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700604 }
605 }
Amith Yamasani13593602012-03-22 16:16:17 -0700606 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700607 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700608 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700609 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700610 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700611 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800612 } finally {
613 if (fis != null) {
614 try {
615 fis.close();
616 } catch (IOException e) {
617 }
618 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700619 }
620 }
621
Amith Yamasani6f34b412012-10-22 18:19:27 -0700622 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800623 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700624 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700625 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700626 int userVersion = mUserVersion;
627 if (userVersion < 1) {
628 // Assign a proper name for the owner, if not initialized correctly before
629 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
630 if ("Primary".equals(user.name)) {
631 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
632 writeUserLocked(user);
633 }
634 userVersion = 1;
635 }
636
Amith Yamasanibc9625052012-11-15 14:39:18 -0800637 if (userVersion < 2) {
638 // Owner should be marked as initialized
639 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
640 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
641 user.flags |= UserInfo.FLAG_INITIALIZED;
642 writeUserLocked(user);
643 }
644 userVersion = 2;
645 }
646
Amith Yamasani350962c2013-08-06 11:18:53 -0700647
Amith Yamasani5e486f52013-08-07 11:06:44 -0700648 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700649 userVersion = 4;
650 }
651
Amith Yamasani6f34b412012-10-22 18:19:27 -0700652 if (userVersion < USER_VERSION) {
653 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
654 + USER_VERSION);
655 } else {
656 mUserVersion = userVersion;
657 writeUserListLocked();
658 }
659 }
660
Amith Yamasani13593602012-03-22 16:16:17 -0700661 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700662 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800663 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700664 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700665 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700666 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700667 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400668 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800669
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500670 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800671 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
672
Amith Yamasani13593602012-03-22 16:16:17 -0700673 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700674
Amith Yamasani13593602012-03-22 16:16:17 -0700675 writeUserListLocked();
676 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700677 }
678
679 /*
680 * Writes the user file in this format:
681 *
682 * <user flags="20039023" id="0">
683 * <name>Primary</name>
684 * </user>
685 */
Amith Yamasani13593602012-03-22 16:16:17 -0700686 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700687 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700688 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700689 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700690 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700691 final BufferedOutputStream bos = new BufferedOutputStream(fos);
692
693 // XmlSerializer serializer = XmlUtils.serializerInstance();
694 final XmlSerializer serializer = new FastXmlSerializer();
695 serializer.setOutput(bos, "utf-8");
696 serializer.startDocument(null, true);
697 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
698
699 serializer.startTag(null, TAG_USER);
700 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700701 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700702 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700703 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
704 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
705 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700706 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
707 if (pinState != null) {
708 if (pinState.salt != 0) {
709 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
710 }
711 if (pinState.pinHash != null) {
712 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
713 }
714 if (pinState.failedAttempts != 0) {
715 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
716 Integer.toString(pinState.failedAttempts));
717 serializer.attribute(null, ATTR_LAST_RETRY_MS,
718 Long.toString(pinState.lastAttemptTime));
719 }
720 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700721 if (userInfo.iconPath != null) {
722 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
723 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700724 if (userInfo.partial) {
725 serializer.attribute(null, ATTR_PARTIAL, "true");
726 }
Kenny Guy2a764942014-04-02 13:29:20 +0100727 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
728 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
729 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000730 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700731
732 serializer.startTag(null, TAG_NAME);
733 serializer.text(userInfo.name);
734 serializer.endTag(null, TAG_NAME);
735
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800736 Bundle restrictions = mUserRestrictions.get(userInfo.id);
737 if (restrictions != null) {
738 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700739 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
740 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
741 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
742 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
743 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400744 writeBoolean(serializer, restrictions,
745 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
746 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
747 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400748 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
749 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800750 serializer.endTag(null, TAG_RESTRICTIONS);
751 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700752 serializer.endTag(null, TAG_USER);
753
754 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700755 userFile.finishWrite(fos);
756 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700757 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700758 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700759 }
760 }
761
762 /*
763 * Writes the user list file in this format:
764 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700765 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700766 * <user id="0"></user>
767 * <user id="2"></user>
768 * </users>
769 */
Amith Yamasani13593602012-03-22 16:16:17 -0700770 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700771 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700772 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700773 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700774 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700775 final BufferedOutputStream bos = new BufferedOutputStream(fos);
776
777 // XmlSerializer serializer = XmlUtils.serializerInstance();
778 final XmlSerializer serializer = new FastXmlSerializer();
779 serializer.setOutput(bos, "utf-8");
780 serializer.startDocument(null, true);
781 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
782
783 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700784 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700785 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700786
787 for (int i = 0; i < mUsers.size(); i++) {
788 UserInfo user = mUsers.valueAt(i);
789 serializer.startTag(null, TAG_USER);
790 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
791 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700792 }
793
794 serializer.endTag(null, TAG_USERS);
795
796 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700797 userListFile.finishWrite(fos);
798 } catch (Exception e) {
799 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700800 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700801 }
802 }
803
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800804 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700805 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700806 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700807 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700808 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700809 long creationTime = 0L;
810 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700811 long salt = 0L;
812 String pinHash = null;
813 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100814 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700815 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700816 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800817 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700818
819 FileInputStream fis = null;
820 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700821 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700822 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700823 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700824 XmlPullParser parser = Xml.newPullParser();
825 parser.setInput(fis, null);
826 int type;
827 while ((type = parser.next()) != XmlPullParser.START_TAG
828 && type != XmlPullParser.END_DOCUMENT) {
829 ;
830 }
831
832 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700833 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700834 return null;
835 }
836
837 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700838 int storedId = readIntAttribute(parser, ATTR_ID, -1);
839 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700840 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700841 return null;
842 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700843 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
844 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700845 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700846 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
847 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700848 salt = readLongAttribute(parser, ATTR_SALT, 0L);
849 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
850 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
851 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100852 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
853 UserInfo.NO_PROFILE_GROUP_ID);
854 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
855 // This attribute was added and renamed during development of L.
856 // TODO Remove upgrade path by 1st May 2014
857 profileGroupId = readIntAttribute(parser, "relatedGroupId",
858 UserInfo.NO_PROFILE_GROUP_ID);
859 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700860 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
861 if ("true".equals(valueString)) {
862 partial = true;
863 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700864
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800865 int outerDepth = parser.getDepth();
866 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
867 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
868 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
869 continue;
870 }
871 String tag = parser.getName();
872 if (TAG_NAME.equals(tag)) {
873 type = parser.next();
874 if (type == XmlPullParser.TEXT) {
875 name = parser.getText();
876 }
877 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700878 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
879 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
880 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
881 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
882 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400883 readBoolean(parser, restrictions,
884 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
885 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
886 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400887 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
888 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700889 }
890 }
891 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700892
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700893 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700894 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700895 userInfo.creationTime = creationTime;
896 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700897 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100898 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800899 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700900 if (salt != 0L) {
901 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
902 if (pinState == null) {
903 pinState = new RestrictionsPinState();
904 mRestrictionsPinStates.put(id, pinState);
905 }
906 pinState.salt = salt;
907 pinState.pinHash = pinHash;
908 pinState.failedAttempts = failedAttempts;
909 pinState.lastAttemptTime = lastAttemptTime;
910 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700911 return userInfo;
912
913 } catch (IOException ioe) {
914 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800915 } finally {
916 if (fis != null) {
917 try {
918 fis.close();
919 } catch (IOException e) {
920 }
921 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700922 }
923 return null;
924 }
925
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800926 private void readBoolean(XmlPullParser parser, Bundle restrictions,
927 String restrictionKey) {
928 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700929 if (value != null) {
930 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
931 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800932 }
933
934 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
935 throws IOException {
936 if (restrictions.containsKey(restrictionKey)) {
937 xml.attribute(null, restrictionKey,
938 Boolean.toString(restrictions.getBoolean(restrictionKey)));
939 }
940 }
941
Amith Yamasani920ace02012-09-20 22:15:37 -0700942 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
943 String valueString = parser.getAttributeValue(null, attr);
944 if (valueString == null) return defaultValue;
945 try {
946 return Integer.parseInt(valueString);
947 } catch (NumberFormatException nfe) {
948 return defaultValue;
949 }
950 }
951
952 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
953 String valueString = parser.getAttributeValue(null, attr);
954 if (valueString == null) return defaultValue;
955 try {
956 return Long.parseLong(valueString);
957 } catch (NumberFormatException nfe) {
958 return defaultValue;
959 }
960 }
961
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700962 private boolean isPackageInstalled(String pkg, int userId) {
963 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
964 PackageManager.GET_UNINSTALLED_PACKAGES,
965 userId);
966 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
967 return false;
968 }
969 return true;
970 }
971
Amith Yamasanib82add22013-07-09 11:24:44 -0700972 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700973 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
974 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -0700975 * Does not do any permissions checking.
976 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700977 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -0700978 synchronized (mPackagesLock) {
979 File dir = Environment.getUserSystemDirectory(userId);
980 String[] files = dir.list();
981 if (files == null) return;
982 for (String fileName : files) {
983 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
984 File resFile = new File(dir, fileName);
985 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700986 if (all) {
987 resFile.delete();
988 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -0700989 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700990 if (!isPackageInstalled(pkg, userId)) {
991 resFile.delete();
992 }
993 }
Amith Yamasanib82add22013-07-09 11:24:44 -0700994 }
995 }
996 }
997 }
998 }
999
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001000 /**
1001 * Removes the app restrictions file for a specific package and user id, if it exists.
1002 */
1003 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1004 synchronized (mPackagesLock) {
1005 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001006 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001007 if (resFile.exists()) {
1008 resFile.delete();
1009 }
1010 }
1011 }
1012
Kenny Guy2a764942014-04-02 13:29:20 +01001013 private int getNextProfileGroupIdLocked() {
1014 int maxGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001015 for (int i = 0; i < mUsers.size(); i++) {
1016 UserInfo ui = mUsers.valueAt(i);
Kenny Guy2a764942014-04-02 13:29:20 +01001017 if (maxGroupId < ui.profileGroupId) {
1018 maxGroupId = ui.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001019 }
1020 }
1021 return maxGroupId + 1;
1022 }
1023
1024 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001025 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001026 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001027 if (userId != UserHandle.USER_OWNER) {
1028 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001029 return null;
1030 }
Kenny Guy2a764942014-04-02 13:29:20 +01001031 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001032 }
1033
Amith Yamasani258848d2012-08-10 17:06:33 -07001034 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001035 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001036 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001037 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001038 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001039
Kenny Guy2a764942014-04-02 13:29:20 +01001040 private UserInfo createUserInternal(String name, int flags, int profileId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001041 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001042 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001043 try {
1044 synchronized (mInstallLock) {
1045 synchronized (mPackagesLock) {
Kenny Guy2a764942014-04-02 13:29:20 +01001046 UserInfo profile = null;
1047 if (profileId != UserHandle.USER_NULL) {
1048 profile = getUserInfoLocked(profileId);
1049 if (profile == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001050 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001051 if (isUserLimitReachedLocked()) return null;
1052 int userId = getNextAvailableIdLocked();
1053 userInfo = new UserInfo(userId, name, null, flags);
1054 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1055 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001056 long now = System.currentTimeMillis();
1057 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001058 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001059 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001060 mUsers.put(userId, userInfo);
1061 writeUserListLocked();
Kenny Guy2a764942014-04-02 13:29:20 +01001062 if (profile != null) {
1063 if (profile.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1064 profile.profileGroupId = getNextProfileGroupIdLocked();
1065 writeUserLocked(profile);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001066 }
Kenny Guy2a764942014-04-02 13:29:20 +01001067 userInfo.profileGroupId = profile.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001068 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001069 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001070 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001071 userInfo.partial = false;
1072 writeUserLocked(userInfo);
1073 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001074 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001075 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001076 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001077 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001078 if (userInfo != null) {
1079 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1080 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1081 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1082 android.Manifest.permission.MANAGE_USERS);
1083 }
1084 } finally {
1085 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001086 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001087 return userInfo;
1088 }
1089
Amith Yamasani0b285492011-04-14 17:35:23 -07001090 /**
1091 * Removes a user and all data directories created for that user. This method should be called
1092 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001093 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001094 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001095 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001096 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001097 final UserInfo user;
1098 synchronized (mPackagesLock) {
1099 user = mUsers.get(userHandle);
1100 if (userHandle == 0 || user == null) {
1101 return false;
1102 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001103 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -07001104 // Set this to a partially created user, so that the user will be purged
1105 // on next startup, in case the runtime stops now before stopping and
1106 // removing the user completely.
1107 user.partial = true;
1108 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001109 }
Amith Yamasani16389312012-10-17 21:20:14 -07001110 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001111 int res;
1112 try {
1113 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1114 new IStopUserCallback.Stub() {
1115 @Override
1116 public void userStopped(int userId) {
1117 finishRemoveUser(userId);
1118 }
1119 @Override
1120 public void userStopAborted(int userId) {
1121 }
1122 });
1123 } catch (RemoteException e) {
1124 return false;
1125 }
1126
1127 return res == ActivityManager.USER_OP_SUCCESS;
1128 }
1129
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001130 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001131 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001132 // Let other services shutdown any activity and clean up their state before completely
1133 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001134 long ident = Binder.clearCallingIdentity();
1135 try {
1136 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1137 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001138 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1139 android.Manifest.permission.MANAGE_USERS,
1140
1141 new BroadcastReceiver() {
1142 @Override
1143 public void onReceive(Context context, Intent intent) {
1144 if (DBG) {
1145 Slog.i(LOG_TAG,
1146 "USER_REMOVED broadcast sent, cleaning up user data "
1147 + userHandle);
1148 }
1149 new Thread() {
1150 public void run() {
1151 synchronized (mInstallLock) {
1152 synchronized (mPackagesLock) {
1153 removeUserStateLocked(userHandle);
1154 }
1155 }
1156 }
1157 }.start();
1158 }
1159 },
1160
1161 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001162 } finally {
1163 Binder.restoreCallingIdentity(ident);
1164 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001165 }
1166
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001167 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001168 // Cleanup package manager settings
1169 mPm.cleanUpUserLILPw(userHandle);
1170
1171 // Remove this user from the list
1172 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001173
1174 // Have user ID linger for several seconds to let external storage VFS
1175 // cache entries expire. This must be greater than the 'entry_valid'
1176 // timeout used by the FUSE daemon.
1177 mHandler.postDelayed(new Runnable() {
1178 @Override
1179 public void run() {
1180 synchronized (mPackagesLock) {
1181 mRemovingUserIds.delete(userHandle);
1182 }
1183 }
1184 }, MINUTE_IN_MILLIS);
1185
Amith Yamasani655d0e22013-06-12 14:19:10 -07001186 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001187 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001188 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001189 userFile.delete();
1190 // Update the user list
1191 writeUserListLocked();
1192 updateUserIdsLocked();
1193 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1194 }
1195
Amith Yamasani61f57372012-08-31 12:12:28 -07001196 private void removeDirectoryRecursive(File parent) {
1197 if (parent.isDirectory()) {
1198 String[] files = parent.list();
1199 for (String filename : files) {
1200 File child = new File(parent, filename);
1201 removeDirectoryRecursive(child);
1202 }
1203 }
1204 parent.delete();
1205 }
1206
Amith Yamasani2a003292012-08-14 18:25:45 -07001207 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001208 public Bundle getApplicationRestrictions(String packageName) {
1209 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1210 }
1211
1212 @Override
1213 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001214 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001215 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001216 checkProfileOwnerOrManageUsersPermission(
1217 "Only system or device owner can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001218 }
1219 synchronized (mPackagesLock) {
1220 // Read the restrictions from XML
1221 return readApplicationRestrictionsLocked(packageName, userId);
1222 }
1223 }
1224
1225 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001226 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001227 int userId) {
1228 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001229 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001230 checkProfileOwnerOrManageUsersPermission(
1231 "Only system or device owner can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001232 }
1233 synchronized (mPackagesLock) {
1234 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001235 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001236 }
Robin Lee66e5d962014-04-09 16:44:21 +01001237
1238 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1239 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1240 changeIntent.setPackage(packageName);
1241 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1242 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001243 }
1244
Amith Yamasani655d0e22013-06-12 14:19:10 -07001245 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001246 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001247 checkManageUsersPermission("Only system can modify the restrictions pin");
1248 int userId = UserHandle.getCallingUserId();
1249 synchronized (mPackagesLock) {
1250 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1251 if (pinState == null) {
1252 pinState = new RestrictionsPinState();
1253 }
1254 if (newPin == null) {
1255 pinState.salt = 0;
1256 pinState.pinHash = null;
1257 } else {
1258 try {
1259 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1260 } catch (NoSuchAlgorithmException e) {
1261 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1262 }
1263 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1264 pinState.failedAttempts = 0;
1265 }
1266 mRestrictionsPinStates.put(userId, pinState);
1267 writeUserLocked(mUsers.get(userId));
1268 }
1269 return true;
1270 }
1271
1272 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001273 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001274 checkManageUsersPermission("Only system can verify the restrictions pin");
1275 int userId = UserHandle.getCallingUserId();
1276 synchronized (mPackagesLock) {
1277 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1278 // If there's no pin set, return error code
1279 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1280 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1281 } else if (pin == null) {
1282 // If just checking if user can be prompted, return remaining time
1283 int waitTime = getRemainingTimeForPinAttempt(pinState);
1284 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1285 return waitTime;
1286 } else {
1287 int waitTime = getRemainingTimeForPinAttempt(pinState);
1288 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1289 if (waitTime > 0) {
1290 return waitTime;
1291 }
1292 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1293 pinState.failedAttempts = 0;
1294 writeUserLocked(mUsers.get(userId));
1295 return UserManager.PIN_VERIFICATION_SUCCESS;
1296 } else {
1297 pinState.failedAttempts++;
1298 pinState.lastAttemptTime = System.currentTimeMillis();
1299 writeUserLocked(mUsers.get(userId));
1300 return waitTime;
1301 }
1302 }
1303 }
1304 }
1305
1306 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1307 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1308 BACKOFF_TIMES.length - 1);
1309 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1310 BACKOFF_TIMES[backoffIndex] : 0;
1311 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1312 0);
1313 }
1314
1315 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001316 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001317 int userId = UserHandle.getCallingUserId();
1318 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001319 return hasRestrictionsPinLocked(userId);
1320 }
1321 }
1322
1323 private boolean hasRestrictionsPinLocked(int userId) {
1324 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1325 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1326 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001327 }
1328 return true;
1329 }
1330
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001331 @Override
1332 public void removeRestrictions() {
Emily Bernier7a2b4d12014-04-23 12:51:35 -04001333 checkProfileOwnerOrManageUsersPermission(
1334 "Only system or device owner can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001335 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001336 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001337 }
1338
Amith Yamasani5e486f52013-08-07 11:06:44 -07001339 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001340 synchronized (mPackagesLock) {
1341 // Remove all user restrictions
1342 setUserRestrictions(new Bundle(), userHandle);
1343 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001344 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001345 // Remove any app restrictions
1346 cleanAppRestrictions(userHandle, true);
1347 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001348 if (unblockApps) {
1349 unblockAllAppsForUser(userHandle);
1350 }
1351 }
1352
1353 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001354 mHandler.post(new Runnable() {
1355 @Override
1356 public void run() {
1357 List<ApplicationInfo> apps =
1358 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1359 userHandle).getList();
1360 final long ident = Binder.clearCallingIdentity();
1361 try {
1362 for (ApplicationInfo appInfo : apps) {
1363 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1364 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1365 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1366 userHandle);
1367 }
1368 }
1369 } finally {
1370 Binder.restoreCallingIdentity(ident);
1371 }
1372 }
1373 });
1374 }
1375
Amith Yamasani655d0e22013-06-12 14:19:10 -07001376 /*
1377 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1378 * Not the most secure, but it is at least a second level of protection. First level is that
1379 * the file is in a location only readable by the system process.
1380 * @param password the password.
1381 * @param salt the randomly generated salt
1382 * @return the hash of the pattern in a String.
1383 */
1384 private String passwordToHash(String password, long salt) {
1385 if (password == null) {
1386 return null;
1387 }
1388 String algo = null;
1389 String hashed = salt + password;
1390 try {
1391 byte[] saltedPassword = (password + salt).getBytes();
1392 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1393 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1394 hashed = toHex(sha1) + toHex(md5);
1395 } catch (NoSuchAlgorithmException e) {
1396 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1397 }
1398 return hashed;
1399 }
1400
1401 private static String toHex(byte[] ary) {
1402 final String hex = "0123456789ABCDEF";
1403 String ret = "";
1404 for (int i = 0; i < ary.length; i++) {
1405 ret += hex.charAt((ary[i] >> 4) & 0xf);
1406 ret += hex.charAt(ary[i] & 0xf);
1407 }
1408 return ret;
1409 }
1410
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001411 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001412 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001413 try {
1414 return mContext.getPackageManager().getApplicationInfo(packageName,
1415 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1416 } catch (NameNotFoundException nnfe) {
1417 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001418 } finally {
1419 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001420 }
1421 }
1422
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001423 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001424 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001425 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001426 final ArrayList<String> values = new ArrayList<String>();
1427
1428 FileInputStream fis = null;
1429 try {
1430 AtomicFile restrictionsFile =
1431 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001432 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001433 fis = restrictionsFile.openRead();
1434 XmlPullParser parser = Xml.newPullParser();
1435 parser.setInput(fis, null);
1436 int type;
1437 while ((type = parser.next()) != XmlPullParser.START_TAG
1438 && type != XmlPullParser.END_DOCUMENT) {
1439 ;
1440 }
1441
1442 if (type != XmlPullParser.START_TAG) {
1443 Slog.e(LOG_TAG, "Unable to read restrictions file "
1444 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001445 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001446 }
1447
1448 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1449 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1450 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001451 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001452 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1453 if (multiple != null) {
1454 int count = Integer.parseInt(multiple);
1455 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1456 if (type == XmlPullParser.START_TAG
1457 && parser.getName().equals(TAG_VALUE)) {
1458 values.add(parser.nextText().trim());
1459 count--;
1460 }
1461 }
1462 String [] valueStrings = new String[values.size()];
1463 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001464 restrictions.putStringArray(key, valueStrings);
1465 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1466 restrictions.putBoolean(key, Boolean.parseBoolean(
1467 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001468 } else {
1469 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001470 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001471 }
1472 }
1473 }
1474
1475 } catch (IOException ioe) {
1476 } catch (XmlPullParserException pe) {
1477 } finally {
1478 if (fis != null) {
1479 try {
1480 fis.close();
1481 } catch (IOException e) {
1482 }
1483 }
1484 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001485 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001486 }
1487
1488 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001489 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001490 FileOutputStream fos = null;
1491 AtomicFile restrictionsFile = new AtomicFile(
1492 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001493 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001494 try {
1495 fos = restrictionsFile.startWrite();
1496 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1497
1498 // XmlSerializer serializer = XmlUtils.serializerInstance();
1499 final XmlSerializer serializer = new FastXmlSerializer();
1500 serializer.setOutput(bos, "utf-8");
1501 serializer.startDocument(null, true);
1502 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1503
1504 serializer.startTag(null, TAG_RESTRICTIONS);
1505
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001506 for (String key : restrictions.keySet()) {
1507 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001508 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001509 serializer.attribute(null, ATTR_KEY, key);
1510
1511 if (value instanceof Boolean) {
1512 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1513 serializer.text(value.toString());
1514 } else if (value == null || value instanceof String) {
1515 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1516 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001517 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001518 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1519 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001520 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001521 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001522 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001523 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001524 serializer.endTag(null, TAG_VALUE);
1525 }
1526 }
1527 serializer.endTag(null, TAG_ENTRY);
1528 }
1529
1530 serializer.endTag(null, TAG_RESTRICTIONS);
1531
1532 serializer.endDocument();
1533 restrictionsFile.finishWrite(fos);
1534 } catch (Exception e) {
1535 restrictionsFile.failWrite(fos);
1536 Slog.e(LOG_TAG, "Error writing application restrictions list");
1537 }
1538 }
1539
1540 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001541 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001542 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001543 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001544 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001545 }
1546 }
1547
1548 @Override
1549 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001550 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001551 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001552 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001553 }
1554 // Not found
1555 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001556 }
1557 }
1558
Amith Yamasani0b285492011-04-14 17:35:23 -07001559 /**
1560 * Caches the list of user ids in an array, adjusting the array size when necessary.
1561 */
Amith Yamasani13593602012-03-22 16:16:17 -07001562 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001563 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001564 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001565 if (!mUsers.valueAt(i).partial) {
1566 num++;
1567 }
1568 }
Amith Yamasani16389312012-10-17 21:20:14 -07001569 final int[] newUsers = new int[num];
1570 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001571 for (int i = 0; i < mUsers.size(); i++) {
1572 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001573 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001574 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001575 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001576 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001577 }
1578
1579 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001580 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001581 * @param userId the user that was just foregrounded
1582 */
1583 public void userForeground(int userId) {
1584 synchronized (mPackagesLock) {
1585 UserInfo user = mUsers.get(userId);
1586 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001587 if (user == null || user.partial) {
1588 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1589 return;
1590 }
1591 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001592 user.lastLoggedInTime = now;
1593 writeUserLocked(user);
1594 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001595 // If this is not a restricted profile and there is no restrictions pin, clean up
1596 // all restrictions files that might have been left behind, else clean up just the
1597 // ones with uninstalled packages
1598 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1599 final long salt = pinState == null ? 0 : pinState.salt;
1600 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001601 }
1602 }
1603
1604 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001605 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001606 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1607 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001608 * @return
1609 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001610 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001611 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001612 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001613 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001614 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001615 break;
1616 }
1617 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001618 }
Amith Yamasani195263742012-08-21 15:40:12 -07001619 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001620 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001621 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001622
Amith Yamasanifc95e702013-09-26 13:20:17 -07001623 private String packageToRestrictionsFileName(String packageName) {
1624 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1625 }
1626
1627 private String restrictionsFileNameToPackage(String fileName) {
1628 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1629 (int) (fileName.length() - XML_SUFFIX.length()));
1630 }
1631
Amith Yamasani920ace02012-09-20 22:15:37 -07001632 @Override
1633 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1634 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1635 != PackageManager.PERMISSION_GRANTED) {
1636 pw.println("Permission Denial: can't dump UserManager from from pid="
1637 + Binder.getCallingPid()
1638 + ", uid=" + Binder.getCallingUid()
1639 + " without permission "
1640 + android.Manifest.permission.DUMP);
1641 return;
1642 }
1643
1644 long now = System.currentTimeMillis();
1645 StringBuilder sb = new StringBuilder();
1646 synchronized (mPackagesLock) {
1647 pw.println("Users:");
1648 for (int i = 0; i < mUsers.size(); i++) {
1649 UserInfo user = mUsers.valueAt(i);
1650 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001651 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001652 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001653 if (user.partial) pw.print(" <partial>");
1654 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001655 pw.print(" Created: ");
1656 if (user.creationTime == 0) {
1657 pw.println("<unknown>");
1658 } else {
1659 sb.setLength(0);
1660 TimeUtils.formatDuration(now - user.creationTime, sb);
1661 sb.append(" ago");
1662 pw.println(sb);
1663 }
1664 pw.print(" Last logged in: ");
1665 if (user.lastLoggedInTime == 0) {
1666 pw.println("<unknown>");
1667 } else {
1668 sb.setLength(0);
1669 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1670 sb.append(" ago");
1671 pw.println(sb);
1672 }
1673 }
1674 }
1675 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001676
1677 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1678 @Override
1679 public void onPackageRemoved(String pkg, int uid) {
1680 final int userId = this.getChangingUserId();
1681 // Package could be disappearing because it is being blocked, so also check if
1682 // it has been uninstalled.
1683 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1684 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1685 cleanAppRestrictionsForPackage(pkg, userId);
1686 }
1687 }
1688 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001689}