blob: 3882769e189a76da2d4061d746f5af247c5d04cf [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 Yamasanie4afaa32014-06-30 14:55:07 +053098 private static final String TAG_GUEST_RESTRICTIONS = "guestRestrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700100 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800101 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800102 private static final String TAG_ENTRY = "entry";
103 private static final String TAG_VALUE = "value";
104 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700105 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800106 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700107
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700108 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
109 private static final String ATTR_TYPE_STRING = "s";
110 private static final String ATTR_TYPE_BOOLEAN = "b";
Amith Yamasani5b5aa402014-06-01 20:10:14 -0700111 private static final String ATTR_TYPE_INTEGER = "i";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700112
Amith Yamasani0b285492011-04-14 17:35:23 -0700113 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700115 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700116
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800117 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700118 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800119
Amith Yamasani634cf312012-10-04 17:34:21 -0700120 private static final int MIN_USER_ID = 10;
121
Amith Yamasani5e486f52013-08-07 11:06:44 -0700122 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700123
Amith Yamasani920ace02012-09-20 22:15:37 -0700124 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
125
Amith Yamasani655d0e22013-06-12 14:19:10 -0700126 // Number of attempts before jumping to the next BACKOFF_TIMES slot
127 private static final int BACKOFF_INC_INTERVAL = 5;
128
129 // Amount of time to force the user to wait before entering the PIN again, after failing
130 // BACKOFF_INC_INTERVAL times.
131 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
132
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530133
Dianne Hackborn4428e172012-08-24 17:43:05 -0700134 private final Context mContext;
135 private final PackageManagerService mPm;
136 private final Object mInstallLock;
137 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700138
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800139 private final Handler mHandler;
140
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700141 private final File mUsersDir;
142 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700143 private final File mBaseUserPath;
144
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800145 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800146 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530147 private final Bundle mGuestRestrictions = new Bundle();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800148
Amith Yamasani655d0e22013-06-12 14:19:10 -0700149 class RestrictionsPinState {
150 long salt;
151 String pinHash;
152 int failedAttempts;
153 long lastAttemptTime;
154 }
155
156 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
157 new SparseArray<RestrictionsPinState>();
158
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800159 /**
160 * Set of user IDs being actively removed. Removed IDs linger in this set
161 * for several seconds to work around a VFS caching issue.
162 */
163 // @GuardedBy("mPackagesLock")
164 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165
Amith Yamasani0b285492011-04-14 17:35:23 -0700166 private int[] mUserIds;
Amith Yamasani2a003292012-08-14 18:25:45 -0700167 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700168 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700169
Jason Monk62062992014-05-06 09:55:28 -0400170 private IAppOpsService mAppOpsService;
171
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700173
Dianne Hackborn4428e172012-08-24 17:43:05 -0700174 public static UserManagerService getInstance() {
175 synchronized (UserManagerService.class) {
176 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700177 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700178 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179
180 /**
181 * Available for testing purposes.
182 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700183 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700184 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700185 }
186
Dianne Hackborn4428e172012-08-24 17:43:05 -0700187 /**
188 * Called by package manager to create the service. This is closely
189 * associated with the package manager, and the given lock is the
190 * package manager's own lock.
191 */
192 UserManagerService(Context context, PackageManagerService pm,
193 Object installLock, Object packagesLock) {
194 this(context, pm, installLock, packagesLock,
195 Environment.getDataDirectory(),
196 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700197 }
198
Dianne Hackborn4428e172012-08-24 17:43:05 -0700199 /**
200 * Available for testing purposes.
201 */
202 private UserManagerService(Context context, PackageManagerService pm,
203 Object installLock, Object packagesLock,
204 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700205 mContext = context;
206 mPm = pm;
207 mInstallLock = installLock;
208 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800209 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700210 synchronized (mInstallLock) {
211 synchronized (mPackagesLock) {
212 mUsersDir = new File(dataDir, USER_INFO_DIR);
213 mUsersDir.mkdirs();
214 // Make zeroth user directory, for services to migrate their files to that location
215 File userZeroDir = new File(mUsersDir, "0");
216 userZeroDir.mkdirs();
217 mBaseUserPath = baseUserPath;
218 FileUtils.setPermissions(mUsersDir.toString(),
219 FileUtils.S_IRWXU|FileUtils.S_IRWXG
220 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
221 -1, -1);
222 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
223 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700224 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700225 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
226 for (int i = 0; i < mUsers.size(); i++) {
227 UserInfo ui = mUsers.valueAt(i);
228 if (ui.partial && i != 0) {
229 partials.add(ui);
230 }
231 }
232 for (int i = 0; i < partials.size(); i++) {
233 UserInfo ui = partials.get(i);
234 Slog.w(LOG_TAG, "Removing partially created user #" + i
235 + " (name=" + ui.name + ")");
236 removeUserStateLocked(ui.id);
237 }
238 sInstance = this;
239 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700240 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700241 }
242
243 void systemReady() {
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700244 mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700245 userForeground(UserHandle.USER_OWNER);
Jason Monk62062992014-05-06 09:55:28 -0400246 mAppOpsService = IAppOpsService.Stub.asInterface(
247 ServiceManager.getService(Context.APP_OPS_SERVICE));
248 for (int i = 0; i < mUserIds.length; ++i) {
249 try {
250 mAppOpsService.setUserRestrictions(mUserRestrictions.get(mUserIds[i]), mUserIds[i]);
251 } catch (RemoteException e) {
252 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
253 }
254 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700255 }
256
257 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700258 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700259 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700260 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700261 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
262 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700263 UserInfo ui = mUsers.valueAt(i);
264 if (ui.partial) {
265 continue;
266 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800267 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700269 }
Amith Yamasani13593602012-03-22 16:16:17 -0700270 }
271 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700272 }
Amith Yamasani13593602012-03-22 16:16:17 -0700273 }
274
Amith Yamasani258848d2012-08-10 17:06:33 -0700275 @Override
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100276 public List<UserInfo> getProfiles(int userId, boolean enabledOnly) {
Amith Yamasani4f582632014-02-19 14:31:52 -0800277 if (userId != UserHandle.getCallingUserId()) {
278 checkManageUsersPermission("getting profiles related to user " + userId);
279 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700280 final long ident = Binder.clearCallingIdentity();
281 try {
282 synchronized (mPackagesLock) {
283 return getProfilesLocked(userId, enabledOnly);
Alexandra Gherghina385124d2014-04-03 13:37:39 +0100284 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700285 } finally {
286 Binder.restoreCallingIdentity(ident);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000287 }
288 }
289
Amith Yamasanibe465322014-04-24 13:45:17 -0700290 /** Assume permissions already checked and caller's identity cleared */
291 private List<UserInfo> getProfilesLocked(int userId, boolean enabledOnly) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700292 UserInfo user = getUserInfoLocked(userId);
293 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
294 for (int i = 0; i < mUsers.size(); i++) {
295 UserInfo profile = mUsers.valueAt(i);
296 if (!isProfileOf(user, profile)) {
297 continue;
298 }
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100299 if (enabledOnly && !profile.isEnabled()) {
300 continue;
Amith Yamasanibe465322014-04-24 13:45:17 -0700301 }
Amith Yamasani70fcf0c2014-07-11 08:40:19 -0700302 if (mRemovingUserIds.get(profile.id)) {
303 continue;
304 }
Amith Yamasanibe465322014-04-24 13:45:17 -0700305 users.add(profile);
306 }
307 return users;
308 }
309
Jessica Hummelbe81c802014-04-22 15:49:22 +0100310 @Override
311 public UserInfo getProfileParent(int userHandle) {
312 checkManageUsersPermission("get the profile parent");
313 synchronized (mPackagesLock) {
314 UserInfo profile = getUserInfoLocked(userHandle);
315 int parentUserId = profile.profileGroupId;
316 if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
317 return null;
318 } else {
319 return getUserInfoLocked(parentUserId);
320 }
321 }
322 }
323
Kenny Guy2a764942014-04-02 13:29:20 +0100324 private boolean isProfileOf(UserInfo user, UserInfo profile) {
325 return user.id == profile.id ||
326 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
327 && user.profileGroupId == profile.profileGroupId);
Kenny Guya52dc3e2014-02-11 15:33:14 +0000328 }
329
330 @Override
Alexandra Gherghinadf35d572014-04-09 13:54:39 +0100331 public void setUserEnabled(int userId) {
332 checkManageUsersPermission("enable user");
333 synchronized (mPackagesLock) {
334 UserInfo info = getUserInfoLocked(userId);
335 if (info != null && !info.isEnabled()) {
336 info.flags ^= UserInfo.FLAG_DISABLED;
337 writeUserLocked(info);
338 }
339 }
340 }
341
342 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700343 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700344 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700345 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700346 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700347 }
348 }
349
Amith Yamasani71e6c692013-03-24 17:39:28 -0700350 @Override
351 public boolean isRestricted() {
352 synchronized (mPackagesLock) {
353 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
354 }
355 }
356
Amith Yamasani195263742012-08-21 15:40:12 -0700357 /*
358 * Should be locked on mUsers before calling this.
359 */
360 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700361 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700362 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800363 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700364 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
365 return null;
366 }
367 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700368 }
369
Amith Yamasani13593602012-03-22 16:16:17 -0700370 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700371 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700372 return ArrayUtils.contains(mUserIds, userId);
373 }
374 }
375
Amith Yamasani258848d2012-08-10 17:06:33 -0700376 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700377 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700378 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700379 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700380 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700381 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700382 if (info == null || info.partial) {
383 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
384 return;
385 }
Amith Yamasani13593602012-03-22 16:16:17 -0700386 if (name != null && !name.equals(info.name)) {
387 info.name = name;
388 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700389 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700390 }
391 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700392 if (changed) {
393 sendUserInfoChangedBroadcast(userId);
394 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700395 }
396
Amith Yamasani258848d2012-08-10 17:06:33 -0700397 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700398 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700399 checkManageUsersPermission("update users");
Jason Monk9a944532014-07-08 09:31:21 -0400400 long ident = Binder.clearCallingIdentity();
401 try {
402 synchronized (mPackagesLock) {
403 UserInfo info = mUsers.get(userId);
404 if (info == null || info.partial) {
405 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
406 return;
407 }
408 writeBitmapLocked(info, bitmap);
409 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700410 }
Jason Monk9a944532014-07-08 09:31:21 -0400411 sendUserInfoChangedBroadcast(userId);
412 } finally {
413 Binder.restoreCallingIdentity(ident);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700414 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700415 }
416
417 private void sendUserInfoChangedBroadcast(int userId) {
418 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
419 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
420 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700421 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700422 }
423
Amith Yamasani258848d2012-08-10 17:06:33 -0700424 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700425 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700426 synchronized (mPackagesLock) {
427 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700428 if (info == null || info.partial) {
429 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
430 return null;
431 }
Nicolas Prevot88cc3462014-05-14 14:51:48 +0100432 int callingGroupId = mUsers.get(UserHandle.getCallingUserId()).profileGroupId;
433 if (callingGroupId == UserInfo.NO_PROFILE_GROUP_ID
434 || callingGroupId != info.profileGroupId) {
435 checkManageUsersPermission("get the icon of a user who is not related");
436 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700437 if (info.iconPath == null) {
438 return null;
439 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700440 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700441 }
442 }
443
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700444 public void makeInitialized(int userId) {
445 checkManageUsersPermission("makeInitialized");
446 synchronized (mPackagesLock) {
447 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700448 if (info == null || info.partial) {
449 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
450 }
451 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700452 info.flags |= UserInfo.FLAG_INITIALIZED;
453 writeUserLocked(info);
454 }
455 }
456 }
457
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800458 @Override
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530459 public Bundle getDefaultGuestRestrictions() {
460 checkManageUsersPermission("getDefaultGuestRestrictions");
461 synchronized (mPackagesLock) {
462 return new Bundle(mGuestRestrictions);
463 }
464 }
465
466 @Override
467 public void setDefaultGuestRestrictions(Bundle restrictions) {
468 checkManageUsersPermission("setDefaultGuestRestrictions");
469 synchronized (mPackagesLock) {
470 mGuestRestrictions.clear();
471 mGuestRestrictions.putAll(restrictions);
472 writeUserListLocked();
473 }
474 }
475
476 @Override
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800477 public Bundle getUserRestrictions(int userId) {
478 // checkManageUsersPermission("getUserRestrictions");
479
480 synchronized (mPackagesLock) {
481 Bundle restrictions = mUserRestrictions.get(userId);
Amith Yamasanibe465322014-04-24 13:45:17 -0700482 return restrictions != null ? new Bundle(restrictions) : new Bundle();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800483 }
484 }
485
486 @Override
487 public void setUserRestrictions(Bundle restrictions, int userId) {
Amith Yamasanibe465322014-04-24 13:45:17 -0700488 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700489 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800490
491 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700492 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800493 mUserRestrictions.get(userId).putAll(restrictions);
Jason Monk62062992014-05-06 09:55:28 -0400494 long token = Binder.clearCallingIdentity();
495 try {
496 mAppOpsService.setUserRestrictions(mUserRestrictions.get(userId), userId);
497 } catch (RemoteException e) {
498 Log.w(LOG_TAG, "Unable to notify AppOpsService of UserRestrictions");
499 } finally {
500 Binder.restoreCallingIdentity(token);
501 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800502 writeUserLocked(mUsers.get(userId));
503 }
504 }
505
Amith Yamasani258848d2012-08-10 17:06:33 -0700506 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700507 * Check if we've hit the limit of how many users can be created.
508 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700509 private boolean isUserLimitReachedLocked() {
Amith Yamasanif584f012014-05-19 17:57:25 -0700510 int aliveUserCount = 0;
511 final int totalUserCount = mUsers.size();
512 // Skip over users being removed
513 for (int i = 0; i < totalUserCount; i++) {
514 UserInfo user = mUsers.valueAt(i);
515 if (!mRemovingUserIds.get(user.id)) {
516 aliveUserCount++;
517 }
518 }
519 return aliveUserCount >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700520 }
521
522 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700523 * Enforces that only the system UID or root's UID or apps that have the
Dianne Hackborn10ad9822014-03-17 11:28:36 -0700524 * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}
Amith Yamasani195263742012-08-21 15:40:12 -0700525 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700526 *
527 * @param message used as message if SecurityException is thrown
528 * @throws SecurityException if the caller is not system or root
529 */
Amith Yamasanibe465322014-04-24 13:45:17 -0700530 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700531 final int uid = Binder.getCallingUid();
Amith Yamasanibe465322014-04-24 13:45:17 -0700532 if (uid != Process.SYSTEM_UID && uid != 0
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400533 && ActivityManager.checkComponentPermission(
534 android.Manifest.permission.MANAGE_USERS,
Amith Yamasanibe465322014-04-24 13:45:17 -0700535 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
536 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
537 }
Emily Bernier7a2b4d12014-04-23 12:51:35 -0400538 }
539
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700540 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700541 try {
542 File dir = new File(mUsersDir, Integer.toString(info.id));
543 File file = new File(dir, USER_PHOTO_FILENAME);
544 if (!dir.exists()) {
545 dir.mkdir();
546 FileUtils.setPermissions(
547 dir.getPath(),
548 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
549 -1, -1);
550 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700551 FileOutputStream os;
552 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700553 info.iconPath = file.getAbsolutePath();
554 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700555 try {
556 os.close();
557 } catch (IOException ioe) {
558 // What the ... !
559 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700560 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700561 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700562 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700563 }
564
Amith Yamasani0b285492011-04-14 17:35:23 -0700565 /**
566 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
567 * cache it elsewhere.
568 * @return the array of user ids.
569 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700570 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700571 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700572 return mUserIds;
573 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700574 }
575
Dianne Hackborn4428e172012-08-24 17:43:05 -0700576 int[] getUserIdsLPr() {
577 return mUserIds;
578 }
579
Amith Yamasani13593602012-03-22 16:16:17 -0700580 private void readUserListLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700581 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700582 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700583 return;
584 }
585 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700586 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700587 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700588 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700589 XmlPullParser parser = Xml.newPullParser();
590 parser.setInput(fis, null);
591 int type;
592 while ((type = parser.next()) != XmlPullParser.START_TAG
593 && type != XmlPullParser.END_DOCUMENT) {
594 ;
595 }
596
597 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700598 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700599 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700600 return;
601 }
602
Amith Yamasani2a003292012-08-14 18:25:45 -0700603 mNextSerialNumber = -1;
604 if (parser.getName().equals(TAG_USERS)) {
605 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
606 if (lastSerialNumber != null) {
607 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
608 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700609 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
610 if (versionNumber != null) {
611 mUserVersion = Integer.parseInt(versionNumber);
612 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700613 }
614
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700615 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530616 if (type == XmlPullParser.START_TAG) {
617 final String name = parser.getName();
618 if (name.equals(TAG_USER)) {
619 String id = parser.getAttributeValue(null, ATTR_ID);
620 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700621
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530622 if (user != null) {
623 mUsers.put(user.id, user);
624 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
625 mNextSerialNumber = user.id + 1;
626 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700627 }
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530628 } else if (name.equals(TAG_GUEST_RESTRICTIONS)) {
629 mGuestRestrictions.clear();
630 readRestrictionsLocked(parser, mGuestRestrictions);
Amith Yamasani258848d2012-08-10 17:06:33 -0700631 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700632 }
633 }
Amith Yamasani13593602012-03-22 16:16:17 -0700634 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700635 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700636 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700637 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700638 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700639 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800640 } finally {
641 if (fis != null) {
642 try {
643 fis.close();
644 } catch (IOException e) {
645 }
646 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700647 }
648 }
649
Amith Yamasani6f34b412012-10-22 18:19:27 -0700650 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800651 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700652 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700653 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700654 int userVersion = mUserVersion;
655 if (userVersion < 1) {
656 // Assign a proper name for the owner, if not initialized correctly before
657 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
658 if ("Primary".equals(user.name)) {
659 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
660 writeUserLocked(user);
661 }
662 userVersion = 1;
663 }
664
Amith Yamasanibc9625052012-11-15 14:39:18 -0800665 if (userVersion < 2) {
666 // Owner should be marked as initialized
667 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
668 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
669 user.flags |= UserInfo.FLAG_INITIALIZED;
670 writeUserLocked(user);
671 }
672 userVersion = 2;
673 }
674
Amith Yamasani350962c2013-08-06 11:18:53 -0700675
Amith Yamasani5e486f52013-08-07 11:06:44 -0700676 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700677 userVersion = 4;
678 }
679
Amith Yamasani6f34b412012-10-22 18:19:27 -0700680 if (userVersion < USER_VERSION) {
681 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
682 + USER_VERSION);
683 } else {
684 mUserVersion = userVersion;
685 writeUserListLocked();
686 }
687 }
688
Amith Yamasani13593602012-03-22 16:16:17 -0700689 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700690 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800691 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700692 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700693 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700694 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700695 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400696 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800697
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500698 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800699 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
700
Amith Yamasani13593602012-03-22 16:16:17 -0700701 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700702
Amith Yamasani13593602012-03-22 16:16:17 -0700703 writeUserListLocked();
704 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700705 }
706
707 /*
708 * Writes the user file in this format:
709 *
710 * <user flags="20039023" id="0">
711 * <name>Primary</name>
712 * </user>
713 */
Amith Yamasani13593602012-03-22 16:16:17 -0700714 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700715 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700716 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700717 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700718 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700719 final BufferedOutputStream bos = new BufferedOutputStream(fos);
720
721 // XmlSerializer serializer = XmlUtils.serializerInstance();
722 final XmlSerializer serializer = new FastXmlSerializer();
723 serializer.setOutput(bos, "utf-8");
724 serializer.startDocument(null, true);
725 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
726
727 serializer.startTag(null, TAG_USER);
728 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700729 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700730 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700731 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
732 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
733 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700734 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
735 if (pinState != null) {
736 if (pinState.salt != 0) {
737 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
738 }
739 if (pinState.pinHash != null) {
740 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
741 }
742 if (pinState.failedAttempts != 0) {
743 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
744 Integer.toString(pinState.failedAttempts));
745 serializer.attribute(null, ATTR_LAST_RETRY_MS,
746 Long.toString(pinState.lastAttemptTime));
747 }
748 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700749 if (userInfo.iconPath != null) {
750 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
751 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700752 if (userInfo.partial) {
753 serializer.attribute(null, ATTR_PARTIAL, "true");
754 }
Kenny Guy2a764942014-04-02 13:29:20 +0100755 if (userInfo.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
756 serializer.attribute(null, ATTR_PROFILE_GROUP_ID,
757 Integer.toString(userInfo.profileGroupId));
Kenny Guya52dc3e2014-02-11 15:33:14 +0000758 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700759
760 serializer.startTag(null, TAG_NAME);
761 serializer.text(userInfo.name);
762 serializer.endTag(null, TAG_NAME);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800763 Bundle restrictions = mUserRestrictions.get(userInfo.id);
764 if (restrictions != null) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530765 writeRestrictionsLocked(serializer, restrictions);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800766 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700767 serializer.endTag(null, TAG_USER);
768
769 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700770 userFile.finishWrite(fos);
771 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700772 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700773 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 }
775 }
776
777 /*
778 * Writes the user list file in this format:
779 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700780 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700781 * <user id="0"></user>
782 * <user id="2"></user>
783 * </users>
784 */
Amith Yamasani13593602012-03-22 16:16:17 -0700785 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700786 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700787 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700788 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700789 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700790 final BufferedOutputStream bos = new BufferedOutputStream(fos);
791
792 // XmlSerializer serializer = XmlUtils.serializerInstance();
793 final XmlSerializer serializer = new FastXmlSerializer();
794 serializer.setOutput(bos, "utf-8");
795 serializer.startDocument(null, true);
796 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
797
798 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700799 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700800 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700801
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530802 serializer.startTag(null, TAG_GUEST_RESTRICTIONS);
803 writeRestrictionsLocked(serializer, mGuestRestrictions);
804 serializer.endTag(null, TAG_GUEST_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700805 for (int i = 0; i < mUsers.size(); i++) {
806 UserInfo user = mUsers.valueAt(i);
807 serializer.startTag(null, TAG_USER);
808 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
809 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700810 }
811
812 serializer.endTag(null, TAG_USERS);
813
814 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700815 userListFile.finishWrite(fos);
816 } catch (Exception e) {
817 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700818 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700819 }
820 }
821
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530822 private void writeRestrictionsLocked(XmlSerializer serializer, Bundle restrictions)
823 throws IOException {
824 serializer.startTag(null, TAG_RESTRICTIONS);
825 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
826 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
827 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
828 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
829 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
830 writeBoolean(serializer, restrictions,
831 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
832 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
833 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
834 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
835 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
836 writeBoolean(serializer, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
837 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_VPN);
838 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
839 writeBoolean(serializer, restrictions, UserManager.DISALLOW_FACTORY_RESET);
840 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADD_USER);
841 writeBoolean(serializer, restrictions, UserManager.ENSURE_VERIFY_APPS);
842 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
843 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
844 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APPS_CONTROL);
845 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
846 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
847 writeBoolean(serializer, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
848 writeBoolean(serializer, restrictions, UserManager.DISALLOW_TELEPHONY);
Jason Monk1c7c3192014-06-26 12:52:18 -0400849 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530850 serializer.endTag(null, TAG_RESTRICTIONS);
851 }
852
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800853 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700854 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700855 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700856 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700857 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700858 long creationTime = 0L;
859 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700860 long salt = 0L;
861 String pinHash = null;
862 int failedAttempts = 0;
Kenny Guy2a764942014-04-02 13:29:20 +0100863 int profileGroupId = UserInfo.NO_PROFILE_GROUP_ID;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700864 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700865 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800866 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700867
868 FileInputStream fis = null;
869 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700870 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700871 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700872 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700873 XmlPullParser parser = Xml.newPullParser();
874 parser.setInput(fis, null);
875 int type;
876 while ((type = parser.next()) != XmlPullParser.START_TAG
877 && type != XmlPullParser.END_DOCUMENT) {
878 ;
879 }
880
881 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700882 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700883 return null;
884 }
885
886 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700887 int storedId = readIntAttribute(parser, ATTR_ID, -1);
888 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700889 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700890 return null;
891 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700892 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
893 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700894 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700895 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
896 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700897 salt = readLongAttribute(parser, ATTR_SALT, 0L);
898 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
899 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
900 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Kenny Guy2a764942014-04-02 13:29:20 +0100901 profileGroupId = readIntAttribute(parser, ATTR_PROFILE_GROUP_ID,
902 UserInfo.NO_PROFILE_GROUP_ID);
903 if (profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
904 // This attribute was added and renamed during development of L.
905 // TODO Remove upgrade path by 1st May 2014
906 profileGroupId = readIntAttribute(parser, "relatedGroupId",
907 UserInfo.NO_PROFILE_GROUP_ID);
908 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700909 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
910 if ("true".equals(valueString)) {
911 partial = true;
912 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700913
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800914 int outerDepth = parser.getDepth();
915 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
916 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
917 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
918 continue;
919 }
920 String tag = parser.getName();
921 if (TAG_NAME.equals(tag)) {
922 type = parser.next();
923 if (type == XmlPullParser.TEXT) {
924 name = parser.getText();
925 }
926 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530927 readRestrictionsLocked(parser, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700928 }
929 }
930 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700931
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700932 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700933 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700934 userInfo.creationTime = creationTime;
935 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700936 userInfo.partial = partial;
Kenny Guy2a764942014-04-02 13:29:20 +0100937 userInfo.profileGroupId = profileGroupId;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800938 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700939 if (salt != 0L) {
940 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
941 if (pinState == null) {
942 pinState = new RestrictionsPinState();
943 mRestrictionsPinStates.put(id, pinState);
944 }
945 pinState.salt = salt;
946 pinState.pinHash = pinHash;
947 pinState.failedAttempts = failedAttempts;
948 pinState.lastAttemptTime = lastAttemptTime;
949 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700950 return userInfo;
951
952 } catch (IOException ioe) {
953 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800954 } finally {
955 if (fis != null) {
956 try {
957 fis.close();
958 } catch (IOException e) {
959 }
960 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700961 }
962 return null;
963 }
964
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530965 private void readRestrictionsLocked(XmlPullParser parser, Bundle restrictions)
966 throws IOException {
967 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
968 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
969 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
970 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
971 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
972 readBoolean(parser, restrictions,
973 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
974 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
975 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
976 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
977 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
978 readBoolean(parser, restrictions, UserManager.DISALLOW_DEBUGGING_FEATURES);
979 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_VPN);
980 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_TETHERING);
981 readBoolean(parser, restrictions, UserManager.DISALLOW_FACTORY_RESET);
982 readBoolean(parser, restrictions, UserManager.DISALLOW_ADD_USER);
983 readBoolean(parser, restrictions, UserManager.ENSURE_VERIFY_APPS);
984 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
985 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
986 readBoolean(parser, restrictions, UserManager.DISALLOW_APPS_CONTROL);
987 readBoolean(parser, restrictions,
988 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
989 readBoolean(parser, restrictions, UserManager.DISALLOW_UNMUTE_MICROPHONE);
990 readBoolean(parser, restrictions, UserManager.DISALLOW_ADJUST_VOLUME);
991 readBoolean(parser, restrictions, UserManager.DISALLOW_TELEPHONY);
Jason Monk1c7c3192014-06-26 12:52:18 -0400992 readBoolean(parser, restrictions, UserManager.DISALLOW_CREATE_WINDOWS);
Amith Yamasanie4afaa32014-06-30 14:55:07 +0530993 }
994
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800995 private void readBoolean(XmlPullParser parser, Bundle restrictions,
996 String restrictionKey) {
997 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700998 if (value != null) {
999 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
1000 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001001 }
1002
1003 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
1004 throws IOException {
1005 if (restrictions.containsKey(restrictionKey)) {
1006 xml.attribute(null, restrictionKey,
1007 Boolean.toString(restrictions.getBoolean(restrictionKey)));
1008 }
1009 }
1010
Amith Yamasani920ace02012-09-20 22:15:37 -07001011 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
1012 String valueString = parser.getAttributeValue(null, attr);
1013 if (valueString == null) return defaultValue;
1014 try {
1015 return Integer.parseInt(valueString);
1016 } catch (NumberFormatException nfe) {
1017 return defaultValue;
1018 }
1019 }
1020
1021 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
1022 String valueString = parser.getAttributeValue(null, attr);
1023 if (valueString == null) return defaultValue;
1024 try {
1025 return Long.parseLong(valueString);
1026 } catch (NumberFormatException nfe) {
1027 return defaultValue;
1028 }
1029 }
1030
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001031 private boolean isPackageInstalled(String pkg, int userId) {
1032 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
1033 PackageManager.GET_UNINSTALLED_PACKAGES,
1034 userId);
1035 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
1036 return false;
1037 }
1038 return true;
1039 }
1040
Amith Yamasanib82add22013-07-09 11:24:44 -07001041 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001042 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
1043 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -07001044 * Does not do any permissions checking.
1045 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001046 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -07001047 synchronized (mPackagesLock) {
1048 File dir = Environment.getUserSystemDirectory(userId);
1049 String[] files = dir.list();
1050 if (files == null) return;
1051 for (String fileName : files) {
1052 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
1053 File resFile = new File(dir, fileName);
1054 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001055 if (all) {
1056 resFile.delete();
1057 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -07001058 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001059 if (!isPackageInstalled(pkg, userId)) {
1060 resFile.delete();
1061 }
1062 }
Amith Yamasanib82add22013-07-09 11:24:44 -07001063 }
1064 }
1065 }
1066 }
1067 }
1068
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001069 /**
1070 * Removes the app restrictions file for a specific package and user id, if it exists.
1071 */
1072 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
1073 synchronized (mPackagesLock) {
1074 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -07001075 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001076 if (resFile.exists()) {
1077 resFile.delete();
1078 }
1079 }
1080 }
1081
Kenny Guya52dc3e2014-02-11 15:33:14 +00001082 @Override
Kenny Guy2a764942014-04-02 13:29:20 +01001083 public UserInfo createProfileForUser(String name, int flags, int userId) {
Kenny Guya52dc3e2014-02-11 15:33:14 +00001084 checkManageUsersPermission("Only the system can create users");
Kenny Guy2a764942014-04-02 13:29:20 +01001085 if (userId != UserHandle.USER_OWNER) {
1086 Slog.w(LOG_TAG, "Only user owner can have profiles");
Kenny Guya52dc3e2014-02-11 15:33:14 +00001087 return null;
1088 }
Kenny Guy2a764942014-04-02 13:29:20 +01001089 return createUserInternal(name, flags, userId);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001090 }
1091
Amith Yamasani258848d2012-08-10 17:06:33 -07001092 @Override
Amith Yamasani13593602012-03-22 16:16:17 -07001093 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001094 checkManageUsersPermission("Only the system can create users");
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001095 return createUserInternal(name, flags, UserHandle.USER_NULL);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001096 }
Amith Yamasanifaea76f2012-09-11 10:59:48 -07001097
Jessica Hummelbe81c802014-04-22 15:49:22 +01001098 private UserInfo createUserInternal(String name, int flags, int parentId) {
Julia Reynolds75175022014-06-26 16:35:00 -04001099 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1100 UserManager.DISALLOW_ADD_USER, false)) {
1101 Log.w(LOG_TAG, "Cannot add user. DISALLOW_ADD_USER is enabled.");
1102 return null;
1103 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001104 final long ident = Binder.clearCallingIdentity();
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001105 UserInfo userInfo = null;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001106 try {
1107 synchronized (mInstallLock) {
1108 synchronized (mPackagesLock) {
Jessica Hummelbe81c802014-04-22 15:49:22 +01001109 UserInfo parent = null;
1110 if (parentId != UserHandle.USER_NULL) {
1111 parent = getUserInfoLocked(parentId);
1112 if (parent == null) return null;
Nicolas Prevotc6d033e2014-02-27 13:11:09 +00001113 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001114 if (isUserLimitReachedLocked()) return null;
1115 int userId = getNextAvailableIdLocked();
1116 userInfo = new UserInfo(userId, name, null, flags);
1117 File userPath = new File(mBaseUserPath, Integer.toString(userId));
1118 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -07001119 long now = System.currentTimeMillis();
1120 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001121 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -07001122 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001123 mUsers.put(userId, userInfo);
1124 writeUserListLocked();
Jessica Hummelbe81c802014-04-22 15:49:22 +01001125 if (parent != null) {
1126 if (parent.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
1127 parent.profileGroupId = parent.id;
1128 writeUserLocked(parent);
Kenny Guya52dc3e2014-02-11 15:33:14 +00001129 }
Jessica Hummelbe81c802014-04-22 15:49:22 +01001130 userInfo.profileGroupId = parent.profileGroupId;
Kenny Guya52dc3e2014-02-11 15:33:14 +00001131 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001132 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001133 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001134 userInfo.partial = false;
1135 writeUserLocked(userInfo);
1136 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001137 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -05001138 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001139 }
Dianne Hackborn4428e172012-08-24 17:43:05 -07001140 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001141 if (userInfo != null) {
1142 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
1143 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
1144 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
1145 android.Manifest.permission.MANAGE_USERS);
1146 }
1147 } finally {
1148 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -07001149 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001150 return userInfo;
1151 }
1152
Amith Yamasani0b285492011-04-14 17:35:23 -07001153 /**
1154 * Removes a user and all data directories created for that user. This method should be called
1155 * after the user's processes have been terminated.
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001156 * @param userHandle the user's id
Amith Yamasani0b285492011-04-14 17:35:23 -07001157 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001158 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001159 checkManageUsersPermission("Only the system can remove users");
Julia Reynolds4ac5f852014-06-23 17:38:51 -04001160 if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
1161 UserManager.DISALLOW_REMOVE_USER, false)) {
1162 Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
1163 return false;
1164 }
1165
Kenny Guyee58b4f2014-05-23 15:19:53 +01001166 long ident = Binder.clearCallingIdentity();
1167 try {
1168 final UserInfo user;
1169 synchronized (mPackagesLock) {
1170 user = mUsers.get(userHandle);
Kenny Guy17c9d692014-06-13 13:51:42 +01001171 if (userHandle == 0 || user == null || mRemovingUserIds.get(userHandle)) {
Kenny Guyee58b4f2014-05-23 15:19:53 +01001172 return false;
1173 }
1174 mRemovingUserIds.put(userHandle, true);
1175 try {
1176 mAppOpsService.removeUser(userHandle);
1177 } catch (RemoteException e) {
1178 Log.w(LOG_TAG, "Unable to notify AppOpsService of removing user", e);
1179 }
1180 // Set this to a partially created user, so that the user will be purged
1181 // on next startup, in case the runtime stops now before stopping and
1182 // removing the user completely.
1183 user.partial = true;
1184 // Mark it as disabled, so that it isn't returned any more when
1185 // profiles are queried.
1186 user.flags |= UserInfo.FLAG_DISABLED;
1187 writeUserLocked(user);
1188 }
1189
1190 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1191 && user.isManagedProfile()) {
1192 // Send broadcast to notify system that the user removed was a
1193 // managed user.
1194 sendProfileRemovedBroadcast(user.profileGroupId, user.id);
1195 }
1196
1197 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
1198 int res;
1199 try {
1200 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1201 new IStopUserCallback.Stub() {
1202 @Override
1203 public void userStopped(int userId) {
1204 finishRemoveUser(userId);
1205 }
1206 @Override
1207 public void userStopAborted(int userId) {
1208 }
1209 });
1210 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001211 return false;
1212 }
Kenny Guyee58b4f2014-05-23 15:19:53 +01001213 return res == ActivityManager.USER_OP_SUCCESS;
1214 } finally {
1215 Binder.restoreCallingIdentity(ident);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001216 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001217 }
1218
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001219 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001220 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001221 // Let other services shutdown any activity and clean up their state before completely
1222 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001223 long ident = Binder.clearCallingIdentity();
1224 try {
1225 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1226 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001227 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1228 android.Manifest.permission.MANAGE_USERS,
1229
1230 new BroadcastReceiver() {
1231 @Override
1232 public void onReceive(Context context, Intent intent) {
1233 if (DBG) {
1234 Slog.i(LOG_TAG,
1235 "USER_REMOVED broadcast sent, cleaning up user data "
1236 + userHandle);
1237 }
1238 new Thread() {
1239 public void run() {
1240 synchronized (mInstallLock) {
1241 synchronized (mPackagesLock) {
1242 removeUserStateLocked(userHandle);
1243 }
1244 }
1245 }
1246 }.start();
1247 }
1248 },
1249
1250 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001251 } finally {
1252 Binder.restoreCallingIdentity(ident);
1253 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001254 }
1255
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001256 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001257 // Cleanup package manager settings
1258 mPm.cleanUpUserLILPw(userHandle);
1259
1260 // Remove this user from the list
1261 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001262
1263 // Have user ID linger for several seconds to let external storage VFS
1264 // cache entries expire. This must be greater than the 'entry_valid'
1265 // timeout used by the FUSE daemon.
1266 mHandler.postDelayed(new Runnable() {
1267 @Override
1268 public void run() {
1269 synchronized (mPackagesLock) {
1270 mRemovingUserIds.delete(userHandle);
1271 }
1272 }
1273 }, MINUTE_IN_MILLIS);
1274
Amith Yamasani655d0e22013-06-12 14:19:10 -07001275 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001276 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001277 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001278 userFile.delete();
1279 // Update the user list
1280 writeUserListLocked();
1281 updateUserIdsLocked();
1282 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1283 }
1284
Amith Yamasani61f57372012-08-31 12:12:28 -07001285 private void removeDirectoryRecursive(File parent) {
1286 if (parent.isDirectory()) {
1287 String[] files = parent.list();
1288 for (String filename : files) {
1289 File child = new File(parent, filename);
1290 removeDirectoryRecursive(child);
1291 }
1292 }
1293 parent.delete();
1294 }
1295
Kenny Guyf8d3a232014-05-15 16:09:52 +01001296 private void sendProfileRemovedBroadcast(int parentUserId, int removedUserId) {
Adam Connors7b66ed52014-04-14 11:58:10 +01001297 Intent managedProfileIntent = new Intent(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Adam Connorsd4b584e2014-06-09 13:55:47 +01001298 managedProfileIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
1299 Intent.FLAG_RECEIVER_FOREGROUND);
Kenny Guyf8d3a232014-05-15 16:09:52 +01001300 managedProfileIntent.putExtra(Intent.EXTRA_USER, new UserHandle(removedUserId));
1301 mContext.sendBroadcastAsUser(managedProfileIntent, new UserHandle(parentUserId), null);
Adam Connors7b66ed52014-04-14 11:58:10 +01001302 }
1303
Amith Yamasani2a003292012-08-14 18:25:45 -07001304 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001305 public Bundle getApplicationRestrictions(String packageName) {
1306 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1307 }
1308
1309 @Override
1310 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001311 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001312 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001313 checkManageUsersPermission("Only system can get restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001314 }
1315 synchronized (mPackagesLock) {
1316 // Read the restrictions from XML
1317 return readApplicationRestrictionsLocked(packageName, userId);
1318 }
1319 }
1320
1321 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001322 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001323 int userId) {
1324 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001325 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanibe465322014-04-24 13:45:17 -07001326 checkManageUsersPermission("Only system can set restrictions for other users/apps");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001327 }
1328 synchronized (mPackagesLock) {
1329 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001330 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001331 }
Robin Lee66e5d962014-04-09 16:44:21 +01001332
1333 // Notify package of changes via an intent - only sent to explicitly registered receivers.
1334 Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
1335 changeIntent.setPackage(packageName);
1336 changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1337 mContext.sendBroadcastAsUser(changeIntent, new UserHandle(userId));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001338 }
1339
Amith Yamasani655d0e22013-06-12 14:19:10 -07001340 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001341 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001342 checkManageUsersPermission("Only system can modify the restrictions pin");
1343 int userId = UserHandle.getCallingUserId();
1344 synchronized (mPackagesLock) {
1345 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1346 if (pinState == null) {
1347 pinState = new RestrictionsPinState();
1348 }
1349 if (newPin == null) {
1350 pinState.salt = 0;
1351 pinState.pinHash = null;
1352 } else {
1353 try {
1354 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1355 } catch (NoSuchAlgorithmException e) {
1356 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1357 }
1358 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1359 pinState.failedAttempts = 0;
1360 }
1361 mRestrictionsPinStates.put(userId, pinState);
1362 writeUserLocked(mUsers.get(userId));
1363 }
1364 return true;
1365 }
1366
1367 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001368 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001369 checkManageUsersPermission("Only system can verify the restrictions pin");
1370 int userId = UserHandle.getCallingUserId();
1371 synchronized (mPackagesLock) {
1372 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1373 // If there's no pin set, return error code
1374 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1375 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1376 } else if (pin == null) {
1377 // If just checking if user can be prompted, return remaining time
1378 int waitTime = getRemainingTimeForPinAttempt(pinState);
1379 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1380 return waitTime;
1381 } else {
1382 int waitTime = getRemainingTimeForPinAttempt(pinState);
1383 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1384 if (waitTime > 0) {
1385 return waitTime;
1386 }
1387 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1388 pinState.failedAttempts = 0;
1389 writeUserLocked(mUsers.get(userId));
1390 return UserManager.PIN_VERIFICATION_SUCCESS;
1391 } else {
1392 pinState.failedAttempts++;
1393 pinState.lastAttemptTime = System.currentTimeMillis();
1394 writeUserLocked(mUsers.get(userId));
1395 return waitTime;
1396 }
1397 }
1398 }
1399 }
1400
1401 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1402 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1403 BACKOFF_TIMES.length - 1);
1404 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1405 BACKOFF_TIMES[backoffIndex] : 0;
1406 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1407 0);
1408 }
1409
1410 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001411 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001412 int userId = UserHandle.getCallingUserId();
1413 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001414 return hasRestrictionsPinLocked(userId);
1415 }
1416 }
1417
1418 private boolean hasRestrictionsPinLocked(int userId) {
1419 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1420 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1421 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001422 }
1423 return true;
1424 }
1425
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001426 @Override
1427 public void removeRestrictions() {
Amith Yamasanibe465322014-04-24 13:45:17 -07001428 checkManageUsersPermission("Only system can remove restrictions");
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001429 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001430 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001431 }
1432
Amith Yamasani5e486f52013-08-07 11:06:44 -07001433 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001434 synchronized (mPackagesLock) {
1435 // Remove all user restrictions
1436 setUserRestrictions(new Bundle(), userHandle);
1437 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001438 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001439 // Remove any app restrictions
1440 cleanAppRestrictions(userHandle, true);
1441 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001442 if (unblockApps) {
1443 unblockAllAppsForUser(userHandle);
1444 }
1445 }
1446
1447 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001448 mHandler.post(new Runnable() {
1449 @Override
1450 public void run() {
1451 List<ApplicationInfo> apps =
1452 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1453 userHandle).getList();
1454 final long ident = Binder.clearCallingIdentity();
1455 try {
1456 for (ApplicationInfo appInfo : apps) {
1457 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1458 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1459 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1460 userHandle);
1461 }
1462 }
1463 } finally {
1464 Binder.restoreCallingIdentity(ident);
1465 }
1466 }
1467 });
1468 }
1469
Amith Yamasani655d0e22013-06-12 14:19:10 -07001470 /*
1471 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1472 * Not the most secure, but it is at least a second level of protection. First level is that
1473 * the file is in a location only readable by the system process.
1474 * @param password the password.
1475 * @param salt the randomly generated salt
1476 * @return the hash of the pattern in a String.
1477 */
1478 private String passwordToHash(String password, long salt) {
1479 if (password == null) {
1480 return null;
1481 }
1482 String algo = null;
1483 String hashed = salt + password;
1484 try {
1485 byte[] saltedPassword = (password + salt).getBytes();
1486 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1487 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1488 hashed = toHex(sha1) + toHex(md5);
1489 } catch (NoSuchAlgorithmException e) {
1490 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1491 }
1492 return hashed;
1493 }
1494
1495 private static String toHex(byte[] ary) {
1496 final String hex = "0123456789ABCDEF";
1497 String ret = "";
1498 for (int i = 0; i < ary.length; i++) {
1499 ret += hex.charAt((ary[i] >> 4) & 0xf);
1500 ret += hex.charAt(ary[i] & 0xf);
1501 }
1502 return ret;
1503 }
1504
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001505 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001506 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001507 try {
1508 return mContext.getPackageManager().getApplicationInfo(packageName,
1509 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1510 } catch (NameNotFoundException nnfe) {
1511 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001512 } finally {
1513 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001514 }
1515 }
1516
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001517 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001518 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001519 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001520 final ArrayList<String> values = new ArrayList<String>();
1521
1522 FileInputStream fis = null;
1523 try {
1524 AtomicFile restrictionsFile =
1525 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001526 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001527 fis = restrictionsFile.openRead();
1528 XmlPullParser parser = Xml.newPullParser();
1529 parser.setInput(fis, null);
1530 int type;
1531 while ((type = parser.next()) != XmlPullParser.START_TAG
1532 && type != XmlPullParser.END_DOCUMENT) {
1533 ;
1534 }
1535
1536 if (type != XmlPullParser.START_TAG) {
1537 Slog.e(LOG_TAG, "Unable to read restrictions file "
1538 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001539 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001540 }
1541
1542 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1543 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1544 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001545 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001546 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1547 if (multiple != null) {
1548 int count = Integer.parseInt(multiple);
1549 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1550 if (type == XmlPullParser.START_TAG
1551 && parser.getName().equals(TAG_VALUE)) {
1552 values.add(parser.nextText().trim());
1553 count--;
1554 }
1555 }
1556 String [] valueStrings = new String[values.size()];
1557 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001558 restrictions.putStringArray(key, valueStrings);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001559 } else {
1560 String value = parser.nextText().trim();
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001561 if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1562 restrictions.putBoolean(key, Boolean.parseBoolean(value));
1563 } else if (ATTR_TYPE_INTEGER.equals(valType)) {
1564 restrictions.putInt(key, Integer.parseInt(value));
1565 } else {
1566 restrictions.putString(key, value);
1567 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001568 }
1569 }
1570 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001571 } catch (IOException ioe) {
1572 } catch (XmlPullParserException pe) {
1573 } finally {
1574 if (fis != null) {
1575 try {
1576 fis.close();
1577 } catch (IOException e) {
1578 }
1579 }
1580 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001581 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001582 }
1583
1584 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001585 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001586 FileOutputStream fos = null;
1587 AtomicFile restrictionsFile = new AtomicFile(
1588 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001589 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001590 try {
1591 fos = restrictionsFile.startWrite();
1592 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1593
1594 // XmlSerializer serializer = XmlUtils.serializerInstance();
1595 final XmlSerializer serializer = new FastXmlSerializer();
1596 serializer.setOutput(bos, "utf-8");
1597 serializer.startDocument(null, true);
1598 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1599
1600 serializer.startTag(null, TAG_RESTRICTIONS);
1601
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001602 for (String key : restrictions.keySet()) {
1603 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001604 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001605 serializer.attribute(null, ATTR_KEY, key);
1606
1607 if (value instanceof Boolean) {
1608 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1609 serializer.text(value.toString());
Amith Yamasani5b5aa402014-06-01 20:10:14 -07001610 } else if (value instanceof Integer) {
1611 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_INTEGER);
1612 serializer.text(value.toString());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001613 } else if (value == null || value instanceof String) {
1614 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1615 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001616 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001617 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1618 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001619 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001620 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001621 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001622 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001623 serializer.endTag(null, TAG_VALUE);
1624 }
1625 }
1626 serializer.endTag(null, TAG_ENTRY);
1627 }
1628
1629 serializer.endTag(null, TAG_RESTRICTIONS);
1630
1631 serializer.endDocument();
1632 restrictionsFile.finishWrite(fos);
1633 } catch (Exception e) {
1634 restrictionsFile.failWrite(fos);
1635 Slog.e(LOG_TAG, "Error writing application restrictions list");
1636 }
1637 }
1638
1639 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001640 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001641 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001642 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001643 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001644 }
1645 }
1646
1647 @Override
1648 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001649 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001650 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001651 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001652 }
1653 // Not found
1654 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001655 }
1656 }
1657
Amith Yamasani0b285492011-04-14 17:35:23 -07001658 /**
1659 * Caches the list of user ids in an array, adjusting the array size when necessary.
1660 */
Amith Yamasani13593602012-03-22 16:16:17 -07001661 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001662 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001663 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001664 if (!mUsers.valueAt(i).partial) {
1665 num++;
1666 }
1667 }
Amith Yamasani16389312012-10-17 21:20:14 -07001668 final int[] newUsers = new int[num];
1669 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001670 for (int i = 0; i < mUsers.size(); i++) {
1671 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001672 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001673 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001674 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001675 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001676 }
1677
1678 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001679 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001680 * @param userId the user that was just foregrounded
1681 */
1682 public void userForeground(int userId) {
1683 synchronized (mPackagesLock) {
1684 UserInfo user = mUsers.get(userId);
1685 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001686 if (user == null || user.partial) {
1687 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1688 return;
1689 }
1690 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001691 user.lastLoggedInTime = now;
1692 writeUserLocked(user);
1693 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001694 // If this is not a restricted profile and there is no restrictions pin, clean up
1695 // all restrictions files that might have been left behind, else clean up just the
1696 // ones with uninstalled packages
1697 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1698 final long salt = pinState == null ? 0 : pinState.salt;
1699 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001700 }
1701 }
1702
1703 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001704 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001705 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1706 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001707 * @return
1708 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001709 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001710 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001711 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001712 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001713 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001714 break;
1715 }
1716 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001717 }
Amith Yamasani195263742012-08-21 15:40:12 -07001718 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001719 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001720 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001721
Amith Yamasanifc95e702013-09-26 13:20:17 -07001722 private String packageToRestrictionsFileName(String packageName) {
1723 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1724 }
1725
1726 private String restrictionsFileNameToPackage(String fileName) {
1727 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1728 (int) (fileName.length() - XML_SUFFIX.length()));
1729 }
1730
Amith Yamasani920ace02012-09-20 22:15:37 -07001731 @Override
1732 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1733 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1734 != PackageManager.PERMISSION_GRANTED) {
1735 pw.println("Permission Denial: can't dump UserManager from from pid="
1736 + Binder.getCallingPid()
1737 + ", uid=" + Binder.getCallingUid()
1738 + " without permission "
1739 + android.Manifest.permission.DUMP);
1740 return;
1741 }
1742
1743 long now = System.currentTimeMillis();
1744 StringBuilder sb = new StringBuilder();
1745 synchronized (mPackagesLock) {
1746 pw.println("Users:");
1747 for (int i = 0; i < mUsers.size(); i++) {
1748 UserInfo user = mUsers.valueAt(i);
1749 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001750 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001751 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001752 if (user.partial) pw.print(" <partial>");
1753 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001754 pw.print(" Created: ");
1755 if (user.creationTime == 0) {
1756 pw.println("<unknown>");
1757 } else {
1758 sb.setLength(0);
1759 TimeUtils.formatDuration(now - user.creationTime, sb);
1760 sb.append(" ago");
1761 pw.println(sb);
1762 }
1763 pw.print(" Last logged in: ");
1764 if (user.lastLoggedInTime == 0) {
1765 pw.println("<unknown>");
1766 } else {
1767 sb.setLength(0);
1768 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1769 sb.append(" ago");
1770 pw.println(sb);
1771 }
1772 }
1773 }
1774 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001775
1776 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1777 @Override
1778 public void onPackageRemoved(String pkg, int uid) {
1779 final int userId = this.getChangingUserId();
1780 // Package could be disappearing because it is being blocked, so also check if
1781 // it has been uninstalled.
1782 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1783 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1784 cleanAppRestrictionsForPackage(pkg, userId);
1785 }
1786 }
1787 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001788}