blob: a0cb0989440302559b378c91d14378e6132f1588 [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;
Jason Monk62062992014-05-06 09:55:28 -040043import android.os.ServiceManager;
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
Jason Monk62062992014-05-06 09:55:28 -040054import com.android.internal.app.IAppOpsService;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070055import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080056import com.android.internal.util.ArrayUtils;
57import com.android.internal.util.FastXmlSerializer;
58
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
62
Amith Yamasani4b2e9342011-03-31 12:38:53 -070063import java.io.BufferedOutputStream;
64import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070065import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070067import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070068import java.io.FileOutputStream;
69import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070070import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070071import java.security.MessageDigest;
72import java.security.NoSuchAlgorithmException;
73import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074import java.util.ArrayList;
75import java.util.List;
76
Amith Yamasani258848d2012-08-10 17:06:33 -070077public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani2a003292012-08-14 18:25:45 -070079 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070080
Amith Yamasani16389312012-10-17 21:20:14 -070081 private static final boolean DBG = false;
82
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070085 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070087 private static final String ATTR_CREATION_TIME = "created";
88 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070089 private static final String ATTR_SALT = "salt";
90 private static final String ATTR_PIN_HASH = "pinHash";
91 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
92 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070093 private static final String ATTR_SERIAL_NO = "serialNumber";
94 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070095 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070096 private static final String ATTR_USER_VERSION = "version";
Kenny Guy2a764942014-04-02 13:29:20 +010097 private static final String ATTR_PROFILE_GROUP_ID = "profileGroupId";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800100 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800101 private static final String TAG_ENTRY = "entry";
102 private static final String TAG_VALUE = "value";
103 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700107 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
108 private static final String ATTR_TYPE_STRING = "s";
109 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700110 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700111
Amith Yamasani0b285492011-04-14 17:35:23 -0700112 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700114 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800116 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700117 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800118
Amith Yamasani634cf312012-10-04 17:34:21 -0700119 private static final int MIN_USER_ID = 10;
120
Amith Yamasani5e486f52013-08-07 11:06:44 -0700121 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700122
Amith Yamasani920ace02012-09-20 22:15:37 -0700123 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
124
Amith Yamasani655d0e22013-06-12 14:19:10 -0700125 // Number of attempts before jumping to the next BACKOFF_TIMES slot
126 private static final int BACKOFF_INC_INTERVAL = 5;
127
128 // Amount of time to force the user to wait before entering the PIN again, after failing
129 // BACKOFF_INC_INTERVAL times.
130 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
131
Dianne Hackborn4428e172012-08-24 17:43:05 -0700132 private final Context mContext;
133 private final PackageManagerService mPm;
134 private final Object mInstallLock;
135 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800137 private final Handler mHandler;
138
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139 private final File mUsersDir;
140 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700141 private final File mBaseUserPath;
142
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800144 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800145
Amith Yamasani655d0e22013-06-12 14:19:10 -0700146 class RestrictionsPinState {
147 long salt;
148 String pinHash;
149 int failedAttempts;
150 long lastAttemptTime;
151 }
152
153 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
154 new SparseArray<RestrictionsPinState>();
155
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800156 /**
157 * Set of user IDs being actively removed. Removed IDs linger in this set
158 * for several seconds to work around a VFS caching issue.
159 */
160 // @GuardedBy("mPackagesLock")
161 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700162
Amith Yamasani0b285492011-04-14 17:35:23 -0700163 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700164 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700165 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700166
Jason Monk62062992014-05-06 09:55:28 -0400167 private IAppOpsService mAppOpsService;
168
Amith Yamasani258848d2012-08-10 17:06:33 -0700169 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700170
Dianne Hackborn4428e172012-08-24 17:43:05 -0700171 public static UserManagerService getInstance() {
172 synchronized (UserManagerService.class) {
173 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700174 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700175 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700176
177 /**
178 * Available for testing purposes.
179 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700180 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700182 }
183
Dianne Hackborn4428e172012-08-24 17:43:05 -0700184 /**
185 * Called by package manager to create the service. This is closely
186 * associated with the package manager, and the given lock is the
187 * package manager's own lock.
188 */
189 UserManagerService(Context context, PackageManagerService pm,
190 Object installLock, Object packagesLock) {
191 this(context, pm, installLock, packagesLock,
192 Environment.getDataDirectory(),
193 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700194 }
195
Dianne Hackborn4428e172012-08-24 17:43:05 -0700196 /**
197 * Available for testing purposes.
198 */
199 private UserManagerService(Context context, PackageManagerService pm,
200 Object installLock, Object packagesLock,
201 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700202 mContext = context;
203 mPm = pm;
204 mInstallLock = installLock;
205 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800206 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700207 synchronized (mInstallLock) {
208 synchronized (mPackagesLock) {
209 mUsersDir = new File(dataDir, USER_INFO_DIR);
210 mUsersDir.mkdirs();
211 // Make zeroth user directory, for services to migrate their files to that location
212 File userZeroDir = new File(mUsersDir, "0");
213 userZeroDir.mkdirs();
214 mBaseUserPath = baseUserPath;
215 FileUtils.setPermissions(mUsersDir.toString(),
216 FileUtils.S_IRWXU|FileUtils.S_IRWXG
217 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
218 -1, -1);
219 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
220 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700221 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700222 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
223 for (int i = 0; i < mUsers.size(); i++) {
224 UserInfo ui = mUsers.valueAt(i);
225 if (ui.partial && i != 0) {
226 partials.add(ui);
227 }
228 }
229 for (int i = 0; i < partials.size(); i++) {
230 UserInfo ui = partials.get(i);
231 Slog.w(LOG_TAG, "Removing partially created user #" + i
232 + " (name=" + ui.name + ")");
233 removeUserStateLocked(ui.id);
234 }
235 sInstance = this;
236 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700237 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700238 }
239
240 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700241 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700242 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400243 mAppOpsService = IAppOpsService.Stub.asInterface(
244 ServiceManager.getService(Context.APP_OPS_SERVICE));
245 for (int i = 0; i < mUserIds.length; ++i) {
246 try {
247 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
248 } catch (RemoteException e) {
249 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
250 }
251 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700252 }
253
254 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700255 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700256 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700257 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700258 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
259 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700260 UserInfo ui = mUsers.valueAt(i);
261 if (ui.partial) {
262 continue;
263 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800264 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700265 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700266 }
Amith Yamasani13593602012-03-22 16:16:17 -0700267 }
268 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700269 }
Amith Yamasani13593602012-03-22 16:16:17 -0700270 }
271
Amith Yamasani258848d2012-08-10 17:06:33 -0700272 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100273 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800274 if (userId != UserHandle.getCallingUserId()) {
275 checkManageUsersPermission("getting profiles related to user " + userId);
276 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700277 final long ident = Binder.clearCallingIdentity();
278 try {
279 synchronized (mPackagesLock) {
280 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100281 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700282 } finally {
283 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000284 }
285 }
286
Amith Yamasanibe465322014-04-24 13:45:17 -0700287 /** Assume permissions already checked and caller's identity cleared */
288 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700289 UserInfo user = getUserInfoLocked(userId);
290 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
291 for (int i = 0; i < mUsers.size(); i++) {
292 UserInfo profile = mUsers.valueAt(i);
293 if (!isProfileOf(user, profile)) {
294 continue;
295 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100296 if (enabledOnly && !profile.isEnabled()) {
297 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700298 }
299 users.add(profile);
300 }
301 return users;
302 }
303
Jessica Hummelbe81c802014-04-22 15:49:22 +0100304 @Override
305 public UserInfo getProfileParent(int userHandle) {
306 checkManageUsersPermission("get the profile parent");
307 synchronized (mPackagesLock) {
308 UserInfo profile = getUserInfoLocked(userHandle);
309 int parentUserId = profile.profileGroupId;
310 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
311 return null;
312 } else {
313 return getUserInfoLocked(parentUserId);
314 }
315 }
316 }
317
Kenny Guy2a764942014-04-02 13:29:20 +0100318 private boolean isProfileOf(UserInfo user, UserInfo profile) {
319 return user.id == profile.id ||
320 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
321 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000322 }
323
324 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100325 public void setUserEnabled(int userId) {
326 checkManageUsersPermission("enable user");
327 synchronized (mPackagesLock) {
328 UserInfo info = getUserInfoLocked(userId);
329 if (info != null && !info.isEnabled()) {
330 info.flags ^= UserInfo.FLAG_DISABLED;
331 writeUserLocked(info);
332 }
333 }
334 }
335
336 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700337 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700338 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700339 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700340 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700341 }
342 }
343
Amith Yamasani71e6c692013-03-24 17:39:28 -0700344 @Override
345 public boolean isRestricted() {
346 synchronized (mPackagesLock) {
347 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
348 }
349 }
350
Amith Yamasani195263742012-08-21 15:40:12 -0700351 /*
352 * Should be locked on mUsers before calling this.
353 */
354 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700355 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700356 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800357 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700358 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
359 return null;
360 }
361 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700362 }
363
Amith Yamasani13593602012-03-22 16:16:17 -0700364 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700365 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700366 return ArrayUtils.contains(mUserIds, userId);
367 }
368 }
369
Amith Yamasani258848d2012-08-10 17:06:33 -0700370 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700371 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700372 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700373 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700374 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700375 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700376 if (info == null || info.partial) {
377 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
378 return;
379 }
Amith Yamasani13593602012-03-22 16:16:17 -0700380 if (name != null && !name.equals(info.name)) {
381 info.name = name;
382 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700383 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700384 }
385 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700386 if (changed) {
387 sendUserInfoChangedBroadcast(userId);
388 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700389 }
390
Amith Yamasani258848d2012-08-10 17:06:33 -0700391 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700392 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700393 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700394 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700395 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700396 if (info == null || info.partial) {
397 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
398 return;
399 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700400 writeBitmapLocked(info, bitmap);
401 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700402 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700403 sendUserInfoChangedBroadcast(userId);
404 }
405
406 private void sendUserInfoChangedBroadcast(int userId) {
407 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
408 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
409 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700410 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700411 }
412
Amith Yamasani258848d2012-08-10 17:06:33 -0700413 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700414 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700415 synchronized (mPackagesLock) {
416 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700417 if (info == null || info.partial) {
418 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
419 return null;
420 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100421 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
422 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
423 || callingGroupId != info.profileGroupId) {
424 checkManageUsersPermission("get the icon of a user who is not related");
425 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700426 if (info.iconPath == null) {
427 return null;
428 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700429 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700430 }
431 }
432
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700433 public void makeInitialized(int userId) {
434 checkManageUsersPermission("makeInitialized");
435 synchronized (mPackagesLock) {
436 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700437 if (info == null || info.partial) {
438 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
439 }
440 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700441 info.flags |= UserInfo.FLAG_INITIALIZED;
442 writeUserLocked(info);
443 }
444 }
445 }
446
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800447 @Override
448 public Bundle getUserRestrictions(int userId) {
449 // checkManageUsersPermission("getUserRestrictions");
450
451 synchronized (mPackagesLock) {
452 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700453 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800454 }
455 }
456
457 @Override
458 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700459 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700460 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800461
462 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700463 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800464 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400465 long token = Binder.clearCallingIdentity();
466 try {
467 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
468 } catch (RemoteException e) {
469 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
470 } finally {
471 Binder.restoreCallingIdentity(token);
472 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800473 writeUserLocked(mUsers.get(userId));
474 }
475 }
476
Amith Yamasani258848d2012-08-10 17:06:33 -0700477 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700478 * Check if we've hit the limit of how many users can be created.
479 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700480 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700481 int aliveUserCount = 0;
482 final int totalUserCount = mUsers.size();
483 // Skip over users being removed
484 for (int i = 0; i < totalUserCount; i++) {
485 UserInfo user = mUsers.valueAt(i);
486 if (!mRemovingUserIds.get(user.id)) {
487 aliveUserCount++;
488 }
489 }
490 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700491 }
492
493 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700494 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700495 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700496 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700497 *
498 * @param message used as message if SecurityException is thrown
499 * @throws SecurityException if the caller is not system or root
500 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700501 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700502 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700503 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400504 && ActivityManager.checkComponentPermission(
505 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700506 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
507 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
508 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400509 }
510
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700511 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700512 try {
513 File dir = new File(mUsersDir, Integer.toString(info.id));
514 File file = new File(dir, USER_PHOTO_FILENAME);
515 if (!dir.exists()) {
516 dir.mkdir();
517 FileUtils.setPermissions(
518 dir.getPath(),
519 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
520 -1, -1);
521 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700522 FileOutputStream os;
523 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700524 info.iconPath = file.getAbsolutePath();
525 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700526 try {
527 os.close();
528 } catch (IOException ioe) {
529 // What the ... !
530 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700531 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700532 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700533 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700534 }
535
Amith Yamasani0b285492011-04-14 17:35:23 -0700536 /**
537 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
538 * cache it elsewhere.
539 * @return the array of user ids.
540 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700541 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700542 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700543 return mUserIds;
544 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700545 }
546
Dianne Hackborn4428e172012-08-24 17:43:05 -0700547 int[] getUserIdsLPr() {
548 return mUserIds;
549 }
550
Amith Yamasani13593602012-03-22 16:16:17 -0700551 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700552 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700553 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700554 return;
555 }
556 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700557 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700558 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700559 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700560 XmlPullParser parser = Xml.newPullParser();
561 parser.setInput(fis, null);
562 int type;
563 while ((type = parser.next()) != XmlPullParser.START_TAG
564 && type != XmlPullParser.END_DOCUMENT) {
565 ;
566 }
567
568 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700569 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700570 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700571 return;
572 }
573
Amith Yamasani2a003292012-08-14 18:25:45 -0700574 mNextSerialNumber = -1;
575 if (parser.getName().equals(TAG_USERS)) {
576 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
577 if (lastSerialNumber != null) {
578 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
579 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700580 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
581 if (versionNumber != null) {
582 mUserVersion = Integer.parseInt(versionNumber);
583 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700584 }
585
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700586 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
587 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
588 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800589 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700590
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700591 if (user != null) {
592 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700593 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
594 mNextSerialNumber = user.id + 1;
595 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700596 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700597 }
598 }
Amith Yamasani13593602012-03-22 16:16:17 -0700599 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700600 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700601 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700602 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700603 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700604 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800605 } finally {
606 if (fis != null) {
607 try {
608 fis.close();
609 } catch (IOException e) {
610 }
611 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700612 }
613 }
614
Amith Yamasani6f34b412012-10-22 18:19:27 -0700615 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800616 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700617 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700618 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700619 int userVersion = mUserVersion;
620 if (userVersion < 1) {
621 // Assign a proper name for the owner, if not initialized correctly before
622 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
623 if ("Primary".equals(user.name)) {
624 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
625 writeUserLocked(user);
626 }
627 userVersion = 1;
628 }
629
Amith Yamasanibc9625052012-11-15 14:39:18 -0800630 if (userVersion < 2) {
631 // Owner should be marked as initialized
632 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
633 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
634 user.flags |= UserInfo.FLAG_INITIALIZED;
635 writeUserLocked(user);
636 }
637 userVersion = 2;
638 }
639
Amith Yamasani350962c2013-08-06 11:18:53 -0700640
Amith Yamasani5e486f52013-08-07 11:06:44 -0700641 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700642 userVersion = 4;
643 }
644
Amith Yamasani6f34b412012-10-22 18:19:27 -0700645 if (userVersion < USER_VERSION) {
646 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
647 + USER_VERSION);
648 } else {
649 mUserVersion = userVersion;
650 writeUserListLocked();
651 }
652 }
653
Amith Yamasani13593602012-03-22 16:16:17 -0700654 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700655 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800656 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700657 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700658 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700659 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700660 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400661 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800662
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500663 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800664 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
665
Amith Yamasani13593602012-03-22 16:16:17 -0700666 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700667
Amith Yamasani13593602012-03-22 16:16:17 -0700668 writeUserListLocked();
669 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700670 }
671
672 /*
673 * Writes the user file in this format:
674 *
675 * <user flags="20039023" id="0">
676 * <name>Primary</name>
677 * </user>
678 */
Amith Yamasani13593602012-03-22 16:16:17 -0700679 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700680 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700681 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700682 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700683 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700684 final BufferedOutputStream bos = new BufferedOutputStream(fos);
685
686 // XmlSerializer serializer = XmlUtils.serializerInstance();
687 final XmlSerializer serializer = new FastXmlSerializer();
688 serializer.setOutput(bos, "utf-8");
689 serializer.startDocument(null, true);
690 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
691
692 serializer.startTag(null, TAG_USER);
693 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700694 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700695 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700696 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
697 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
698 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700699 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
700 if (pinState != null) {
701 if (pinState.salt != 0) {
702 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
703 }
704 if (pinState.pinHash != null) {
705 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
706 }
707 if (pinState.failedAttempts != 0) {
708 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
709 Integer.toString(pinState.failedAttempts));
710 serializer.attribute(null, ATTR_LAST_RETRY_MS,
711 Long.toString(pinState.lastAttemptTime));
712 }
713 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700714 if (userInfo.iconPath != null) {
715 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
716 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700717 if (userInfo.partial) {
718 serializer.attribute(null, ATTR_PARTIAL, "true");
719 }
Kenny Guy2a764942014-04-02 13:29:20 +0100720 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
721 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
722 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000723 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700724
725 serializer.startTag(null, TAG_NAME);
726 serializer.text(userInfo.name);
727 serializer.endTag(null, TAG_NAME);
728
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800729 Bundle restrictions = mUserRestrictions.get(userInfo.id);
730 if (restrictions != null) {
731 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700732 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
733 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
734 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
735 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
736 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400737 writeBoolean(serializer, restrictions,
738 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
739 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
740 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400741 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
742 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400743 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
744 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
745 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
746 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
747 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
748 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
749 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
750 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
Julia Reynolds36fbc8d2014-06-18 09:26:30 -0400751 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400752 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
753 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
754 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani9f6c25f2014-05-16 14:49:15 -0700755 writeBoolean(serializer, restrictions, UserManager.DISALLOW_TELEPHONY);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800756 serializer.endTag(null, TAG_RESTRICTIONS);
757 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700758 serializer.endTag(null, TAG_USER);
759
760 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700761 userFile.finishWrite(fos);
762 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700763 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700764 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700765 }
766 }
767
768 /*
769 * Writes the user list file in this format:
770 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700771 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772 * <user id="0"></user>
773 * <user id="2"></user>
774 * </users>
775 */
Amith Yamasani13593602012-03-22 16:16:17 -0700776 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700777 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700778 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700779 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700780 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700781 final BufferedOutputStream bos = new BufferedOutputStream(fos);
782
783 // XmlSerializer serializer = XmlUtils.serializerInstance();
784 final XmlSerializer serializer = new FastXmlSerializer();
785 serializer.setOutput(bos, "utf-8");
786 serializer.startDocument(null, true);
787 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
788
789 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700790 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700791 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700792
793 for (int i = 0; i < mUsers.size(); i++) {
794 UserInfo user = mUsers.valueAt(i);
795 serializer.startTag(null, TAG_USER);
796 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
797 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700798 }
799
800 serializer.endTag(null, TAG_USERS);
801
802 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700803 userListFile.finishWrite(fos);
804 } catch (Exception e) {
805 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700806 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700807 }
808 }
809
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800810 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700811 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700812 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700813 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700814 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700815 long creationTime = 0L;
816 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700817 long salt = 0L;
818 String pinHash = null;
819 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100820 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700821 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700822 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800823 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700824
825 FileInputStream fis = null;
826 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700827 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700828 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700829 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700830 XmlPullParser parser = Xml.newPullParser();
831 parser.setInput(fis, null);
832 int type;
833 while ((type = parser.next()) != XmlPullParser.START_TAG
834 && type != XmlPullParser.END_DOCUMENT) {
835 ;
836 }
837
838 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700839 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700840 return null;
841 }
842
843 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700844 int storedId = readIntAttribute(parser, ATTR_ID, -1);
845 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700846 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700847 return null;
848 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700849 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
850 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700851 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700852 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
853 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700854 salt = readLongAttribute(parser, ATTR_SALT, 0L);
855 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
856 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
857 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100858 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
859 UserInfo.NO_PROFILE_GROUP_ID);
860 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
861 // This attribute was added and renamed during development of L.
862 // TODO Remove upgrade path by 1st May 2014
863 profileGroupId = readIntAttribute(parser, "relatedGroupId",
864 UserInfo.NO_PROFILE_GROUP_ID);
865 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700866 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
867 if ("true".equals(valueString)) {
868 partial = true;
869 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700870
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800871 int outerDepth = parser.getDepth();
872 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
873 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
874 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
875 continue;
876 }
877 String tag = parser.getName();
878 if (TAG_NAME.equals(tag)) {
879 type = parser.next();
880 if (type == XmlPullParser.TEXT) {
881 name = parser.getText();
882 }
883 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700884 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
885 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
886 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
887 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
888 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400889 readBoolean(parser, restrictions,
890 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
891 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
892 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400893 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
894 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400895 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
896 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
897 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
898 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
899 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
900 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
901 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
902 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
Julia Reynolds36fbc8d2014-06-18 09:26:30 -0400903 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400904 readBoolean(parser, restrictions,
905 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
906 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
907 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani9f6c25f2014-05-16 14:49:15 -0700908 readBoolean(parser, restrictions, UserManager.DISALLOW_TELEPHONY);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700909 }
910 }
911 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700912
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700913 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700914 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700915 userInfo.creationTime = creationTime;
916 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700917 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100918 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800919 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700920 if (salt != 0L) {
921 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
922 if (pinState == null) {
923 pinState = new RestrictionsPinState();
924 mRestrictionsPinStates.put(id, pinState);
925 }
926 pinState.salt = salt;
927 pinState.pinHash = pinHash;
928 pinState.failedAttempts = failedAttempts;
929 pinState.lastAttemptTime = lastAttemptTime;
930 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700931 return userInfo;
932
933 } catch (IOException ioe) {
934 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800935 } finally {
936 if (fis != null) {
937 try {
938 fis.close();
939 } catch (IOException e) {
940 }
941 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700942 }
943 return null;
944 }
945
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800946 private void readBoolean(XmlPullParser parser, Bundle restrictions,
947 String restrictionKey) {
948 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700949 if (value != null) {
950 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
951 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800952 }
953
954 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
955 throws IOException {
956 if (restrictions.containsKey(restrictionKey)) {
957 xml.attribute(null, restrictionKey,
958 Boolean.toString(restrictions.getBoolean(restrictionKey)));
959 }
960 }
961
Amith Yamasani920ace02012-09-20 22:15:37 -0700962 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
963 String valueString = parser.getAttributeValue(null, attr);
964 if (valueString == null) return defaultValue;
965 try {
966 return Integer.parseInt(valueString);
967 } catch (NumberFormatException nfe) {
968 return defaultValue;
969 }
970 }
971
972 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
973 String valueString = parser.getAttributeValue(null, attr);
974 if (valueString == null) return defaultValue;
975 try {
976 return Long.parseLong(valueString);
977 } catch (NumberFormatException nfe) {
978 return defaultValue;
979 }
980 }
981
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700982 private boolean isPackageInstalled(String pkg, int userId) {
983 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
984 PackageManager.GET_UNINSTALLED_PACKAGES,
985 userId);
986 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
987 return false;
988 }
989 return true;
990 }
991
Amith Yamasanib82add22013-07-09 11:24:44 -0700992 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700993 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
994 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -0700995 * Does not do any permissions checking.
996 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700997 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -0700998 synchronized (mPackagesLock) {
999 File dir = Environment.getUserSystemDirectory(userId);
1000 String[] files = dir.list();
1001 if (files == null) return;
1002 for (String fileName : files) {
1003 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1004 File resFile = new File(dir, fileName);
1005 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001006 if (all) {
1007 resFile.delete();
1008 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -07001009 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001010 if (!isPackageInstalled(pkg, userId)) {
1011 resFile.delete();
1012 }
1013 }
Amith Yamasanib82add22013-07-09 11:24:44 -07001014 }
1015 }
1016 }
1017 }
1018 }
1019
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001020 /**
1021 * Removes the app restrictions file for a specific package and user id, if it exists.
1022 */
1023 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1024 synchronized (mPackagesLock) {
1025 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001026 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001027 if (resFile.exists()) {
1028 resFile.delete();
1029 }
1030 }
1031 }
1032
Kenny Guya52dc3e2014-02-11 15:33:14 +00001033 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001034 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001035 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001036 if (userId != UserHandle.USER_OWNER) {
1037 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001038 return null;
1039 }
Kenny Guy2a764942014-04-02 13:29:20 +01001040 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001041 }
1042
Amith Yamasani258848d2012-08-10 17:06:33 -07001043 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001044 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001045 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001046 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001047 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001048
Jessica Hummelbe81c802014-04-22 15:49:22 +01001049 private UserInfo createUserInternal(String name, int flags, int parentId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001050 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001051 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001052 try {
1053 synchronized (mInstallLock) {
1054 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001055 UserInfo parent = null;
1056 if (parentId != UserHandle.USER_NULL) {
1057 parent = getUserInfoLocked(parentId);
1058 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001059 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001060 if (isUserLimitReachedLocked()) return null;
1061 int userId = getNextAvailableIdLocked();
1062 userInfo = new UserInfo(userId, name, null, flags);
1063 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1064 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001065 long now = System.currentTimeMillis();
1066 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001067 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001068 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001069 mUsers.put(userId, userInfo);
1070 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001071 if (parent != null) {
1072 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1073 parent.profileGroupId = parent.id;
1074 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001075 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001076 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001077 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001078 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001079 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001080 userInfo.partial = false;
1081 writeUserLocked(userInfo);
1082 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001083 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001084 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001085 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001086 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001087 if (userInfo != null) {
1088 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1089 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1090 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1091 android.Manifest.permission.MANAGE_USERS);
1092 }
1093 } finally {
1094 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001095 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001096 return userInfo;
1097 }
1098
Amith Yamasani0b285492011-04-14 17:35:23 -07001099 /**
1100 * Removes a user and all data directories created for that user. This method should be called
1101 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001102 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001103 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001104 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001105 checkManageUsersPermission("Only the system can remove users");
Kenny Guyee58b4f2014-05-23 15:19:53 +01001106 long ident = Binder.clearCallingIdentity();
1107 try {
1108 final UserInfo user;
1109 synchronized (mPackagesLock) {
1110 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001111 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001112 return false;
1113 }
1114 mRemovingUserIds.put(userHandle, true);
1115 try {
1116 mAppOpsService.removeUser(userHandle);
1117 } catch (RemoteException e) {
1118 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1119 }
1120 // Set this to a partially created user, so that the user will be purged
1121 // on next startup, in case the runtime stops now before stopping and
1122 // removing the user completely.
1123 user.partial = true;
1124 // Mark it as disabled, so that it isn't returned any more when
1125 // profiles are queried.
1126 user.flags |= UserInfo.FLAG_DISABLED;
1127 writeUserLocked(user);
1128 }
1129
1130 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1131 && user.isManagedProfile()) {
1132 // Send broadcast to notify system that the user removed was a
1133 // managed user.
1134 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1135 }
1136
1137 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1138 int res;
1139 try {
1140 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1141 new IStopUserCallback.Stub() {
1142 @Override
1143 public void userStopped(int userId) {
1144 finishRemoveUser(userId);
1145 }
1146 @Override
1147 public void userStopAborted(int userId) {
1148 }
1149 });
1150 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001151 return false;
1152 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001153 return res == ActivityManager.USER_OP_SUCCESS;
1154 } finally {
1155 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001156 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001157 }
1158
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001159 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001160 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001161 // Let other services shutdown any activity and clean up their state before completely
1162 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001163 long ident = Binder.clearCallingIdentity();
1164 try {
1165 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1166 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001167 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1168 android.Manifest.permission.MANAGE_USERS,
1169
1170 new BroadcastReceiver() {
1171 @Override
1172 public void onReceive(Context context, Intent intent) {
1173 if (DBG) {
1174 Slog.i(LOG_TAG,
1175 "USER_REMOVED broadcast sent, cleaning up user data "
1176 + userHandle);
1177 }
1178 new Thread() {
1179 public void run() {
1180 synchronized (mInstallLock) {
1181 synchronized (mPackagesLock) {
1182 removeUserStateLocked(userHandle);
1183 }
1184 }
1185 }
1186 }.start();
1187 }
1188 },
1189
1190 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001191 } finally {
1192 Binder.restoreCallingIdentity(ident);
1193 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001194 }
1195
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001196 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001197 // Cleanup package manager settings
1198 mPm.cleanUpUserLILPw(userHandle);
1199
1200 // Remove this user from the list
1201 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001202
1203 // Have user ID linger for several seconds to let external storage VFS
1204 // cache entries expire. This must be greater than the 'entry_valid'
1205 // timeout used by the FUSE daemon.
1206 mHandler.postDelayed(new Runnable() {
1207 @Override
1208 public void run() {
1209 synchronized (mPackagesLock) {
1210 mRemovingUserIds.delete(userHandle);
1211 }
1212 }
1213 }, MINUTE_IN_MILLIS);
1214
Amith Yamasani655d0e22013-06-12 14:19:10 -07001215 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001216 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001217 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001218 userFile.delete();
1219 // Update the user list
1220 writeUserListLocked();
1221 updateUserIdsLocked();
1222 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1223 }
1224
Amith Yamasani61f57372012-08-31 12:12:28 -07001225 private void removeDirectoryRecursive(File parent) {
1226 if (parent.isDirectory()) {
1227 String[] files = parent.list();
1228 for (String filename : files) {
1229 File child = new File(parent, filename);
1230 removeDirectoryRecursive(child);
1231 }
1232 }
1233 parent.delete();
1234 }
1235
Kenny Guyf8d3a232014-05-15 16:09:52 +01001236 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001237 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001238 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1239 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001240 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1241 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001242 }
1243
Amith Yamasani2a003292012-08-14 18:25:45 -07001244 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001245 public Bundle getApplicationRestrictions(String packageName) {
1246 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1247 }
1248
1249 @Override
1250 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001251 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001252 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001253 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001254 }
1255 synchronized (mPackagesLock) {
1256 // Read the restrictions from XML
1257 return readApplicationRestrictionsLocked(packageName, userId);
1258 }
1259 }
1260
1261 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001262 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001263 int userId) {
1264 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001265 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001266 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001267 }
1268 synchronized (mPackagesLock) {
1269 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001270 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001271 }
Robin Lee66e5d962014-04-09 16:44:21 +01001272
1273 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1274 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1275 changeIntent.setPackage(packageName);
1276 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1277 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001278 }
1279
Amith Yamasani655d0e22013-06-12 14:19:10 -07001280 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001281 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001282 checkManageUsersPermission("Only system can modify the restrictions pin");
1283 int userId = UserHandle.getCallingUserId();
1284 synchronized (mPackagesLock) {
1285 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1286 if (pinState == null) {
1287 pinState = new RestrictionsPinState();
1288 }
1289 if (newPin == null) {
1290 pinState.salt = 0;
1291 pinState.pinHash = null;
1292 } else {
1293 try {
1294 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1295 } catch (NoSuchAlgorithmException e) {
1296 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1297 }
1298 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1299 pinState.failedAttempts = 0;
1300 }
1301 mRestrictionsPinStates.put(userId, pinState);
1302 writeUserLocked(mUsers.get(userId));
1303 }
1304 return true;
1305 }
1306
1307 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001308 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001309 checkManageUsersPermission("Only system can verify the restrictions pin");
1310 int userId = UserHandle.getCallingUserId();
1311 synchronized (mPackagesLock) {
1312 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1313 // If there's no pin set, return error code
1314 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1315 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1316 } else if (pin == null) {
1317 // If just checking if user can be prompted, return remaining time
1318 int waitTime = getRemainingTimeForPinAttempt(pinState);
1319 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1320 return waitTime;
1321 } else {
1322 int waitTime = getRemainingTimeForPinAttempt(pinState);
1323 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1324 if (waitTime > 0) {
1325 return waitTime;
1326 }
1327 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1328 pinState.failedAttempts = 0;
1329 writeUserLocked(mUsers.get(userId));
1330 return UserManager.PIN_VERIFICATION_SUCCESS;
1331 } else {
1332 pinState.failedAttempts++;
1333 pinState.lastAttemptTime = System.currentTimeMillis();
1334 writeUserLocked(mUsers.get(userId));
1335 return waitTime;
1336 }
1337 }
1338 }
1339 }
1340
1341 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1342 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1343 BACKOFF_TIMES.length - 1);
1344 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1345 BACKOFF_TIMES[backoffIndex] : 0;
1346 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1347 0);
1348 }
1349
1350 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001351 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001352 int userId = UserHandle.getCallingUserId();
1353 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001354 return hasRestrictionsPinLocked(userId);
1355 }
1356 }
1357
1358 private boolean hasRestrictionsPinLocked(int userId) {
1359 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1360 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1361 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001362 }
1363 return true;
1364 }
1365
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001366 @Override
1367 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001368 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001369 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001370 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001371 }
1372
Amith Yamasani5e486f52013-08-07 11:06:44 -07001373 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001374 synchronized (mPackagesLock) {
1375 // Remove all user restrictions
1376 setUserRestrictions(new Bundle(), userHandle);
1377 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001378 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001379 // Remove any app restrictions
1380 cleanAppRestrictions(userHandle, true);
1381 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001382 if (unblockApps) {
1383 unblockAllAppsForUser(userHandle);
1384 }
1385 }
1386
1387 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001388 mHandler.post(new Runnable() {
1389 @Override
1390 public void run() {
1391 List<ApplicationInfo> apps =
1392 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1393 userHandle).getList();
1394 final long ident = Binder.clearCallingIdentity();
1395 try {
1396 for (ApplicationInfo appInfo : apps) {
1397 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1398 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1399 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1400 userHandle);
1401 }
1402 }
1403 } finally {
1404 Binder.restoreCallingIdentity(ident);
1405 }
1406 }
1407 });
1408 }
1409
Amith Yamasani655d0e22013-06-12 14:19:10 -07001410 /*
1411 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1412 * Not the most secure, but it is at least a second level of protection. First level is that
1413 * the file is in a location only readable by the system process.
1414 * @param password the password.
1415 * @param salt the randomly generated salt
1416 * @return the hash of the pattern in a String.
1417 */
1418 private String passwordToHash(String password, long salt) {
1419 if (password == null) {
1420 return null;
1421 }
1422 String algo = null;
1423 String hashed = salt + password;
1424 try {
1425 byte[] saltedPassword = (password + salt).getBytes();
1426 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1427 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1428 hashed = toHex(sha1) + toHex(md5);
1429 } catch (NoSuchAlgorithmException e) {
1430 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1431 }
1432 return hashed;
1433 }
1434
1435 private static String toHex(byte[] ary) {
1436 final String hex = "0123456789ABCDEF";
1437 String ret = "";
1438 for (int i = 0; i < ary.length; i++) {
1439 ret += hex.charAt((ary[i] >> 4) & 0xf);
1440 ret += hex.charAt(ary[i] & 0xf);
1441 }
1442 return ret;
1443 }
1444
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001445 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001446 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001447 try {
1448 return mContext.getPackageManager().getApplicationInfo(packageName,
1449 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1450 } catch (NameNotFoundException nnfe) {
1451 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001452 } finally {
1453 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001454 }
1455 }
1456
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001457 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001458 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001459 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001460 final ArrayList<String> values = new ArrayList<String>();
1461
1462 FileInputStream fis = null;
1463 try {
1464 AtomicFile restrictionsFile =
1465 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001466 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001467 fis = restrictionsFile.openRead();
1468 XmlPullParser parser = Xml.newPullParser();
1469 parser.setInput(fis, null);
1470 int type;
1471 while ((type = parser.next()) != XmlPullParser.START_TAG
1472 && type != XmlPullParser.END_DOCUMENT) {
1473 ;
1474 }
1475
1476 if (type != XmlPullParser.START_TAG) {
1477 Slog.e(LOG_TAG, "Unable to read restrictions file "
1478 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001479 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001480 }
1481
1482 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1483 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1484 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001485 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001486 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1487 if (multiple != null) {
1488 int count = Integer.parseInt(multiple);
1489 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1490 if (type == XmlPullParser.START_TAG
1491 && parser.getName().equals(TAG_VALUE)) {
1492 values.add(parser.nextText().trim());
1493 count--;
1494 }
1495 }
1496 String [] valueStrings = new String[values.size()];
1497 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001498 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001499 } else {
1500 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001501 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1502 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1503 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1504 restrictions.putInt(key, Integer.parseInt(value));
1505 } else {
1506 restrictions.putString(key, value);
1507 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001508 }
1509 }
1510 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001511 } catch (IOException ioe) {
1512 } catch (XmlPullParserException pe) {
1513 } finally {
1514 if (fis != null) {
1515 try {
1516 fis.close();
1517 } catch (IOException e) {
1518 }
1519 }
1520 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001521 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001522 }
1523
1524 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001525 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001526 FileOutputStream fos = null;
1527 AtomicFile restrictionsFile = new AtomicFile(
1528 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001529 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001530 try {
1531 fos = restrictionsFile.startWrite();
1532 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1533
1534 // XmlSerializer serializer = XmlUtils.serializerInstance();
1535 final XmlSerializer serializer = new FastXmlSerializer();
1536 serializer.setOutput(bos, "utf-8");
1537 serializer.startDocument(null, true);
1538 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1539
1540 serializer.startTag(null, TAG_RESTRICTIONS);
1541
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001542 for (String key : restrictions.keySet()) {
1543 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001544 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001545 serializer.attribute(null, ATTR_KEY, key);
1546
1547 if (value instanceof Boolean) {
1548 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1549 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001550 } else if (value instanceof Integer) {
1551 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1552 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001553 } else if (value == null || value instanceof String) {
1554 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1555 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001556 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001557 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1558 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001559 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001560 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001561 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001562 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001563 serializer.endTag(null, TAG_VALUE);
1564 }
1565 }
1566 serializer.endTag(null, TAG_ENTRY);
1567 }
1568
1569 serializer.endTag(null, TAG_RESTRICTIONS);
1570
1571 serializer.endDocument();
1572 restrictionsFile.finishWrite(fos);
1573 } catch (Exception e) {
1574 restrictionsFile.failWrite(fos);
1575 Slog.e(LOG_TAG, "Error writing application restrictions list");
1576 }
1577 }
1578
1579 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001580 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001581 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001582 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001583 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001584 }
1585 }
1586
1587 @Override
1588 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001589 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001590 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001591 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001592 }
1593 // Not found
1594 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001595 }
1596 }
1597
Amith Yamasani0b285492011-04-14 17:35:23 -07001598 /**
1599 * Caches the list of user ids in an array, adjusting the array size when necessary.
1600 */
Amith Yamasani13593602012-03-22 16:16:17 -07001601 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001602 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001603 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001604 if (!mUsers.valueAt(i).partial) {
1605 num++;
1606 }
1607 }
Amith Yamasani16389312012-10-17 21:20:14 -07001608 final int[] newUsers = new int[num];
1609 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001610 for (int i = 0; i < mUsers.size(); i++) {
1611 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001612 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001613 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001614 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001615 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001616 }
1617
1618 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001619 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001620 * @param userId the user that was just foregrounded
1621 */
1622 public void userForeground(int userId) {
1623 synchronized (mPackagesLock) {
1624 UserInfo user = mUsers.get(userId);
1625 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001626 if (user == null || user.partial) {
1627 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1628 return;
1629 }
1630 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001631 user.lastLoggedInTime = now;
1632 writeUserLocked(user);
1633 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001634 // If this is not a restricted profile and there is no restrictions pin, clean up
1635 // all restrictions files that might have been left behind, else clean up just the
1636 // ones with uninstalled packages
1637 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1638 final long salt = pinState == null ? 0 : pinState.salt;
1639 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001640 }
1641 }
1642
1643 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001644 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001645 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1646 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001647 * @return
1648 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001649 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001650 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001651 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001652 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001653 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001654 break;
1655 }
1656 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001657 }
Amith Yamasani195263742012-08-21 15:40:12 -07001658 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001659 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001660 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001661
Amith Yamasanifc95e702013-09-26 13:20:17 -07001662 private String packageToRestrictionsFileName(String packageName) {
1663 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1664 }
1665
1666 private String restrictionsFileNameToPackage(String fileName) {
1667 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1668 (int) (fileName.length() - XML_SUFFIX.length()));
1669 }
1670
Amith Yamasani920ace02012-09-20 22:15:37 -07001671 @Override
1672 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1673 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1674 != PackageManager.PERMISSION_GRANTED) {
1675 pw.println("Permission Denial: can't dump UserManager from from pid="
1676 + Binder.getCallingPid()
1677 + ", uid=" + Binder.getCallingUid()
1678 + " without permission "
1679 + android.Manifest.permission.DUMP);
1680 return;
1681 }
1682
1683 long now = System.currentTimeMillis();
1684 StringBuilder sb = new StringBuilder();
1685 synchronized (mPackagesLock) {
1686 pw.println("Users:");
1687 for (int i = 0; i < mUsers.size(); i++) {
1688 UserInfo user = mUsers.valueAt(i);
1689 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001690 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001691 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001692 if (user.partial) pw.print(" <partial>");
1693 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001694 pw.print(" Created: ");
1695 if (user.creationTime == 0) {
1696 pw.println("<unknown>");
1697 } else {
1698 sb.setLength(0);
1699 TimeUtils.formatDuration(now - user.creationTime, sb);
1700 sb.append(" ago");
1701 pw.println(sb);
1702 }
1703 pw.print(" Last logged in: ");
1704 if (user.lastLoggedInTime == 0) {
1705 pw.println("<unknown>");
1706 } else {
1707 sb.setLength(0);
1708 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1709 sb.append(" ago");
1710 pw.println(sb);
1711 }
1712 }
1713 }
1714 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001715
1716 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1717 @Override
1718 public void onPackageRemoved(String pkg, int uid) {
1719 final int userId = this.getChangingUserId();
1720 // Package could be disappearing because it is being blocked, so also check if
1721 // it has been uninstalled.
1722 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1723 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1724 cleanAppRestrictionsForPackage(pkg, userId);
1725 }
1726 }
1727 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001728}