blob: fd180bf130f291fc8189a31fa2808d77873ad4ce [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";
110
Amith Yamasani0b285492011-04-14 17:35:23 -0700111 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700116 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800117
Amith Yamasani634cf312012-10-04 17:34:21 -0700118 private static final int MIN_USER_ID = 10;
119
Amith Yamasani5e486f52013-08-07 11:06:44 -0700120 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700121
Amith Yamasani920ace02012-09-20 22:15:37 -0700122 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
123
Amith Yamasani655d0e22013-06-12 14:19:10 -0700124 // Number of attempts before jumping to the next BACKOFF_TIMES slot
125 private static final int BACKOFF_INC_INTERVAL = 5;
126
127 // Amount of time to force the user to wait before entering the PIN again, after failing
128 // BACKOFF_INC_INTERVAL times.
129 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
130
Dianne Hackborn4428e172012-08-24 17:43:05 -0700131 private final Context mContext;
132 private final PackageManagerService mPm;
133 private final Object mInstallLock;
134 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800136 private final Handler mHandler;
137
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138 private final File mUsersDir;
139 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700140 private final File mBaseUserPath;
141
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800142 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800143 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800144
Amith Yamasani655d0e22013-06-12 14:19:10 -0700145 class RestrictionsPinState {
146 long salt;
147 String pinHash;
148 int failedAttempts;
149 long lastAttemptTime;
150 }
151
152 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
153 new SparseArray<RestrictionsPinState>();
154
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800155 /**
156 * Set of user IDs being actively removed. Removed IDs linger in this set
157 * for several seconds to work around a VFS caching issue.
158 */
159 // @GuardedBy("mPackagesLock")
160 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700161
Amith Yamasani0b285492011-04-14 17:35:23 -0700162 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700163 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700164 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700165 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700166
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 checkManageUsersPermission("read users");
416 synchronized (mPackagesLock) {
417 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700418 if (info == null || info.partial) {
419 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
420 return null;
421 }
422 if (info.iconPath == null) {
423 return null;
424 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700425 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700426 }
427 }
428
429 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700430 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700431 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700432 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700433 if (mGuestEnabled != enable) {
434 mGuestEnabled = enable;
435 // Erase any guest user that currently exists
436 for (int i = 0; i < mUsers.size(); i++) {
437 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700438 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700439 if (!enable) {
440 removeUser(user.id);
441 }
442 return;
443 }
444 }
445 // No guest was found
446 if (enable) {
447 createUser("Guest", UserInfo.FLAG_GUEST);
448 }
449 }
450 }
451 }
452
453 @Override
454 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700455 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700456 return mGuestEnabled;
457 }
458 }
459
460 @Override
461 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700462 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700463 // TODO:
464 }
465
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700466 public void makeInitialized(int userId) {
467 checkManageUsersPermission("makeInitialized");
468 synchronized (mPackagesLock) {
469 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700470 if (info == null || info.partial) {
471 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
472 }
473 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700474 info.flags |= UserInfo.FLAG_INITIALIZED;
475 writeUserLocked(info);
476 }
477 }
478 }
479
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800480 @Override
481 public Bundle getUserRestrictions(int userId) {
482 // checkManageUsersPermission("getUserRestrictions");
483
484 synchronized (mPackagesLock) {
485 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700486 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800487 }
488 }
489
490 @Override
491 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700492 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700493 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800494
495 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700496 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800497 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400498 long token = Binder.clearCallingIdentity();
499 try {
500 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
501 } catch (RemoteException e) {
502 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
503 } finally {
504 Binder.restoreCallingIdentity(token);
505 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800506 writeUserLocked(mUsers.get(userId));
507 }
508 }
509
Amith Yamasani258848d2012-08-10 17:06:33 -0700510 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700511 * Check if we've hit the limit of how many users can be created.
512 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700513 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700514 int aliveUserCount = 0;
515 final int totalUserCount = mUsers.size();
516 // Skip over users being removed
517 for (int i = 0; i < totalUserCount; i++) {
518 UserInfo user = mUsers.valueAt(i);
519 if (!mRemovingUserIds.get(user.id)) {
520 aliveUserCount++;
521 }
522 }
523 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700524 }
525
526 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700527 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700528 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700529 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700530 *
531 * @param message used as message if SecurityException is thrown
532 * @throws SecurityException if the caller is not system or root
533 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700534 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700535 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700536 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400537 && ActivityManager.checkComponentPermission(
538 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700539 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
540 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
541 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400542 }
543
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700544 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700545 try {
546 File dir = new File(mUsersDir, Integer.toString(info.id));
547 File file = new File(dir, USER_PHOTO_FILENAME);
548 if (!dir.exists()) {
549 dir.mkdir();
550 FileUtils.setPermissions(
551 dir.getPath(),
552 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
553 -1, -1);
554 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700555 FileOutputStream os;
556 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700557 info.iconPath = file.getAbsolutePath();
558 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700559 try {
560 os.close();
561 } catch (IOException ioe) {
562 // What the ... !
563 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700564 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700565 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700566 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700567 }
568
Amith Yamasani0b285492011-04-14 17:35:23 -0700569 /**
570 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
571 * cache it elsewhere.
572 * @return the array of user ids.
573 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700574 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700575 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700576 return mUserIds;
577 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700578 }
579
Dianne Hackborn4428e172012-08-24 17:43:05 -0700580 int[] getUserIdsLPr() {
581 return mUserIds;
582 }
583
Amith Yamasani13593602012-03-22 16:16:17 -0700584 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700585 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700586 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700587 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700588 return;
589 }
590 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700591 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700592 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700593 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700594 XmlPullParser parser = Xml.newPullParser();
595 parser.setInput(fis, null);
596 int type;
597 while ((type = parser.next()) != XmlPullParser.START_TAG
598 && type != XmlPullParser.END_DOCUMENT) {
599 ;
600 }
601
602 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700603 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700604 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700605 return;
606 }
607
Amith Yamasani2a003292012-08-14 18:25:45 -0700608 mNextSerialNumber = -1;
609 if (parser.getName().equals(TAG_USERS)) {
610 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
611 if (lastSerialNumber != null) {
612 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
613 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700614 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
615 if (versionNumber != null) {
616 mUserVersion = Integer.parseInt(versionNumber);
617 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700618 }
619
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700620 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
621 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
622 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800623 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700624
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700625 if (user != null) {
626 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700627 if (user.isGuest()) {
628 mGuestEnabled = true;
629 }
630 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
631 mNextSerialNumber = user.id + 1;
632 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700633 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700634 }
635 }
Amith Yamasani13593602012-03-22 16:16:17 -0700636 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700637 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700638 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700639 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700640 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700641 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800642 } finally {
643 if (fis != null) {
644 try {
645 fis.close();
646 } catch (IOException e) {
647 }
648 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700649 }
650 }
651
Amith Yamasani6f34b412012-10-22 18:19:27 -0700652 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800653 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700654 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700655 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700656 int userVersion = mUserVersion;
657 if (userVersion < 1) {
658 // Assign a proper name for the owner, if not initialized correctly before
659 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
660 if ("Primary".equals(user.name)) {
661 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
662 writeUserLocked(user);
663 }
664 userVersion = 1;
665 }
666
Amith Yamasanibc9625052012-11-15 14:39:18 -0800667 if (userVersion < 2) {
668 // Owner should be marked as initialized
669 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
670 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
671 user.flags |= UserInfo.FLAG_INITIALIZED;
672 writeUserLocked(user);
673 }
674 userVersion = 2;
675 }
676
Amith Yamasani350962c2013-08-06 11:18:53 -0700677
Amith Yamasani5e486f52013-08-07 11:06:44 -0700678 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700679 userVersion = 4;
680 }
681
Amith Yamasani6f34b412012-10-22 18:19:27 -0700682 if (userVersion < USER_VERSION) {
683 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
684 + USER_VERSION);
685 } else {
686 mUserVersion = userVersion;
687 writeUserListLocked();
688 }
689 }
690
Amith Yamasani13593602012-03-22 16:16:17 -0700691 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700692 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800693 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700694 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700695 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700696 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700697 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400698 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800699
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500700 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800701 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
702
Amith Yamasani13593602012-03-22 16:16:17 -0700703 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700704
Amith Yamasani13593602012-03-22 16:16:17 -0700705 writeUserListLocked();
706 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700707 }
708
709 /*
710 * Writes the user file in this format:
711 *
712 * <user flags="20039023" id="0">
713 * <name>Primary</name>
714 * </user>
715 */
Amith Yamasani13593602012-03-22 16:16:17 -0700716 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700717 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700718 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700719 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700720 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700721 final BufferedOutputStream bos = new BufferedOutputStream(fos);
722
723 // XmlSerializer serializer = XmlUtils.serializerInstance();
724 final XmlSerializer serializer = new FastXmlSerializer();
725 serializer.setOutput(bos, "utf-8");
726 serializer.startDocument(null, true);
727 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
728
729 serializer.startTag(null, TAG_USER);
730 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700731 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700732 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700733 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
734 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
735 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700736 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
737 if (pinState != null) {
738 if (pinState.salt != 0) {
739 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
740 }
741 if (pinState.pinHash != null) {
742 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
743 }
744 if (pinState.failedAttempts != 0) {
745 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
746 Integer.toString(pinState.failedAttempts));
747 serializer.attribute(null, ATTR_LAST_RETRY_MS,
748 Long.toString(pinState.lastAttemptTime));
749 }
750 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700751 if (userInfo.iconPath != null) {
752 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
753 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700754 if (userInfo.partial) {
755 serializer.attribute(null, ATTR_PARTIAL, "true");
756 }
Kenny Guy2a764942014-04-02 13:29:20 +0100757 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
758 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
759 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000760 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700761
762 serializer.startTag(null, TAG_NAME);
763 serializer.text(userInfo.name);
764 serializer.endTag(null, TAG_NAME);
765
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800766 Bundle restrictions = mUserRestrictions.get(userInfo.id);
767 if (restrictions != null) {
768 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700769 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
770 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
771 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
772 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
773 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400774 writeBoolean(serializer, restrictions,
775 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
776 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
777 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400778 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
779 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400780 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
781 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
782 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
783 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
784 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
785 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
786 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
787 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
788 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_APPS);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400789 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
790 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
791 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800792 serializer.endTag(null, TAG_RESTRICTIONS);
793 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700794 serializer.endTag(null, TAG_USER);
795
796 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700797 userFile.finishWrite(fos);
798 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700799 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700800 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700801 }
802 }
803
804 /*
805 * Writes the user list file in this format:
806 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700807 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700808 * <user id="0"></user>
809 * <user id="2"></user>
810 * </users>
811 */
Amith Yamasani13593602012-03-22 16:16:17 -0700812 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700813 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700814 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700815 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700816 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817 final BufferedOutputStream bos = new BufferedOutputStream(fos);
818
819 // XmlSerializer serializer = XmlUtils.serializerInstance();
820 final XmlSerializer serializer = new FastXmlSerializer();
821 serializer.setOutput(bos, "utf-8");
822 serializer.startDocument(null, true);
823 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
824
825 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700826 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700827 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700828
829 for (int i = 0; i < mUsers.size(); i++) {
830 UserInfo user = mUsers.valueAt(i);
831 serializer.startTag(null, TAG_USER);
832 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
833 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700834 }
835
836 serializer.endTag(null, TAG_USERS);
837
838 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700839 userListFile.finishWrite(fos);
840 } catch (Exception e) {
841 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700842 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700843 }
844 }
845
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800846 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700847 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700848 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700849 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700850 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700851 long creationTime = 0L;
852 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700853 long salt = 0L;
854 String pinHash = null;
855 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100856 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700857 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700858 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800859 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700860
861 FileInputStream fis = null;
862 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700863 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700864 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700865 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700866 XmlPullParser parser = Xml.newPullParser();
867 parser.setInput(fis, null);
868 int type;
869 while ((type = parser.next()) != XmlPullParser.START_TAG
870 && type != XmlPullParser.END_DOCUMENT) {
871 ;
872 }
873
874 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700875 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700876 return null;
877 }
878
879 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700880 int storedId = readIntAttribute(parser, ATTR_ID, -1);
881 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700882 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700883 return null;
884 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700885 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
886 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700887 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700888 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
889 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700890 salt = readLongAttribute(parser, ATTR_SALT, 0L);
891 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
892 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
893 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100894 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
895 UserInfo.NO_PROFILE_GROUP_ID);
896 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
897 // This attribute was added and renamed during development of L.
898 // TODO Remove upgrade path by 1st May 2014
899 profileGroupId = readIntAttribute(parser, "relatedGroupId",
900 UserInfo.NO_PROFILE_GROUP_ID);
901 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700902 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
903 if ("true".equals(valueString)) {
904 partial = true;
905 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700906
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800907 int outerDepth = parser.getDepth();
908 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
909 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
910 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
911 continue;
912 }
913 String tag = parser.getName();
914 if (TAG_NAME.equals(tag)) {
915 type = parser.next();
916 if (type == XmlPullParser.TEXT) {
917 name = parser.getText();
918 }
919 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700920 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
921 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
922 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
923 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
924 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400925 readBoolean(parser, restrictions,
926 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
927 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
928 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400929 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
930 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Julia Reynoldsd46d0f92014-04-23 15:23:24 -0400931 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
932 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
933 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
934 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
935 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
936 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
937 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
938 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
939 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_APPS);
Emily Bernier394a6cd2014-05-07 12:49:20 -0400940 readBoolean(parser, restrictions,
941 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
942 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
943 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700944 }
945 }
946 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700947
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700948 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700949 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700950 userInfo.creationTime = creationTime;
951 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700952 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100953 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800954 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700955 if (salt != 0L) {
956 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
957 if (pinState == null) {
958 pinState = new RestrictionsPinState();
959 mRestrictionsPinStates.put(id, pinState);
960 }
961 pinState.salt = salt;
962 pinState.pinHash = pinHash;
963 pinState.failedAttempts = failedAttempts;
964 pinState.lastAttemptTime = lastAttemptTime;
965 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700966 return userInfo;
967
968 } catch (IOException ioe) {
969 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800970 } finally {
971 if (fis != null) {
972 try {
973 fis.close();
974 } catch (IOException e) {
975 }
976 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700977 }
978 return null;
979 }
980
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800981 private void readBoolean(XmlPullParser parser, Bundle restrictions,
982 String restrictionKey) {
983 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700984 if (value != null) {
985 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
986 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800987 }
988
989 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
990 throws IOException {
991 if (restrictions.containsKey(restrictionKey)) {
992 xml.attribute(null, restrictionKey,
993 Boolean.toString(restrictions.getBoolean(restrictionKey)));
994 }
995 }
996
Amith Yamasani920ace02012-09-20 22:15:37 -0700997 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
998 String valueString = parser.getAttributeValue(null, attr);
999 if (valueString == null) return defaultValue;
1000 try {
1001 return Integer.parseInt(valueString);
1002 } catch (NumberFormatException nfe) {
1003 return defaultValue;
1004 }
1005 }
1006
1007 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1008 String valueString = parser.getAttributeValue(null, attr);
1009 if (valueString == null) return defaultValue;
1010 try {
1011 return Long.parseLong(valueString);
1012 } catch (NumberFormatException nfe) {
1013 return defaultValue;
1014 }
1015 }
1016
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001017 private boolean isPackageInstalled(String pkg, int userId) {
1018 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1019 PackageManager.GET_UNINSTALLED_PACKAGES,
1020 userId);
1021 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1022 return false;
1023 }
1024 return true;
1025 }
1026
Amith Yamasanib82add22013-07-09 11:24:44 -07001027 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001028 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
1029 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -07001030 * Does not do any permissions checking.
1031 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001032 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001033 synchronized (mPackagesLock) {
1034 File dir = Environment.getUserSystemDirectory(userId);
1035 String[] files = dir.list();
1036 if (files == null) return;
1037 for (String fileName : files) {
1038 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1039 File resFile = new File(dir, fileName);
1040 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001041 if (all) {
1042 resFile.delete();
1043 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -07001044 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001045 if (!isPackageInstalled(pkg, userId)) {
1046 resFile.delete();
1047 }
1048 }
Amith Yamasanib82add22013-07-09 11:24:44 -07001049 }
1050 }
1051 }
1052 }
1053 }
1054
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001055 /**
1056 * Removes the app restrictions file for a specific package and user id, if it exists.
1057 */
1058 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1059 synchronized (mPackagesLock) {
1060 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001061 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001062 if (resFile.exists()) {
1063 resFile.delete();
1064 }
1065 }
1066 }
1067
Kenny Guya52dc3e2014-02-11 15:33:14 +00001068 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001069 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001070 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001071 if (userId != UserHandle.USER_OWNER) {
1072 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001073 return null;
1074 }
Kenny Guy2a764942014-04-02 13:29:20 +01001075 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001076 }
1077
Amith Yamasani258848d2012-08-10 17:06:33 -07001078 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001079 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001080 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001081 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001082 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001083
Jessica Hummelbe81c802014-04-22 15:49:22 +01001084 private UserInfo createUserInternal(String name, int flags, int parentId) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001085 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001086 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001087 try {
1088 synchronized (mInstallLock) {
1089 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001090 UserInfo parent = null;
1091 if (parentId != UserHandle.USER_NULL) {
1092 parent = getUserInfoLocked(parentId);
1093 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001094 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001095 if (isUserLimitReachedLocked()) return null;
1096 int userId = getNextAvailableIdLocked();
1097 userInfo = new UserInfo(userId, name, null, flags);
1098 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1099 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001100 long now = System.currentTimeMillis();
1101 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001102 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001103 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001104 mUsers.put(userId, userInfo);
1105 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001106 if (parent != null) {
1107 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1108 parent.profileGroupId = parent.id;
1109 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001110 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001111 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001112 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001113 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001114 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001115 userInfo.partial = false;
1116 writeUserLocked(userInfo);
1117 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001118 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001119 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001120 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001121 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001122 if (userInfo != null) {
1123 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1124 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1125 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1126 android.Manifest.permission.MANAGE_USERS);
1127 }
1128 } finally {
1129 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001130 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001131 return userInfo;
1132 }
1133
Amith Yamasani0b285492011-04-14 17:35:23 -07001134 /**
1135 * Removes a user and all data directories created for that user. This method should be called
1136 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001137 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001138 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001139 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001140 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001141 final UserInfo user;
1142 synchronized (mPackagesLock) {
1143 user = mUsers.get(userHandle);
1144 if (userHandle == 0 || user == null) {
1145 return false;
1146 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001147 mRemovingUserIds.put(userHandle, true);
Jason Monk62062992014-05-06 09:55:28 -04001148 try {
1149 mAppOpsService.removeUser(userHandle);
1150 } catch (RemoteException e) {
1151 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1152 }
Amith Yamasani756901d2012-10-12 12:30:07 -07001153 // Set this to a partially created user, so that the user will be purged
1154 // on next startup, in case the runtime stops now before stopping and
1155 // removing the user completely.
1156 user.partial = true;
Adam Connors7b66ed52014-04-14 11:58:10 +01001157 // Mark it as disabled, so that it isn't returned any more when
1158 // profiles are queried.
1159 user.flags |= UserInfo.FLAG_DISABLED;
Amith Yamasani756901d2012-10-12 12:30:07 -07001160 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001161 }
Kenny Guyf8d3a232014-05-15 16:09:52 +01001162
1163 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1164 && user.isManagedProfile()) {
1165 // Send broadcast to notify system that the user removed was a
1166 // managed user.
1167 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1168 }
1169
Amith Yamasani16389312012-10-17 21:20:14 -07001170 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001171 int res;
1172 try {
1173 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1174 new IStopUserCallback.Stub() {
1175 @Override
1176 public void userStopped(int userId) {
1177 finishRemoveUser(userId);
1178 }
1179 @Override
1180 public void userStopAborted(int userId) {
1181 }
1182 });
1183 } catch (RemoteException e) {
1184 return false;
1185 }
1186
1187 return res == ActivityManager.USER_OP_SUCCESS;
1188 }
1189
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001190 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001191 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001192 // Let other services shutdown any activity and clean up their state before completely
1193 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001194 long ident = Binder.clearCallingIdentity();
1195 try {
1196 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1197 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001198 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1199 android.Manifest.permission.MANAGE_USERS,
1200
1201 new BroadcastReceiver() {
1202 @Override
1203 public void onReceive(Context context, Intent intent) {
1204 if (DBG) {
1205 Slog.i(LOG_TAG,
1206 "USER_REMOVED broadcast sent, cleaning up user data "
1207 + userHandle);
1208 }
1209 new Thread() {
1210 public void run() {
1211 synchronized (mInstallLock) {
1212 synchronized (mPackagesLock) {
1213 removeUserStateLocked(userHandle);
1214 }
1215 }
1216 }
1217 }.start();
1218 }
1219 },
1220
1221 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001222 } finally {
1223 Binder.restoreCallingIdentity(ident);
1224 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001225 }
1226
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001227 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001228 // Cleanup package manager settings
1229 mPm.cleanUpUserLILPw(userHandle);
1230
1231 // Remove this user from the list
1232 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001233
1234 // Have user ID linger for several seconds to let external storage VFS
1235 // cache entries expire. This must be greater than the 'entry_valid'
1236 // timeout used by the FUSE daemon.
1237 mHandler.postDelayed(new Runnable() {
1238 @Override
1239 public void run() {
1240 synchronized (mPackagesLock) {
1241 mRemovingUserIds.delete(userHandle);
1242 }
1243 }
1244 }, MINUTE_IN_MILLIS);
1245
Amith Yamasani655d0e22013-06-12 14:19:10 -07001246 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001247 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001248 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001249 userFile.delete();
1250 // Update the user list
1251 writeUserListLocked();
1252 updateUserIdsLocked();
1253 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1254 }
1255
Amith Yamasani61f57372012-08-31 12:12:28 -07001256 private void removeDirectoryRecursive(File parent) {
1257 if (parent.isDirectory()) {
1258 String[] files = parent.list();
1259 for (String filename : files) {
1260 File child = new File(parent, filename);
1261 removeDirectoryRecursive(child);
1262 }
1263 }
1264 parent.delete();
1265 }
1266
Kenny Guyf8d3a232014-05-15 16:09:52 +01001267 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001268 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001269 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1270 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1271 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001272 }
1273
Amith Yamasani2a003292012-08-14 18:25:45 -07001274 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001275 public Bundle getApplicationRestrictions(String packageName) {
1276 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1277 }
1278
1279 @Override
1280 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001281 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001282 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001283 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001284 }
1285 synchronized (mPackagesLock) {
1286 // Read the restrictions from XML
1287 return readApplicationRestrictionsLocked(packageName, userId);
1288 }
1289 }
1290
1291 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001292 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001293 int userId) {
1294 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001295 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001296 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001297 }
1298 synchronized (mPackagesLock) {
1299 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001300 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001301 }
Robin Lee66e5d962014-04-09 16:44:21 +01001302
1303 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1304 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1305 changeIntent.setPackage(packageName);
1306 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1307 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001308 }
1309
Amith Yamasani655d0e22013-06-12 14:19:10 -07001310 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001311 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001312 checkManageUsersPermission("Only system can modify the restrictions pin");
1313 int userId = UserHandle.getCallingUserId();
1314 synchronized (mPackagesLock) {
1315 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1316 if (pinState == null) {
1317 pinState = new RestrictionsPinState();
1318 }
1319 if (newPin == null) {
1320 pinState.salt = 0;
1321 pinState.pinHash = null;
1322 } else {
1323 try {
1324 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1325 } catch (NoSuchAlgorithmException e) {
1326 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1327 }
1328 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1329 pinState.failedAttempts = 0;
1330 }
1331 mRestrictionsPinStates.put(userId, pinState);
1332 writeUserLocked(mUsers.get(userId));
1333 }
1334 return true;
1335 }
1336
1337 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001338 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001339 checkManageUsersPermission("Only system can verify the restrictions pin");
1340 int userId = UserHandle.getCallingUserId();
1341 synchronized (mPackagesLock) {
1342 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1343 // If there's no pin set, return error code
1344 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1345 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1346 } else if (pin == null) {
1347 // If just checking if user can be prompted, return remaining time
1348 int waitTime = getRemainingTimeForPinAttempt(pinState);
1349 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1350 return waitTime;
1351 } else {
1352 int waitTime = getRemainingTimeForPinAttempt(pinState);
1353 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1354 if (waitTime > 0) {
1355 return waitTime;
1356 }
1357 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1358 pinState.failedAttempts = 0;
1359 writeUserLocked(mUsers.get(userId));
1360 return UserManager.PIN_VERIFICATION_SUCCESS;
1361 } else {
1362 pinState.failedAttempts++;
1363 pinState.lastAttemptTime = System.currentTimeMillis();
1364 writeUserLocked(mUsers.get(userId));
1365 return waitTime;
1366 }
1367 }
1368 }
1369 }
1370
1371 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1372 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1373 BACKOFF_TIMES.length - 1);
1374 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1375 BACKOFF_TIMES[backoffIndex] : 0;
1376 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1377 0);
1378 }
1379
1380 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001381 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001382 int userId = UserHandle.getCallingUserId();
1383 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001384 return hasRestrictionsPinLocked(userId);
1385 }
1386 }
1387
1388 private boolean hasRestrictionsPinLocked(int userId) {
1389 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1390 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1391 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001392 }
1393 return true;
1394 }
1395
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001396 @Override
1397 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001398 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001399 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001400 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001401 }
1402
Amith Yamasani5e486f52013-08-07 11:06:44 -07001403 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001404 synchronized (mPackagesLock) {
1405 // Remove all user restrictions
1406 setUserRestrictions(new Bundle(), userHandle);
1407 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001408 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001409 // Remove any app restrictions
1410 cleanAppRestrictions(userHandle, true);
1411 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001412 if (unblockApps) {
1413 unblockAllAppsForUser(userHandle);
1414 }
1415 }
1416
1417 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001418 mHandler.post(new Runnable() {
1419 @Override
1420 public void run() {
1421 List<ApplicationInfo> apps =
1422 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1423 userHandle).getList();
1424 final long ident = Binder.clearCallingIdentity();
1425 try {
1426 for (ApplicationInfo appInfo : apps) {
1427 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1428 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1429 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1430 userHandle);
1431 }
1432 }
1433 } finally {
1434 Binder.restoreCallingIdentity(ident);
1435 }
1436 }
1437 });
1438 }
1439
Amith Yamasani655d0e22013-06-12 14:19:10 -07001440 /*
1441 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1442 * Not the most secure, but it is at least a second level of protection. First level is that
1443 * the file is in a location only readable by the system process.
1444 * @param password the password.
1445 * @param salt the randomly generated salt
1446 * @return the hash of the pattern in a String.
1447 */
1448 private String passwordToHash(String password, long salt) {
1449 if (password == null) {
1450 return null;
1451 }
1452 String algo = null;
1453 String hashed = salt + password;
1454 try {
1455 byte[] saltedPassword = (password + salt).getBytes();
1456 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1457 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1458 hashed = toHex(sha1) + toHex(md5);
1459 } catch (NoSuchAlgorithmException e) {
1460 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1461 }
1462 return hashed;
1463 }
1464
1465 private static String toHex(byte[] ary) {
1466 final String hex = "0123456789ABCDEF";
1467 String ret = "";
1468 for (int i = 0; i < ary.length; i++) {
1469 ret += hex.charAt((ary[i] >> 4) & 0xf);
1470 ret += hex.charAt(ary[i] & 0xf);
1471 }
1472 return ret;
1473 }
1474
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001475 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001476 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001477 try {
1478 return mContext.getPackageManager().getApplicationInfo(packageName,
1479 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1480 } catch (NameNotFoundException nnfe) {
1481 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001482 } finally {
1483 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001484 }
1485 }
1486
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001487 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001488 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001489 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001490 final ArrayList<String> values = new ArrayList<String>();
1491
1492 FileInputStream fis = null;
1493 try {
1494 AtomicFile restrictionsFile =
1495 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001496 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001497 fis = restrictionsFile.openRead();
1498 XmlPullParser parser = Xml.newPullParser();
1499 parser.setInput(fis, null);
1500 int type;
1501 while ((type = parser.next()) != XmlPullParser.START_TAG
1502 && type != XmlPullParser.END_DOCUMENT) {
1503 ;
1504 }
1505
1506 if (type != XmlPullParser.START_TAG) {
1507 Slog.e(LOG_TAG, "Unable to read restrictions file "
1508 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001509 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001510 }
1511
1512 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1513 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1514 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001515 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001516 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1517 if (multiple != null) {
1518 int count = Integer.parseInt(multiple);
1519 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1520 if (type == XmlPullParser.START_TAG
1521 && parser.getName().equals(TAG_VALUE)) {
1522 values.add(parser.nextText().trim());
1523 count--;
1524 }
1525 }
1526 String [] valueStrings = new String[values.size()];
1527 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001528 restrictions.putStringArray(key, valueStrings);
1529 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1530 restrictions.putBoolean(key, Boolean.parseBoolean(
1531 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001532 } else {
1533 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001534 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001535 }
1536 }
1537 }
1538
1539 } catch (IOException ioe) {
1540 } catch (XmlPullParserException pe) {
1541 } finally {
1542 if (fis != null) {
1543 try {
1544 fis.close();
1545 } catch (IOException e) {
1546 }
1547 }
1548 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001549 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001550 }
1551
1552 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001553 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001554 FileOutputStream fos = null;
1555 AtomicFile restrictionsFile = new AtomicFile(
1556 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001557 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001558 try {
1559 fos = restrictionsFile.startWrite();
1560 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1561
1562 // XmlSerializer serializer = XmlUtils.serializerInstance();
1563 final XmlSerializer serializer = new FastXmlSerializer();
1564 serializer.setOutput(bos, "utf-8");
1565 serializer.startDocument(null, true);
1566 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1567
1568 serializer.startTag(null, TAG_RESTRICTIONS);
1569
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001570 for (String key : restrictions.keySet()) {
1571 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001572 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001573 serializer.attribute(null, ATTR_KEY, key);
1574
1575 if (value instanceof Boolean) {
1576 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1577 serializer.text(value.toString());
1578 } else if (value == null || value instanceof String) {
1579 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1580 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001581 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001582 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1583 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001584 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001585 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001586 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001587 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001588 serializer.endTag(null, TAG_VALUE);
1589 }
1590 }
1591 serializer.endTag(null, TAG_ENTRY);
1592 }
1593
1594 serializer.endTag(null, TAG_RESTRICTIONS);
1595
1596 serializer.endDocument();
1597 restrictionsFile.finishWrite(fos);
1598 } catch (Exception e) {
1599 restrictionsFile.failWrite(fos);
1600 Slog.e(LOG_TAG, "Error writing application restrictions list");
1601 }
1602 }
1603
1604 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001605 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001606 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001607 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001608 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001609 }
1610 }
1611
1612 @Override
1613 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001614 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001615 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001616 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001617 }
1618 // Not found
1619 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001620 }
1621 }
1622
Amith Yamasani0b285492011-04-14 17:35:23 -07001623 /**
1624 * Caches the list of user ids in an array, adjusting the array size when necessary.
1625 */
Amith Yamasani13593602012-03-22 16:16:17 -07001626 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001627 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001628 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001629 if (!mUsers.valueAt(i).partial) {
1630 num++;
1631 }
1632 }
Amith Yamasani16389312012-10-17 21:20:14 -07001633 final int[] newUsers = new int[num];
1634 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001635 for (int i = 0; i < mUsers.size(); i++) {
1636 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001637 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001638 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001639 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001640 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001641 }
1642
1643 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001644 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001645 * @param userId the user that was just foregrounded
1646 */
1647 public void userForeground(int userId) {
1648 synchronized (mPackagesLock) {
1649 UserInfo user = mUsers.get(userId);
1650 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001651 if (user == null || user.partial) {
1652 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1653 return;
1654 }
1655 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001656 user.lastLoggedInTime = now;
1657 writeUserLocked(user);
1658 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001659 // If this is not a restricted profile and there is no restrictions pin, clean up
1660 // all restrictions files that might have been left behind, else clean up just the
1661 // ones with uninstalled packages
1662 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1663 final long salt = pinState == null ? 0 : pinState.salt;
1664 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001665 }
1666 }
1667
1668 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001669 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001670 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1671 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001672 * @return
1673 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001674 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001675 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001676 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001677 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001678 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001679 break;
1680 }
1681 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001682 }
Amith Yamasani195263742012-08-21 15:40:12 -07001683 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001684 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001685 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001686
Amith Yamasanifc95e702013-09-26 13:20:17 -07001687 private String packageToRestrictionsFileName(String packageName) {
1688 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1689 }
1690
1691 private String restrictionsFileNameToPackage(String fileName) {
1692 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1693 (int) (fileName.length() - XML_SUFFIX.length()));
1694 }
1695
Amith Yamasani920ace02012-09-20 22:15:37 -07001696 @Override
1697 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1698 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1699 != PackageManager.PERMISSION_GRANTED) {
1700 pw.println("Permission Denial: can't dump UserManager from from pid="
1701 + Binder.getCallingPid()
1702 + ", uid=" + Binder.getCallingUid()
1703 + " without permission "
1704 + android.Manifest.permission.DUMP);
1705 return;
1706 }
1707
1708 long now = System.currentTimeMillis();
1709 StringBuilder sb = new StringBuilder();
1710 synchronized (mPackagesLock) {
1711 pw.println("Users:");
1712 for (int i = 0; i < mUsers.size(); i++) {
1713 UserInfo user = mUsers.valueAt(i);
1714 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001715 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001716 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001717 if (user.partial) pw.print(" <partial>");
1718 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001719 pw.print(" Created: ");
1720 if (user.creationTime == 0) {
1721 pw.println("<unknown>");
1722 } else {
1723 sb.setLength(0);
1724 TimeUtils.formatDuration(now - user.creationTime, sb);
1725 sb.append(" ago");
1726 pw.println(sb);
1727 }
1728 pw.print(" Last logged in: ");
1729 if (user.lastLoggedInTime == 0) {
1730 pw.println("<unknown>");
1731 } else {
1732 sb.setLength(0);
1733 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1734 sb.append(" ago");
1735 pw.println(sb);
1736 }
1737 }
1738 }
1739 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001740
1741 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1742 @Override
1743 public void onPackageRemoved(String pkg, int uid) {
1744 final int userId = this.getChangingUserId();
1745 // Package could be disappearing because it is being blocked, so also check if
1746 // it has been uninstalled.
1747 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1748 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1749 cleanAppRestrictionsForPackage(pkg, userId);
1750 }
1751 }
1752 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001753}