blob: 60c6313c17e48dd729aabc882ca3435e3be6c335 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080019import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070020
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070024import android.app.ActivityThread;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070045import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070046import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Slog;
48import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070050import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.util.Xml;
52
Amith Yamasani1a7472e2013-07-02 11:17:30 -070053import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080054import com.android.internal.util.ArrayUtils;
55import com.android.internal.util.FastXmlSerializer;
56
57import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59import org.xmlpull.v1.XmlSerializer;
60
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import java.io.BufferedOutputStream;
62import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070063import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070065import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileOutputStream;
67import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070068import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070069import java.security.MessageDigest;
70import java.security.NoSuchAlgorithmException;
71import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import java.util.ArrayList;
73import java.util.List;
74
Amith Yamasani258848d2012-08-10 17:06:33 -070075public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070076
Amith Yamasani2a003292012-08-14 18:25:45 -070077 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani16389312012-10-17 21:20:14 -070079 private static final boolean DBG = false;
80
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070083 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070085 private static final String ATTR_CREATION_TIME = "created";
86 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070087 private static final String ATTR_SALT = "salt";
88 private static final String ATTR_PIN_HASH = "pinHash";
89 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
90 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070091 private static final String ATTR_SERIAL_NO = "serialNumber";
92 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070093 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070094 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010095 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080098 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080099 private static final String TAG_ENTRY = "entry";
100 private static final String TAG_VALUE = "value";
101 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700102 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800103 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700105 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
106 private static final String ATTR_TYPE_STRING = "s";
107 private static final String ATTR_TYPE_BOOLEAN = "b";
108
Amith Yamasani0b285492011-04-14 17:35:23 -0700109 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700111 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800113 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700114 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115
Amith Yamasani634cf312012-10-04 17:34:21 -0700116 private static final int MIN_USER_ID = 10;
117
Amith Yamasani5e486f52013-08-07 11:06:44 -0700118 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700119
Amith Yamasani920ace02012-09-20 22:15:37 -0700120 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
121
Amith Yamasani655d0e22013-06-12 14:19:10 -0700122 // Number of attempts before jumping to the next BACKOFF_TIMES slot
123 private static final int BACKOFF_INC_INTERVAL = 5;
124
125 // Amount of time to force the user to wait before entering the PIN again, after failing
126 // BACKOFF_INC_INTERVAL times.
127 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
128
Dianne Hackborn4428e172012-08-24 17:43:05 -0700129 private final Context mContext;
130 private final PackageManagerService mPm;
131 private final Object mInstallLock;
132 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700133
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800134 private final Handler mHandler;
135
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136 private final File mUsersDir;
137 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700138 private final File mBaseUserPath;
139
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800140 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800141 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800142
Amith Yamasani655d0e22013-06-12 14:19:10 -0700143 class RestrictionsPinState {
144 long salt;
145 String pinHash;
146 int failedAttempts;
147 long lastAttemptTime;
148 }
149
150 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
151 new SparseArray<RestrictionsPinState>();
152
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800153 /**
154 * Set of user IDs being actively removed. Removed IDs linger in this set
155 * for several seconds to work around a VFS caching issue.
156 */
157 // @GuardedBy("mPackagesLock")
158 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700159
Amith Yamasani0b285492011-04-14 17:35:23 -0700160 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700161 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700162 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700163 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700164
Amith Yamasani258848d2012-08-10 17:06:33 -0700165 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700166
Dianne Hackborn4428e172012-08-24 17:43:05 -0700167 public static UserManagerService getInstance() {
168 synchronized (UserManagerService.class) {
169 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700170 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700172
173 /**
174 * Available for testing purposes.
175 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700176 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700177 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700178 }
179
Dianne Hackborn4428e172012-08-24 17:43:05 -0700180 /**
181 * Called by package manager to create the service. This is closely
182 * associated with the package manager, and the given lock is the
183 * package manager's own lock.
184 */
185 UserManagerService(Context context, PackageManagerService pm,
186 Object installLock, Object packagesLock) {
187 this(context, pm, installLock, packagesLock,
188 Environment.getDataDirectory(),
189 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700190 }
191
Dianne Hackborn4428e172012-08-24 17:43:05 -0700192 /**
193 * Available for testing purposes.
194 */
195 private UserManagerService(Context context, PackageManagerService pm,
196 Object installLock, Object packagesLock,
197 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700198 mContext = context;
199 mPm = pm;
200 mInstallLock = installLock;
201 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800202 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700203 synchronized (mInstallLock) {
204 synchronized (mPackagesLock) {
205 mUsersDir = new File(dataDir, USER_INFO_DIR);
206 mUsersDir.mkdirs();
207 // Make zeroth user directory, for services to migrate their files to that location
208 File userZeroDir = new File(mUsersDir, "0");
209 userZeroDir.mkdirs();
210 mBaseUserPath = baseUserPath;
211 FileUtils.setPermissions(mUsersDir.toString(),
212 FileUtils.S_IRWXU|FileUtils.S_IRWXG
213 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
214 -1, -1);
215 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
216 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700217 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700218 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
219 for (int i = 0; i < mUsers.size(); i++) {
220 UserInfo ui = mUsers.valueAt(i);
221 if (ui.partial && i != 0) {
222 partials.add(ui);
223 }
224 }
225 for (int i = 0; i < partials.size(); i++) {
226 UserInfo ui = partials.get(i);
227 Slog.w(LOG_TAG, "Removing partially created user #" + i
228 + " (name=" + ui.name + ")");
229 removeUserStateLocked(ui.id);
230 }
231 sInstance = this;
232 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700233 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700234 }
235
236 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700237 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700238 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700239 }
240
241 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700242 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700243 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700244 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700245 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
246 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700247 UserInfo ui = mUsers.valueAt(i);
248 if (ui.partial) {
249 continue;
250 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800251 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700253 }
Amith Yamasani13593602012-03-22 16:16:17 -0700254 }
255 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700256 }
Amith Yamasani13593602012-03-22 16:16:17 -0700257 }
258
Amith Yamasani258848d2012-08-10 17:06:33 -0700259 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100260 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800261 if (userId != UserHandle.getCallingUserId()) {
262 checkManageUsersPermission("getting profiles related to user " + userId);
263 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700264 final long ident = Binder.clearCallingIdentity();
265 try {
266 synchronized (mPackagesLock) {
267 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100268 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700269 } finally {
270 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000271 }
272 }
273
Amith Yamasanibe465322014-04-24 13:45:17 -0700274 /** Assume permissions already checked and caller's identity cleared */
275 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700276 UserInfo user = getUserInfoLocked(userId);
277 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
278 for (int i = 0; i < mUsers.size(); i++) {
279 UserInfo profile = mUsers.valueAt(i);
280 if (!isProfileOf(user, profile)) {
281 continue;
282 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100283 if (enabledOnly && !profile.isEnabled()) {
284 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700285 }
286 users.add(profile);
287 }
288 return users;
289 }
290
Kenny Guy2a764942014-04-02 13:29:20 +0100291 private boolean isProfileOf(UserInfo user, UserInfo profile) {
292 return user.id == profile.id ||
293 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
294 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000295 }
296
297 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100298 public void setUserEnabled(int userId) {
299 checkManageUsersPermission("enable user");
300 synchronized (mPackagesLock) {
301 UserInfo info = getUserInfoLocked(userId);
302 if (info != null && !info.isEnabled()) {
303 info.flags ^= UserInfo.FLAG_DISABLED;
304 writeUserLocked(info);
305 }
306 }
307 }
308
309 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700310 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700311 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700312 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700313 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700314 }
315 }
316
Amith Yamasani71e6c692013-03-24 17:39:28 -0700317 @Override
318 public boolean isRestricted() {
319 synchronized (mPackagesLock) {
320 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
321 }
322 }
323
Amith Yamasani195263742012-08-21 15:40:12 -0700324 /*
325 * Should be locked on mUsers before calling this.
326 */
327 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700328 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700329 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800330 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700331 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
332 return null;
333 }
334 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700335 }
336
Amith Yamasani13593602012-03-22 16:16:17 -0700337 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700338 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700339 return ArrayUtils.contains(mUserIds, userId);
340 }
341 }
342
Amith Yamasani258848d2012-08-10 17:06:33 -0700343 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700344 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700345 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700346 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700347 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700348 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700349 if (info == null || info.partial) {
350 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
351 return;
352 }
Amith Yamasani13593602012-03-22 16:16:17 -0700353 if (name != null && !name.equals(info.name)) {
354 info.name = name;
355 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700356 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700357 }
358 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700359 if (changed) {
360 sendUserInfoChangedBroadcast(userId);
361 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700362 }
363
Amith Yamasani258848d2012-08-10 17:06:33 -0700364 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700365 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700366 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700367 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700368 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700369 if (info == null || info.partial) {
370 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
371 return;
372 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700373 writeBitmapLocked(info, bitmap);
374 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700375 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700376 sendUserInfoChangedBroadcast(userId);
377 }
378
379 private void sendUserInfoChangedBroadcast(int userId) {
380 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
381 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
382 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700383 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700384 }
385
Amith Yamasani258848d2012-08-10 17:06:33 -0700386 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700387 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700388 checkManageUsersPermission("read users");
389 synchronized (mPackagesLock) {
390 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700391 if (info == null || info.partial) {
392 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
393 return null;
394 }
395 if (info.iconPath == null) {
396 return null;
397 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700398 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700399 }
400 }
401
402 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700403 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700404 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700405 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700406 if (mGuestEnabled != enable) {
407 mGuestEnabled = enable;
408 // Erase any guest user that currently exists
409 for (int i = 0; i < mUsers.size(); i++) {
410 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700411 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700412 if (!enable) {
413 removeUser(user.id);
414 }
415 return;
416 }
417 }
418 // No guest was found
419 if (enable) {
420 createUser("Guest", UserInfo.FLAG_GUEST);
421 }
422 }
423 }
424 }
425
426 @Override
427 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700428 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700429 return mGuestEnabled;
430 }
431 }
432
433 @Override
434 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700435 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700436 // TODO:
437 }
438
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700439 public void makeInitialized(int userId) {
440 checkManageUsersPermission("makeInitialized");
441 synchronized (mPackagesLock) {
442 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700443 if (info == null || info.partial) {
444 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
445 }
446 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700447 info.flags |= UserInfo.FLAG_INITIALIZED;
448 writeUserLocked(info);
449 }
450 }
451 }
452
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800453 @Override
454 public Bundle getUserRestrictions(int userId) {
455 // checkManageUsersPermission("getUserRestrictions");
456
457 synchronized (mPackagesLock) {
458 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700459 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800460 }
461 }
462
463 @Override
464 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700465 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700466 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800467
468 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700469 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800470 mUserRestrictions.get(userId).putAll(restrictions);
471 writeUserLocked(mUsers.get(userId));
472 }
473 }
474
Amith Yamasani258848d2012-08-10 17:06:33 -0700475 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700476 * Check if we've hit the limit of how many users can be created.
477 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700478 private boolean isUserLimitReachedLocked() {
479 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700480 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700481 }
482
483 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700484 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700485 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700486 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700487 *
488 * @param message used as message if SecurityException is thrown
489 * @throws SecurityException if the caller is not system or root
490 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700491 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700492 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700493 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400494 && ActivityManager.checkComponentPermission(
495 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700496 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
497 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
498 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400499 }
500
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700501 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700502 try {
503 File dir = new File(mUsersDir, Integer.toString(info.id));
504 File file = new File(dir, USER_PHOTO_FILENAME);
505 if (!dir.exists()) {
506 dir.mkdir();
507 FileUtils.setPermissions(
508 dir.getPath(),
509 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
510 -1, -1);
511 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700512 FileOutputStream os;
513 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700514 info.iconPath = file.getAbsolutePath();
515 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700516 try {
517 os.close();
518 } catch (IOException ioe) {
519 // What the ... !
520 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700521 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700522 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700523 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700524 }
525
Amith Yamasani0b285492011-04-14 17:35:23 -0700526 /**
527 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
528 * cache it elsewhere.
529 * @return the array of user ids.
530 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700531 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700532 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700533 return mUserIds;
534 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700535 }
536
Dianne Hackborn4428e172012-08-24 17:43:05 -0700537 int[] getUserIdsLPr() {
538 return mUserIds;
539 }
540
Amith Yamasani13593602012-03-22 16:16:17 -0700541 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700542 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700543 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700544 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700545 return;
546 }
547 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700548 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700549 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700550 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700551 XmlPullParser parser = Xml.newPullParser();
552 parser.setInput(fis, null);
553 int type;
554 while ((type = parser.next()) != XmlPullParser.START_TAG
555 && type != XmlPullParser.END_DOCUMENT) {
556 ;
557 }
558
559 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700560 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700561 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700562 return;
563 }
564
Amith Yamasani2a003292012-08-14 18:25:45 -0700565 mNextSerialNumber = -1;
566 if (parser.getName().equals(TAG_USERS)) {
567 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
568 if (lastSerialNumber != null) {
569 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
570 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700571 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
572 if (versionNumber != null) {
573 mUserVersion = Integer.parseInt(versionNumber);
574 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700575 }
576
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700577 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
578 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
579 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800580 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700581
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700582 if (user != null) {
583 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700584 if (user.isGuest()) {
585 mGuestEnabled = true;
586 }
587 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
588 mNextSerialNumber = user.id + 1;
589 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700590 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700591 }
592 }
Amith Yamasani13593602012-03-22 16:16:17 -0700593 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700594 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700595 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700596 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700597 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700598 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800599 } finally {
600 if (fis != null) {
601 try {
602 fis.close();
603 } catch (IOException e) {
604 }
605 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700606 }
607 }
608
Amith Yamasani6f34b412012-10-22 18:19:27 -0700609 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800610 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700611 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700612 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700613 int userVersion = mUserVersion;
614 if (userVersion < 1) {
615 // Assign a proper name for the owner, if not initialized correctly before
616 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
617 if ("Primary".equals(user.name)) {
618 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
619 writeUserLocked(user);
620 }
621 userVersion = 1;
622 }
623
Amith Yamasanibc9625052012-11-15 14:39:18 -0800624 if (userVersion < 2) {
625 // Owner should be marked as initialized
626 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
627 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
628 user.flags |= UserInfo.FLAG_INITIALIZED;
629 writeUserLocked(user);
630 }
631 userVersion = 2;
632 }
633
Amith Yamasani350962c2013-08-06 11:18:53 -0700634
Amith Yamasani5e486f52013-08-07 11:06:44 -0700635 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700636 userVersion = 4;
637 }
638
Amith Yamasani6f34b412012-10-22 18:19:27 -0700639 if (userVersion < USER_VERSION) {
640 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
641 + USER_VERSION);
642 } else {
643 mUserVersion = userVersion;
644 writeUserListLocked();
645 }
646 }
647
Amith Yamasani13593602012-03-22 16:16:17 -0700648 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700649 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800650 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700651 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700652 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700653 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700654 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400655 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800656
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500657 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800658 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
659
Amith Yamasani13593602012-03-22 16:16:17 -0700660 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700661
Amith Yamasani13593602012-03-22 16:16:17 -0700662 writeUserListLocked();
663 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700664 }
665
666 /*
667 * Writes the user file in this format:
668 *
669 * <user flags="20039023" id="0">
670 * <name>Primary</name>
671 * </user>
672 */
Amith Yamasani13593602012-03-22 16:16:17 -0700673 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700674 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700675 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700676 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700677 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700678 final BufferedOutputStream bos = new BufferedOutputStream(fos);
679
680 // XmlSerializer serializer = XmlUtils.serializerInstance();
681 final XmlSerializer serializer = new FastXmlSerializer();
682 serializer.setOutput(bos, "utf-8");
683 serializer.startDocument(null, true);
684 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
685
686 serializer.startTag(null, TAG_USER);
687 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700688 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700689 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700690 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
691 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
692 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700693 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
694 if (pinState != null) {
695 if (pinState.salt != 0) {
696 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
697 }
698 if (pinState.pinHash != null) {
699 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
700 }
701 if (pinState.failedAttempts != 0) {
702 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
703 Integer.toString(pinState.failedAttempts));
704 serializer.attribute(null, ATTR_LAST_RETRY_MS,
705 Long.toString(pinState.lastAttemptTime));
706 }
707 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700708 if (userInfo.iconPath != null) {
709 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
710 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700711 if (userInfo.partial) {
712 serializer.attribute(null, ATTR_PARTIAL, "true");
713 }
Kenny Guy2a764942014-04-02 13:29:20 +0100714 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
715 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
716 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000717 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700718
719 serializer.startTag(null, TAG_NAME);
720 serializer.text(userInfo.name);
721 serializer.endTag(null, TAG_NAME);
722
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800723 Bundle restrictions = mUserRestrictions.get(userInfo.id);
724 if (restrictions != null) {
725 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700726 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
727 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
728 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
729 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
730 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400731 writeBoolean(serializer, restrictions,
732 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
733 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
734 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400735 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
736 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400737 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
738 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
739 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
740 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
741 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
742 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
743 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
744 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
745 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_APPS);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400746 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
747 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
748 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800749 serializer.endTag(null, TAG_RESTRICTIONS);
750 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700751 serializer.endTag(null, TAG_USER);
752
753 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700754 userFile.finishWrite(fos);
755 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700756 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700757 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700758 }
759 }
760
761 /*
762 * Writes the user list file in this format:
763 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700764 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700765 * <user id="0"></user>
766 * <user id="2"></user>
767 * </users>
768 */
Amith Yamasani13593602012-03-22 16:16:17 -0700769 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700770 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700771 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700773 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 final BufferedOutputStream bos = new BufferedOutputStream(fos);
775
776 // XmlSerializer serializer = XmlUtils.serializerInstance();
777 final XmlSerializer serializer = new FastXmlSerializer();
778 serializer.setOutput(bos, "utf-8");
779 serializer.startDocument(null, true);
780 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
781
782 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700783 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700784 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700785
786 for (int i = 0; i < mUsers.size(); i++) {
787 UserInfo user = mUsers.valueAt(i);
788 serializer.startTag(null, TAG_USER);
789 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
790 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700791 }
792
793 serializer.endTag(null, TAG_USERS);
794
795 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700796 userListFile.finishWrite(fos);
797 } catch (Exception e) {
798 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700799 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700800 }
801 }
802
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800803 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700804 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700805 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700806 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700807 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700808 long creationTime = 0L;
809 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700810 long salt = 0L;
811 String pinHash = null;
812 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100813 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700814 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700815 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800816 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817
818 FileInputStream fis = null;
819 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700820 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700821 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700822 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700823 XmlPullParser parser = Xml.newPullParser();
824 parser.setInput(fis, null);
825 int type;
826 while ((type = parser.next()) != XmlPullParser.START_TAG
827 && type != XmlPullParser.END_DOCUMENT) {
828 ;
829 }
830
831 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700832 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700833 return null;
834 }
835
836 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700837 int storedId = readIntAttribute(parser, ATTR_ID, -1);
838 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700839 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700840 return null;
841 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700842 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
843 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700844 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700845 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
846 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700847 salt = readLongAttribute(parser, ATTR_SALT, 0L);
848 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
849 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
850 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100851 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
852 UserInfo.NO_PROFILE_GROUP_ID);
853 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
854 // This attribute was added and renamed during development of L.
855 // TODO Remove upgrade path by 1st May 2014
856 profileGroupId = readIntAttribute(parser, "relatedGroupId",
857 UserInfo.NO_PROFILE_GROUP_ID);
858 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700859 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
860 if ("true".equals(valueString)) {
861 partial = true;
862 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700863
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800864 int outerDepth = parser.getDepth();
865 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
866 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
867 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
868 continue;
869 }
870 String tag = parser.getName();
871 if (TAG_NAME.equals(tag)) {
872 type = parser.next();
873 if (type == XmlPullParser.TEXT) {
874 name = parser.getText();
875 }
876 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700877 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
878 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
879 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
880 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
881 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400882 readBoolean(parser, restrictions,
883 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
884 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
885 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400886 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
887 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400888 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
889 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
890 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
891 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
892 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
893 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
894 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
895 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
896 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_APPS);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400897 readBoolean(parser, restrictions,
898 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
899 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
900 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700901 }
902 }
903 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700904
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700905 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700906 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700907 userInfo.creationTime = creationTime;
908 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700909 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100910 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800911 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700912 if (salt != 0L) {
913 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
914 if (pinState == null) {
915 pinState = new RestrictionsPinState();
916 mRestrictionsPinStates.put(id, pinState);
917 }
918 pinState.salt = salt;
919 pinState.pinHash = pinHash;
920 pinState.failedAttempts = failedAttempts;
921 pinState.lastAttemptTime = lastAttemptTime;
922 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700923 return userInfo;
924
925 } catch (IOException ioe) {
926 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800927 } finally {
928 if (fis != null) {
929 try {
930 fis.close();
931 } catch (IOException e) {
932 }
933 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700934 }
935 return null;
936 }
937
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800938 private void readBoolean(XmlPullParser parser, Bundle restrictions,
939 String restrictionKey) {
940 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700941 if (value != null) {
942 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
943 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800944 }
945
946 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
947 throws IOException {
948 if (restrictions.containsKey(restrictionKey)) {
949 xml.attribute(null, restrictionKey,
950 Boolean.toString(restrictions.getBoolean(restrictionKey)));
951 }
952 }
953
Amith Yamasani920ace02012-09-20 22:15:37 -0700954 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
955 String valueString = parser.getAttributeValue(null, attr);
956 if (valueString == null) return defaultValue;
957 try {
958 return Integer.parseInt(valueString);
959 } catch (NumberFormatException nfe) {
960 return defaultValue;
961 }
962 }
963
964 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
965 String valueString = parser.getAttributeValue(null, attr);
966 if (valueString == null) return defaultValue;
967 try {
968 return Long.parseLong(valueString);
969 } catch (NumberFormatException nfe) {
970 return defaultValue;
971 }
972 }
973
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700974 private boolean isPackageInstalled(String pkg, int userId) {
975 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
976 PackageManager.GET_UNINSTALLED_PACKAGES,
977 userId);
978 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
979 return false;
980 }
981 return true;
982 }
983
Amith Yamasanib82add22013-07-09 11:24:44 -0700984 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700985 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
986 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -0700987 * Does not do any permissions checking.
988 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700989 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -0700990 synchronized (mPackagesLock) {
991 File dir = Environment.getUserSystemDirectory(userId);
992 String[] files = dir.list();
993 if (files == null) return;
994 for (String fileName : files) {
995 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
996 File resFile = new File(dir, fileName);
997 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700998 if (all) {
999 resFile.delete();
1000 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -07001001 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001002 if (!isPackageInstalled(pkg, userId)) {
1003 resFile.delete();
1004 }
1005 }
Amith Yamasanib82add22013-07-09 11:24:44 -07001006 }
1007 }
1008 }
1009 }
1010 }
1011
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001012 /**
1013 * Removes the app restrictions file for a specific package and user id, if it exists.
1014 */
1015 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1016 synchronized (mPackagesLock) {
1017 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001018 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001019 if (resFile.exists()) {
1020 resFile.delete();
1021 }
1022 }
1023 }
1024
Kenny Guy2a764942014-04-02 13:29:20 +01001025 private int getNextProfileGroupIdLocked() {
1026 int maxGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001027 for (int i = 0; i < mUsers.size(); i++) {
1028 UserInfo ui = mUsers.valueAt(i);
Kenny Guy2a764942014-04-02 13:29:20 +01001029 if (maxGroupId < ui.profileGroupId) {
1030 maxGroupId = ui.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001031 }
1032 }
1033 return maxGroupId + 1;
1034 }
1035
1036 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001037 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001038 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001039 if (userId != UserHandle.USER_OWNER) {
1040 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001041 return null;
1042 }
Kenny Guy2a764942014-04-02 13:29:20 +01001043 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001044 }
1045
Amith Yamasani258848d2012-08-10 17:06:33 -07001046 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001047 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001048 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001049 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001050 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001051
Kenny Guy2a764942014-04-02 13:29:20 +01001052 private UserInfo createUserInternal(String name, int flags, int profileId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001053 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001054 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001055 try {
1056 synchronized (mInstallLock) {
1057 synchronized (mPackagesLock) {
Kenny Guy2a764942014-04-02 13:29:20 +01001058 UserInfo profile = null;
1059 if (profileId != UserHandle.USER_NULL) {
1060 profile = getUserInfoLocked(profileId);
1061 if (profile == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001062 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001063 if (isUserLimitReachedLocked()) return null;
1064 int userId = getNextAvailableIdLocked();
1065 userInfo = new UserInfo(userId, name, null, flags);
1066 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1067 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001068 long now = System.currentTimeMillis();
1069 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001070 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001071 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001072 mUsers.put(userId, userInfo);
1073 writeUserListLocked();
Kenny Guy2a764942014-04-02 13:29:20 +01001074 if (profile != null) {
1075 if (profile.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1076 profile.profileGroupId = getNextProfileGroupIdLocked();
1077 writeUserLocked(profile);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001078 }
Kenny Guy2a764942014-04-02 13:29:20 +01001079 userInfo.profileGroupId = profile.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001080 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001081 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001082 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001083 userInfo.partial = false;
1084 writeUserLocked(userInfo);
1085 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001086 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001087 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001088 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001089 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001090 if (userInfo != null) {
1091 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1092 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1093 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1094 android.Manifest.permission.MANAGE_USERS);
1095 }
1096 } finally {
1097 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001098 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001099 return userInfo;
1100 }
1101
Amith Yamasani0b285492011-04-14 17:35:23 -07001102 /**
1103 * Removes a user and all data directories created for that user. This method should be called
1104 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001105 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001106 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001107 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001108 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001109 final UserInfo user;
1110 synchronized (mPackagesLock) {
1111 user = mUsers.get(userHandle);
1112 if (userHandle == 0 || user == null) {
1113 return false;
1114 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001115 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -07001116 // Set this to a partially created user, so that the user will be purged
1117 // on next startup, in case the runtime stops now before stopping and
1118 // removing the user completely.
1119 user.partial = true;
Adam Connors7b66ed52014-04-14 11:58:10 +01001120 // Mark it as disabled, so that it isn't returned any more when
1121 // profiles are queried.
1122 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani756901d2012-10-12 12:30:07 -07001123 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001124 }
Amith Yamasani16389312012-10-17 21:20:14 -07001125 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001126 int res;
1127 try {
1128 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1129 new IStopUserCallback.Stub() {
1130 @Override
1131 public void userStopped(int userId) {
1132 finishRemoveUser(userId);
1133 }
1134 @Override
1135 public void userStopAborted(int userId) {
1136 }
1137 });
1138 } catch (RemoteException e) {
1139 return false;
1140 }
1141
1142 return res == ActivityManager.USER_OP_SUCCESS;
1143 }
1144
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001145 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001146 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001147 // Let other services shutdown any activity and clean up their state before completely
1148 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001149 long ident = Binder.clearCallingIdentity();
1150 try {
Adam Connors7b66ed52014-04-14 11:58:10 +01001151 final boolean isManaged = getUserInfo(userHandle).isManagedProfile();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001152 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1153 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001154 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1155 android.Manifest.permission.MANAGE_USERS,
1156
1157 new BroadcastReceiver() {
1158 @Override
1159 public void onReceive(Context context, Intent intent) {
1160 if (DBG) {
1161 Slog.i(LOG_TAG,
1162 "USER_REMOVED broadcast sent, cleaning up user data "
1163 + userHandle);
1164 }
1165 new Thread() {
1166 public void run() {
1167 synchronized (mInstallLock) {
1168 synchronized (mPackagesLock) {
1169 removeUserStateLocked(userHandle);
1170 }
1171 }
Adam Connors7b66ed52014-04-14 11:58:10 +01001172 // Send broadcast to notify system that the user removed was a
1173 // managed user.
1174 if (isManaged) {
1175 sendProfileRemovedBroadcast(userHandle);
1176 }
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001177 }
1178 }.start();
1179 }
1180 },
1181
1182 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001183 } finally {
1184 Binder.restoreCallingIdentity(ident);
1185 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001186 }
1187
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001188 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001189 // Cleanup package manager settings
1190 mPm.cleanUpUserLILPw(userHandle);
1191
1192 // Remove this user from the list
1193 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001194
1195 // Have user ID linger for several seconds to let external storage VFS
1196 // cache entries expire. This must be greater than the 'entry_valid'
1197 // timeout used by the FUSE daemon.
1198 mHandler.postDelayed(new Runnable() {
1199 @Override
1200 public void run() {
1201 synchronized (mPackagesLock) {
1202 mRemovingUserIds.delete(userHandle);
1203 }
1204 }
1205 }, MINUTE_IN_MILLIS);
1206
Amith Yamasani655d0e22013-06-12 14:19:10 -07001207 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001208 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001209 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001210 userFile.delete();
1211 // Update the user list
1212 writeUserListLocked();
1213 updateUserIdsLocked();
1214 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1215 }
1216
Amith Yamasani61f57372012-08-31 12:12:28 -07001217 private void removeDirectoryRecursive(File parent) {
1218 if (parent.isDirectory()) {
1219 String[] files = parent.list();
1220 for (String filename : files) {
1221 File child = new File(parent, filename);
1222 removeDirectoryRecursive(child);
1223 }
1224 }
1225 parent.delete();
1226 }
1227
Adam Connors7b66ed52014-04-14 11:58:10 +01001228 private void sendProfileRemovedBroadcast(int userHandle) {
1229 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
1230 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
1231 // Note: This makes an assumption that the parent owner is user 0.
1232 mContext.sendBroadcastAsUser(managedProfileIntent, UserHandle.OWNER, null);
1233 }
1234
Amith Yamasani2a003292012-08-14 18:25:45 -07001235 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001236 public Bundle getApplicationRestrictions(String packageName) {
1237 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1238 }
1239
1240 @Override
1241 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001242 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001243 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001244 checkManageUsersPermission("Only system 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))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001257 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001258 }
1259 synchronized (mPackagesLock) {
1260 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001261 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001262 }
Robin Lee66e5d962014-04-09 16:44:21 +01001263
1264 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1265 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1266 changeIntent.setPackage(packageName);
1267 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1268 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001269 }
1270
Amith Yamasani655d0e22013-06-12 14:19:10 -07001271 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001272 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001273 checkManageUsersPermission("Only system can modify the restrictions pin");
1274 int userId = UserHandle.getCallingUserId();
1275 synchronized (mPackagesLock) {
1276 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1277 if (pinState == null) {
1278 pinState = new RestrictionsPinState();
1279 }
1280 if (newPin == null) {
1281 pinState.salt = 0;
1282 pinState.pinHash = null;
1283 } else {
1284 try {
1285 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1286 } catch (NoSuchAlgorithmException e) {
1287 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1288 }
1289 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1290 pinState.failedAttempts = 0;
1291 }
1292 mRestrictionsPinStates.put(userId, pinState);
1293 writeUserLocked(mUsers.get(userId));
1294 }
1295 return true;
1296 }
1297
1298 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001299 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001300 checkManageUsersPermission("Only system can verify the restrictions pin");
1301 int userId = UserHandle.getCallingUserId();
1302 synchronized (mPackagesLock) {
1303 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1304 // If there's no pin set, return error code
1305 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1306 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1307 } else if (pin == null) {
1308 // If just checking if user can be prompted, return remaining time
1309 int waitTime = getRemainingTimeForPinAttempt(pinState);
1310 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1311 return waitTime;
1312 } else {
1313 int waitTime = getRemainingTimeForPinAttempt(pinState);
1314 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1315 if (waitTime > 0) {
1316 return waitTime;
1317 }
1318 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1319 pinState.failedAttempts = 0;
1320 writeUserLocked(mUsers.get(userId));
1321 return UserManager.PIN_VERIFICATION_SUCCESS;
1322 } else {
1323 pinState.failedAttempts++;
1324 pinState.lastAttemptTime = System.currentTimeMillis();
1325 writeUserLocked(mUsers.get(userId));
1326 return waitTime;
1327 }
1328 }
1329 }
1330 }
1331
1332 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1333 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1334 BACKOFF_TIMES.length - 1);
1335 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1336 BACKOFF_TIMES[backoffIndex] : 0;
1337 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1338 0);
1339 }
1340
1341 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001342 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001343 int userId = UserHandle.getCallingUserId();
1344 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001345 return hasRestrictionsPinLocked(userId);
1346 }
1347 }
1348
1349 private boolean hasRestrictionsPinLocked(int userId) {
1350 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1351 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1352 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001353 }
1354 return true;
1355 }
1356
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001357 @Override
1358 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001359 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001360 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001361 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001362 }
1363
Amith Yamasani5e486f52013-08-07 11:06:44 -07001364 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001365 synchronized (mPackagesLock) {
1366 // Remove all user restrictions
1367 setUserRestrictions(new Bundle(), userHandle);
1368 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001369 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001370 // Remove any app restrictions
1371 cleanAppRestrictions(userHandle, true);
1372 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001373 if (unblockApps) {
1374 unblockAllAppsForUser(userHandle);
1375 }
1376 }
1377
1378 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001379 mHandler.post(new Runnable() {
1380 @Override
1381 public void run() {
1382 List<ApplicationInfo> apps =
1383 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1384 userHandle).getList();
1385 final long ident = Binder.clearCallingIdentity();
1386 try {
1387 for (ApplicationInfo appInfo : apps) {
1388 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1389 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1390 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1391 userHandle);
1392 }
1393 }
1394 } finally {
1395 Binder.restoreCallingIdentity(ident);
1396 }
1397 }
1398 });
1399 }
1400
Amith Yamasani655d0e22013-06-12 14:19:10 -07001401 /*
1402 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1403 * Not the most secure, but it is at least a second level of protection. First level is that
1404 * the file is in a location only readable by the system process.
1405 * @param password the password.
1406 * @param salt the randomly generated salt
1407 * @return the hash of the pattern in a String.
1408 */
1409 private String passwordToHash(String password, long salt) {
1410 if (password == null) {
1411 return null;
1412 }
1413 String algo = null;
1414 String hashed = salt + password;
1415 try {
1416 byte[] saltedPassword = (password + salt).getBytes();
1417 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1418 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1419 hashed = toHex(sha1) + toHex(md5);
1420 } catch (NoSuchAlgorithmException e) {
1421 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1422 }
1423 return hashed;
1424 }
1425
1426 private static String toHex(byte[] ary) {
1427 final String hex = "0123456789ABCDEF";
1428 String ret = "";
1429 for (int i = 0; i < ary.length; i++) {
1430 ret += hex.charAt((ary[i] >> 4) & 0xf);
1431 ret += hex.charAt(ary[i] & 0xf);
1432 }
1433 return ret;
1434 }
1435
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001436 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001437 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001438 try {
1439 return mContext.getPackageManager().getApplicationInfo(packageName,
1440 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1441 } catch (NameNotFoundException nnfe) {
1442 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001443 } finally {
1444 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001445 }
1446 }
1447
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001448 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001449 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001450 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001451 final ArrayList<String> values = new ArrayList<String>();
1452
1453 FileInputStream fis = null;
1454 try {
1455 AtomicFile restrictionsFile =
1456 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001457 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001458 fis = restrictionsFile.openRead();
1459 XmlPullParser parser = Xml.newPullParser();
1460 parser.setInput(fis, null);
1461 int type;
1462 while ((type = parser.next()) != XmlPullParser.START_TAG
1463 && type != XmlPullParser.END_DOCUMENT) {
1464 ;
1465 }
1466
1467 if (type != XmlPullParser.START_TAG) {
1468 Slog.e(LOG_TAG, "Unable to read restrictions file "
1469 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001470 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001471 }
1472
1473 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1474 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1475 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001476 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001477 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1478 if (multiple != null) {
1479 int count = Integer.parseInt(multiple);
1480 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1481 if (type == XmlPullParser.START_TAG
1482 && parser.getName().equals(TAG_VALUE)) {
1483 values.add(parser.nextText().trim());
1484 count--;
1485 }
1486 }
1487 String [] valueStrings = new String[values.size()];
1488 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001489 restrictions.putStringArray(key, valueStrings);
1490 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1491 restrictions.putBoolean(key, Boolean.parseBoolean(
1492 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001493 } else {
1494 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001495 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001496 }
1497 }
1498 }
1499
1500 } catch (IOException ioe) {
1501 } catch (XmlPullParserException pe) {
1502 } finally {
1503 if (fis != null) {
1504 try {
1505 fis.close();
1506 } catch (IOException e) {
1507 }
1508 }
1509 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001510 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001511 }
1512
1513 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001514 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001515 FileOutputStream fos = null;
1516 AtomicFile restrictionsFile = new AtomicFile(
1517 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001518 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001519 try {
1520 fos = restrictionsFile.startWrite();
1521 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1522
1523 // XmlSerializer serializer = XmlUtils.serializerInstance();
1524 final XmlSerializer serializer = new FastXmlSerializer();
1525 serializer.setOutput(bos, "utf-8");
1526 serializer.startDocument(null, true);
1527 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1528
1529 serializer.startTag(null, TAG_RESTRICTIONS);
1530
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001531 for (String key : restrictions.keySet()) {
1532 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001533 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001534 serializer.attribute(null, ATTR_KEY, key);
1535
1536 if (value instanceof Boolean) {
1537 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1538 serializer.text(value.toString());
1539 } else if (value == null || value instanceof String) {
1540 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1541 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001542 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001543 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1544 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001545 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001546 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001547 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001548 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001549 serializer.endTag(null, TAG_VALUE);
1550 }
1551 }
1552 serializer.endTag(null, TAG_ENTRY);
1553 }
1554
1555 serializer.endTag(null, TAG_RESTRICTIONS);
1556
1557 serializer.endDocument();
1558 restrictionsFile.finishWrite(fos);
1559 } catch (Exception e) {
1560 restrictionsFile.failWrite(fos);
1561 Slog.e(LOG_TAG, "Error writing application restrictions list");
1562 }
1563 }
1564
1565 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001566 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001567 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001568 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001569 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001570 }
1571 }
1572
1573 @Override
1574 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001575 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001576 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001577 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001578 }
1579 // Not found
1580 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001581 }
1582 }
1583
Amith Yamasani0b285492011-04-14 17:35:23 -07001584 /**
1585 * Caches the list of user ids in an array, adjusting the array size when necessary.
1586 */
Amith Yamasani13593602012-03-22 16:16:17 -07001587 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001588 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001589 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001590 if (!mUsers.valueAt(i).partial) {
1591 num++;
1592 }
1593 }
Amith Yamasani16389312012-10-17 21:20:14 -07001594 final int[] newUsers = new int[num];
1595 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001596 for (int i = 0; i < mUsers.size(); i++) {
1597 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001598 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001599 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001600 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001601 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001602 }
1603
1604 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001605 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001606 * @param userId the user that was just foregrounded
1607 */
1608 public void userForeground(int userId) {
1609 synchronized (mPackagesLock) {
1610 UserInfo user = mUsers.get(userId);
1611 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001612 if (user == null || user.partial) {
1613 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1614 return;
1615 }
1616 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001617 user.lastLoggedInTime = now;
1618 writeUserLocked(user);
1619 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001620 // If this is not a restricted profile and there is no restrictions pin, clean up
1621 // all restrictions files that might have been left behind, else clean up just the
1622 // ones with uninstalled packages
1623 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1624 final long salt = pinState == null ? 0 : pinState.salt;
1625 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001626 }
1627 }
1628
1629 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001630 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001631 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1632 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001633 * @return
1634 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001635 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001636 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001637 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001638 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001639 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001640 break;
1641 }
1642 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001643 }
Amith Yamasani195263742012-08-21 15:40:12 -07001644 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001645 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001646 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001647
Amith Yamasanifc95e702013-09-26 13:20:17 -07001648 private String packageToRestrictionsFileName(String packageName) {
1649 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1650 }
1651
1652 private String restrictionsFileNameToPackage(String fileName) {
1653 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1654 (int) (fileName.length() - XML_SUFFIX.length()));
1655 }
1656
Amith Yamasani920ace02012-09-20 22:15:37 -07001657 @Override
1658 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1659 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1660 != PackageManager.PERMISSION_GRANTED) {
1661 pw.println("Permission Denial: can't dump UserManager from from pid="
1662 + Binder.getCallingPid()
1663 + ", uid=" + Binder.getCallingUid()
1664 + " without permission "
1665 + android.Manifest.permission.DUMP);
1666 return;
1667 }
1668
1669 long now = System.currentTimeMillis();
1670 StringBuilder sb = new StringBuilder();
1671 synchronized (mPackagesLock) {
1672 pw.println("Users:");
1673 for (int i = 0; i < mUsers.size(); i++) {
1674 UserInfo user = mUsers.valueAt(i);
1675 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001676 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001677 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001678 if (user.partial) pw.print(" <partial>");
1679 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001680 pw.print(" Created: ");
1681 if (user.creationTime == 0) {
1682 pw.println("<unknown>");
1683 } else {
1684 sb.setLength(0);
1685 TimeUtils.formatDuration(now - user.creationTime, sb);
1686 sb.append(" ago");
1687 pw.println(sb);
1688 }
1689 pw.print(" Last logged in: ");
1690 if (user.lastLoggedInTime == 0) {
1691 pw.println("<unknown>");
1692 } else {
1693 sb.setLength(0);
1694 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1695 sb.append(" ago");
1696 pw.println(sb);
1697 }
1698 }
1699 }
1700 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001701
1702 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1703 @Override
1704 public void onPackageRemoved(String pkg, int uid) {
1705 final int userId = this.getChangingUserId();
1706 // Package could be disappearing because it is being blocked, so also check if
1707 // it has been uninstalled.
1708 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1709 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1710 cleanAppRestrictionsForPackage(pkg, userId);
1711 }
1712 }
1713 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001714}